<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pavel Polívka on Medium]]></title>
        <description><![CDATA[Stories by Pavel Polívka on Medium]]></description>
        <link>https://medium.com/@polivka-pavel?source=rss-82ff2277907f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xBIMiT4dWKKrxk5ZvDJmQw.jpeg</url>
            <title>Stories by Pavel Polívka on Medium</title>
            <link>https://medium.com/@polivka-pavel?source=rss-82ff2277907f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:02:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@polivka-pavel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Follow me on DEV.to]]></title>
            <link>https://polivka-pavel.medium.com/follow-me-on-dev-to-3e0983969903?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e0983969903</guid>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 10:28:13 GMT</pubDate>
            <atom:updated>2026-04-09T10:28:13.447Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Looking for my latest content?</em></p><p><em>I’ve moved my primary publishing to DEV.to, where I’ve published 53 articles on code review, engineering leadership, and career transitions. I’m a DEV Top 7 author there.</em></p><p><em>Follow me at </em><a href="https://dev.to/pavel_polivka"><em>https://dev.to/pavel_polivka</em></a><em> to stay up to date.</em></p><p><em>I still cross-post selected articles here on Medium, but new content goes to DEV.to first.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e0983969903" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting the Location Header from the HTTP Redirect Response]]></title>
            <link>https://javascript.plainenglish.io/getting-the-location-header-from-the-http-redirect-response-bd5d4e209d33?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5d4e209d33</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 20:24:45 GMT</pubDate>
            <atom:updated>2025-01-06T05:22:48.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QIHDTbl6m53C7tra" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I needed to determine the final redirect URL of any user-provided link in one of my side projects. At first, it seemed like a straightforward task: just fetch the URL, check the response, and grab the Location header if there was a redirect. However, things got more complicated due to CORS restrictions and other browser limitations. Here’s a quick recap of the solutions I tried and how I finally got it working with a proxy function on Vercel.</p><h3><strong>Attempt #1: Plain Fetch with { redirect: ‘manual’ }</strong></h3><p>My initial thought was: “I’ll just make a fetch call and not follow the redirect automatically.” Something like:</p><pre>async function getRedirectLocation(url) {<br>  try {<br>    const response = await fetch(url, {<br>      method: &#39;GET&#39;,<br>      redirect: &#39;manual&#39;,<br>    });<br>    // Theoretically, `response.headers.get(&#39;Location&#39;)` should give the redirect URL.<br>    // But you might run into CORS issues here.<br>    const location = response.headers.get(&#39;Location&#39;);<br>    console.log(&#39;Location header:&#39;, location);<br>  } catch (error) {<br>    console.error(&#39;Error fetching URL:&#39;, error);<br>  }<br>}</pre><p>This approach quickly failed due to CORS (Cross-Origin Resource Sharing) restrictions, because many servers do not include the appropriate headers to let the browser expose the Location header to frontend code.</p><h4><strong>Quick Note on CORS</strong></h4><p><strong>CORS</strong> stands for <em>Cross-Origin Resource Sharing</em>, a security feature in modern browsers that restricts how websites hosted on different domains can access each other’s data. Without proper headers (like Access-Control-Allow-Origin: *), the browser won’t let you read certain response headers or even make some requests. This is meant to protect users, but can be a frustrating obstacle for developers.</p><h3><strong>Attempt #2: Service Worker Interception</strong></h3><p>Since the plain fetch approach was thwarted by CORS, I decided to intercept the request in a <strong>service worker</strong>. The idea was to add a custom header (e.g., X-Fetch-Location) to my requests and handle it within the service worker to see if I could get around the restriction. Something like:</p><p><strong>Main Script</strong></p><pre>// In your main application script<br>navigator.serviceWorker.register(&#39;service-worker.js&#39;)<br>  .then(() =&gt; {<br>    console.log(&#39;Service Worker registered!&#39;);<br>  });<br><br>async function getRedirectLocationUsingSW(url) {<br>  try {<br>    const response = await fetch(url, {<br>      method: &#39;GET&#39;,<br>      headers: {<br>        &#39;X-Fetch-Location&#39;: &#39;true&#39;,<br>      },<br>      redirect: &#39;manual&#39;<br>    });<br>    const location = response.headers.get(&#39;Location&#39;);<br>    console.log(&#39;Location header via SW attempt:&#39;, location);<br>  } catch (error) {<br>    console.error(&#39;Error:&#39;, error);<br>  }<br>}</pre><p><strong>Service Worker</strong></p><pre>// service-worker.js<br>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  const request = event.request;<br>  <br>  // Check if our custom header is present<br>  if (request.headers.get(&#39;X-Fetch-Location&#39;)) {<br>    // We could attempt special handling or manipulate the response.<br>    // But, unfortunately, if the server does not provide CORS headers<br>    // exposing &#39;Location&#39;, we still can&#39;t read it.<br>  }<br>  <br>  event.respondWith(fetch(request));<br>});</pre><p>While intercepting requests in the service worker can help in many scenarios (e.g., caching strategies or manipulating requests), <strong>it doesn’t magically bypass CORS</strong>. The browser’s same-origin policy restrictions are still in place for reading headers. So… still stuck.</p><p><em>(Why does it have to be so hard?)</em></p><h3><strong>The Final Solution: A Proxy Function on Vercel</strong></h3><p>When it comes to retrieving something that a browser won’t let you read directly, a classic approach is to do it server-side and then return the results to your client. Essentially, you create a proxy. This is often the path of least resistance when dealing with CORS nightmares.</p><h4><strong>Step 1: Create a Vercel Function</strong></h4><p>With Vercel, you can quickly spin up a serverless function that makes the HTTP request for you, checks for the redirect Location header, and returns it in a CORS-friendly manner.</p><p><strong>File structure</strong> (in a simple Node.js project):</p><pre>/api<br>  └─ get-redirect.js</pre><p><strong>/api/get-redirect.js:</strong></p><pre>export default async function handler(req, res) {<br>  const { url } = req.query;<br>  <br>  if (!url) {<br>    return res.status(400).json({ error: &#39;No URL provided&#39; });<br>  }<br><br>  try {<br>    // Use a Node fetch or Axios to get the redirect info<br>    const response = await fetch(url, { redirect: &#39;manual&#39; });<br>    const location = response.headers.get(&#39;location&#39;);<br>    <br>    // Return the location in a CORS-friendly way<br>    res.setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>    res.status(200).json({ location });<br>  } catch (error) {<br>    console.error(error);<br>    res.status(500).json({ error: &#39;Something went wrong&#39; });<br>  }<br>}</pre><h4><strong>Step 2: Deploy to Vercel (or run locally with the CLI)</strong></h4><p><strong>1. Install the Vercel CLI</strong>:</p><pre>npm install -g vercel</pre><p>2. <strong>Login to Vercel</strong> (if you haven’t already):</p><pre>vercel login</pre><p>3. <strong>Deploy your project</strong>:</p><pre>vercel</pre><p>This will guide you through setting up and deploying your function. Once deployed, you’ll get a URL like:</p><pre>https://your-project-name.vercel.app/api/get-redirect?url=https://www.example.com</pre><h4><strong>Step 3: Use the Proxy in Your Client-Side Code</strong></h4><p>In your client, all you need to do is call your new function endpoint instead of directly fetching the user’s URL:</p><pre>async function getRedirectLocation(url) {<br>  try {<br>    const response = await fetch(<br>      `https://your-project-name.vercel.app/api/get-redirect?url=${encodeURIComponent(url)}`<br>    );<br>    const data = await response.json();<br>    console.log(&#39;Location header (via proxy):&#39;, data.location);<br>  } catch (error) {<br>    console.error(&#39;Error calling proxy:&#39;, error);<br>  }<br>}</pre><p>Now, since your browser is contacting your own domain (the Vercel function), you control the response headers. You can set them to allow cross-origin access from anywhere (or restricted domains if you prefer). Your serverless function can read the Location header from the remote server — CORS doesn’t apply on a server-to-server request the same way it does in the browser.</p><h3><strong>Conclusion</strong></h3><p>What started out as “just get the Location header” led me through a labyrinth of CORS errors, half solutions, and service-worker experiments. In the end, setting up a simple proxy function on Vercel (or any server-side environment) was the most reliable and straightforward method:</p><ol><li><strong>Browser fetch →</strong> Request to <strong>Vercel function</strong></li><li><strong>Vercel function →</strong> Actually fetch the original URL with redirect: ‘manual’</li><li><strong>Read the </strong>Location<strong> header</strong> on the server, return it to the browser.</li></ol><p>Sure, it seems like a lot of steps for something so simple, but such is the reality of working with CORS and modern web security. The good news is that once you have a proxy set up, you can also perform other manipulations or checks on the server side if needed.</p><p>Happy coding — and may your redirects always lead you exactly where you need to go!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5d4e209d33" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/getting-the-location-header-from-the-http-redirect-response-bd5d4e209d33">Getting the Location Header from the HTTP Redirect Response</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a responsive animated hamburger menu with Angular Material]]></title>
            <link>https://javascript.plainenglish.io/making-a-responsive-animated-hamburger-menu-with-angular-material-f822cdca3ac7?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f822cdca3ac7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 21:08:04 GMT</pubDate>
            <atom:updated>2024-12-19T11:52:15.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7G5h08b9pk9NuzzUMncZg.gif" /></figure><p>In modern web design, the hamburger menu icon has become a universal symbol for toggling navigational panels — particularly on mobile devices. If you’re building an Angular application and want to ensure a consistent, responsive UI, Angular Material provides a robust set of components and styling conventions that can help you build a sleek, intuitive hamburger menu.</p><p>In this article, we’ll walk you through how to create a hamburger menu button that toggles a responsive side navigation drawer using Angular Material’s built-in components. We’ll discuss how to set up Angular Material, implement a responsive layout, and handle navigation states. By the end, you’ll have a working example and a link to a GitHub repository where you can review the complete code.</p><h4><strong>Prerequisites</strong></h4><ul><li><strong>Angular CLI</strong>: Make sure you have the Angular CLI installed. If not, run npm install -g @angular/cli.</li><li><strong>Basic Understanding of Angular</strong>: Familiarity with components, modules, and services.</li><li><strong>Node.js and NPM</strong>: Ensure you have Node.js and npm installed.</li></ul><h4><strong>Step 1: Setting Up the Project</strong></h4><p>First, create a new Angular project using the CLI:</p><pre>ng new angular-hamburger-menu<br>cd angular-hamburger-menu</pre><p>Once the setup is complete, run:</p><pre>ng serve</pre><p>Open <a href="http://localhost:4200/">http://localhost:4200</a> in your browser to confirm the application is running.</p><h4><strong>Step 2: Installing Angular Material</strong></h4><p>Next, install Angular Material and its dependencies:</p><pre>ng add @angular/material</pre><p>This command will guide you through a setup process, asking which theme you’d like to use. Choose a theme that matches your branding or stick with the default. Once done, Angular Material will be integrated into your project.</p><h4><strong>Step 3: Adding animations support</strong></h4><p>In your app.config.ts file add the support for annimations.</p><pre>import { provideAnimations } from &#39;@angular/platform-browser/animations&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideZoneChangeDetection({ eventCoalescing: true }),<br>    provideRouter(routes),<br>    provideAnimations()<br>  ]<br>};</pre><h4><strong>Step 4: Creating hamburger menu component</strong></h4><p>You can create new component by calling:</p><pre>ng generate component components/Hamburger</pre><p>In the component code, you need to define an output that will emit click events. I also have two inputs, one is for initial state, and second one is a Observable that is telling me about events that forced closing of the menu.</p><pre>@Component({<br>  selector: &#39;app-hamburger&#39;,<br>  standalone: true,<br>  imports: [],<br>  templateUrl: &#39;./hamburger.component.html&#39;,<br>  styleUrl: &#39;./hamburger.component.scss&#39;<br>})<br>export class HamburgerComponent implements OnInit {<br>  @Input() initialState: boolean = false;<br>  @Input() closed?: Observable&lt;void&gt;;<br>  @Output() trigger: EventEmitter&lt;void&gt; = new EventEmitter&lt;void&gt;();<br><br>  active: boolean = false;<br><br>  ngOnInit(): void {<br>    this.active = this.initialState || false;<br><br>    if (this.closed) {<br>      this.closed.subscribe(() =&gt; this.active = false);<br>    }<br>  }<br><br>  triggered(): void {<br>    this.active = !this.active;<br>    this.trigger.emit();<br>  }<br><br>}</pre><p>The html for this component is simple as well. Basically few tested divs, main one has support for active class and handles the click event.</p><pre>&lt;div class=&quot;menu&quot; [class.active]=&quot;active&quot; (click)=&quot;triggered()&quot;&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;inner&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>The magic happens in the stylesheet. This is rendering three border in one column when the active class is not present, and two crossed ones when present. With some nice animations for transitions.</p><pre>$width: 24px;<br>$barHeight: 1px;<br>$barColor: #fff;<br><br>.menu {<br>  padding-right: 15px;<br>  width: $width;<br>  height: $width;<br>  cursor: pointer;<br><br>  .container {<br>    position: relative;<br><br>    .inner {<br>      position: absolute;<br>      width: $width - 2 * $barHeight;<br>      left: 0;<br>      top: 11px;<br>      border: $barHeight solid $barColor;<br>      transition: border-color .2s ease-in .2s;<br><br>      &amp;::before {<br>        position: absolute;<br>        content: &#39;&#39;;<br>        top: -6px;<br>        left: -$barHeight;<br>        width: $width - 2 * $barHeight;<br>        border: $barHeight solid $barColor;<br>        transition: top .2s ease-in .3s, transform ease-in .2s;<br>      }<br><br>      &amp;::after {<br>        position: absolute;<br>        content: &#39;&#39;;<br>        top: 4px;<br>        left: -$barHeight;<br>        width: $width - 2 * $barHeight;<br>        border: $barHeight solid $barColor;<br>        transition: top .2s ease-in .3s, transform ease-in .2s;<br>      }<br>    }<br>  }<br><br>  &amp;.active .container .inner {<br>    border-color: transparent;<br>    transition: border-color ease-in .1s;<br>  }<br><br>  &amp;.active .container .inner::before {<br>    top: -$barHeight;<br>    transform: rotate(-45deg);<br>    transition: top ease-out .2s, transform .2s ease-out .3s;<br>  }<br><br>  &amp;.active .container .inner::after {<br>    top: -$barHeight;<br>    transform: rotate(45deg);<br>    transition: top ease-out .2s, transform .2s ease-out .3s;<br>  }<br>}</pre><h4>Step 5: Adding side menu</h4><p>In the app.component.ts we will handle the imports for Material components, define a and handle sidebar mode. Basically we want to have normal sidebar on desktop and over the content sidebar on phones.</p><p>To accomplish the mode changes, we are using Angular CDK BreakpointObserver to force our mode to side when on handset.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [<br>    MatSidenavModule,<br>    MatToolbarModule,<br>    MatIconModule,<br>    MatListModule,<br>    RouterOutlet,<br>    RouterLink,<br>    MatButtonModule,<br>    HamburgerComponent<br>  ],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.scss&#39;<br>})<br>export class AppComponent {<br>  mode: MatDrawerMode = &#39;side&#39;;<br><br>  constructor(private breakpointObserver: BreakpointObserver) {<br>    this.breakpointObserver.observe([Breakpoints.Handset]).subscribe(result =&gt; {<br>      this.mode = result.matches ? &#39;over&#39; : &#39;side&#39;;<br>    });<br>  }<br>}</pre><p>In html we will define some containers, sidebar, menu and conent. We will use Material component to do so. For sidebar we will be using mat-sidenav where we put in the mode we calculated and open the sidenav by default on desktop.</p><p>In the menu toolbar, we will put our new hamburger component, put in the same initial sate as for the sidenav, define a trigger event to toggle the state of the sidenav and also provide a menu closed notifier to the menu component. This is for a case when menu is closed by clicking to background in the over mode.</p><pre>&lt;mat-sidenav-container class=&quot;example-container&quot;&gt;<br>  &lt;mat-sidenav #drawer [mode]=&quot;mode&quot; [opened]=&quot;mode === &#39;side&#39;&quot; class=&quot;example-sidenav&quot;&gt;<br>    &lt;mat-nav-list&gt;<br>      &lt;mat-list-item routerLink=&quot;/&quot;&gt;Home&lt;/mat-list-item&gt;<br>      &lt;mat-list-item routerLink=&quot;/about&quot;&gt;About&lt;/mat-list-item&gt;<br>      &lt;mat-list-item routerLink=&quot;/contact&quot;&gt;Contact&lt;/mat-list-item&gt;<br>    &lt;/mat-nav-list&gt;<br>  &lt;/mat-sidenav&gt;<br><br>  &lt;mat-sidenav-content&gt;<br>    &lt;mat-toolbar color=&quot;primary&quot;&gt;<br>      &lt;app-hamburger [initialState]=&quot;mode === &#39;side&#39;&quot; [closed]=&quot;drawer.closedStart&quot; (trigger)=&quot;drawer.toggle();&quot;/&gt;<br>      &lt;span class=&quot;title&quot;&gt;My Application&lt;/span&gt;<br>    &lt;/mat-toolbar&gt;<br><br>    &lt;div class=&quot;content&quot;&gt;<br>      &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>    &lt;/div&gt;<br>  &lt;/mat-sidenav-content&gt;<br>&lt;/mat-sidenav-container&gt;</pre><p>We finish that up with some styling:</p><pre>.example-container {<br>  height: 100vh;<br>}<br>.example-sidenav {<br>  width: 250px;<br>}<br>.title {<br>  margin-left: 16px;<br>}<br>.content {<br>  padding: 16px;<br>}</pre><h4><strong>Step 6: Routing (Optional)</strong></h4><p>If you want the routerLink directives to work, you’ll need to set up your routes.</p><p>In the app.route.ts file, lets define:</p><pre>export const routes: Routes = [<br>  { path: &#39;&#39;, component: HomeComponent },<br>  { path: &#39;about&#39;, component: AboutComponent },<br>  { path: &#39;contact&#39;, component: ContactComponent },<br>  { path: &#39;&#39;, redirectTo: &#39;/home&#39;, pathMatch: &#39;full&#39; },<br>];</pre><p>You can generate those components by calling:</p><pre>ng generate component components/Home<br>ng generate component components/About<br>ng generate component components/Contact</pre><h4><strong>Check Out the Complete Code on GitHub</strong></h4><p>For the full source code and a working example, visit the GitHub repository:</p><p><a href="https://github.com/PavlikPolivka/angular-hamburger-menu-tutorial"><strong>GitHub Repository</strong></a></p><p>Feel free to explore, fork, and contribute.</p><h4><strong>Conclusion</strong></h4><p>By leveraging Angular Material’s toolbar, sidenav, you can quickly build a functional, responsive hamburger menu in just a few steps. With just a bit of configuration, you’ve got a visually consistent, mobile-friendly navigation solution that aligns with modern design standards.</p><p>Now that you’ve learned the basics, try customizing the menu items, adding animations, or integrating authentication states. The possibilities are endless! And remember, for a handy reference, the GitHub repo is there for you to explore and modify.</p><h4><strong>Happy coding!</strong></h4><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f822cdca3ac7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/making-a-responsive-animated-hamburger-menu-with-angular-material-f822cdca3ac7">Making a responsive animated hamburger menu with Angular Material</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Android Daily Drivers: The Apps Keeping My Life on Track]]></title>
            <link>https://polivka-pavel.medium.com/my-android-daily-drivers-the-apps-keeping-my-life-on-track-7fbf0d4fa5fa?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbf0d4fa5fa</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[phone]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 20:56:00 GMT</pubDate>
            <atom:updated>2024-12-10T20:56:00.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*naH0dJuzPCh9-KOm" /><figcaption>Photo by <a href="https://unsplash.com/@irina_chishkova?utm_source=medium&amp;utm_medium=referral">Irina Chishkova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Android devices are packed with possibilities, but it’s the apps we rely on every day that truly shape our digital routines. From organizing tasks, keeping up with friends, discovering new stories, and optimizing our smart homes, the right set of apps can elevate our day-to-day experience. Here’s a look at the core apps that power my productivity, communication, entertainment, and more.</p><h3>Productivity &amp; Organization</h3><h4><strong>Twos — Note-taking &amp; Task Management</strong></h4><p>When juggling tasks and ideas, a clear and flexible note-taking system is essential. <strong>Twos</strong> provides a beautifully simple interface for capturing thoughts, creating to-do lists, and setting reminders. Whether it’s a random insight during a coffee break or a detailed project checklist, Twos ensures I can access and organize my notes anywhere.</p><h4><strong>Google Keep — Quick Notes &amp; Reminders</strong></h4><p>For those spur-of-the-moment ideas, quick grocery lists, and voice memos, <strong>Google Keep</strong> is my go-to. Its vibrant, color-coded notes and seamless integration with Google’s services make information easy to store, easy to find and super easy to share. It’s like having digital sticky notes always at my fingertips. It supports the S-Pen drawing.</p><h4><strong>1Password — Secure Passwords &amp; Logins</strong></h4><p>In an era of endless online accounts, <strong>1Password</strong> brings sanity to password management. With robust encryption, a polished UI, and easy syncing across devices, I never worry about forgetting a password or compromising security. It’s a daily essential for safe, streamlined access to all my accounts.</p><h4><strong>Google Calendar — Scheduling &amp; Time Management</strong></h4><p>To keep track of meetings, personal appointments, and deadlines, <strong>Google Calendar</strong> provides an intuitive interface and effortless event creation. Synced across all my devices, it ensures I always know what’s next — whether it’s a lunch date or a critical project review. I also highly recommend creating a shared calendar within your family. We have one with my wife, and the power to see whenever my wife has something when planning my calendar is priceless.</p><h4><strong>Instapaper — Distraction-Free Reading</strong></h4><p>The web is full of articles and long-reads that pique my interest. <strong>Instapaper</strong> lets me save them for later, presenting text in a clutter-free layout that’s easy on the eyes. It’s perfect for catching up on reading during commutes or quiet evenings at home.</p><h3><strong>Communication &amp; Social</strong></h3><h4><strong>Blue Sky — A Fresh Social Feed</strong></h4><p>With social media often feeling noisy and overwhelming, <strong>Blue Sky</strong> takes a more thoughtful approach. Its clean interface and focus on quality conversations help me enjoy my daily social check-in, discover new insights, and engage with a more mindful community.</p><h4><strong>Hey — A Modern Email Experience</strong></h4><p>Email can easily become a source of stress. <strong>Hey</strong> rethinks email with intuitive filtering and simple categories, taming inbox chaos. By giving me tools to quickly sort and prioritize messages, Hey makes processing email feel more like a seamless flow than a chore.</p><h4><strong>WhatsApp — Everyday Messaging &amp; Calls</strong></h4><p>For staying connected with friends and family worldwide, <strong>WhatsApp</strong> remains a must-have. The user-friendly design, dependable video and voice calls, and robust encryption help me keep in touch — even across continents — with minimal fuss.</p><h3><strong>Entertainment &amp; Knowledge</strong></h3><h4><strong>Goodreads — Discovering My Next Great Read</strong></h4><p>As a lifelong bookworm, <strong>Goodreads</strong> is an invaluable companion. Tracking what I’ve read, rating books, and joining communities of fellow readers makes finding my next literary escape a delight. The simple layout and community features encourage me to explore new authors and genres.</p><h4><strong>Audible &amp; Smart AudioBook Player — Immersive Listening</strong></h4><p>Audiobooks fill my downtime — walks, workouts, and commutes turn into storytime. <strong>Audible</strong> offers a massive selection of professionally narrated titles, while <strong>Smart AudioBook Player</strong> excels at handling my locally stored (essential when you want to listen to non english books) content with fine-tuned playback controls. Together, they ensure I can immerse myself in great stories whenever I have a moment to spare.</p><h4><strong>YouTube Music — Setting the Soundtrack</strong></h4><p>Whether I’m gearing up for a busy morning or unwinding after work, <strong>YouTube Music</strong> provides the soundtrack. Its curated playlists, clean interface, and vast library let me tune into my favorite tracks or discover new ones. It’s the perfect companion for any mood. Also, it helps that by paying for YT music you get ad free experience on YT.</p><h3><strong>Home, Health &amp; Navigation</strong></h3><h4><strong>SmartThings — Controlling My Smart Home</strong></h4><p>At home, convenience is king. <strong>SmartThings</strong> brings all my smart devices — lights, thermostats, and more — under one roof. Its straightforward controls and automation features help me set the perfect ambiance, whether I’m starting the day with bright lights or winding down with soothing, dimmed tones.</p><h4><strong>Samsung Health — Tracking Wellness &amp; Routine</strong></h4><p>Wellness is about knowing my habits. <strong>Samsung Health</strong> tracks steps, sleep, and workouts, offering clear visualizations of my progress. By providing insights and encouragement, it keeps me motivated to make healthier choices every day.</p><h4><strong>Waze — Navigating with Ease</strong></h4><p>When it’s time to hit the road, <strong>Waze</strong> helps me arrive faster and stress-free. With real-time traffic alerts and an easy-to-use interface, it’s my dependable co-pilot. I trust it to guide me around congestion and unexpected delays, so I spend less time stuck in traffic and more time where I want to be.</p><h3><strong>Final Thoughts</strong></h3><p>These apps form the backbone of my daily Android experience. They keep me organized, connected, informed, and entertained — ensuring I get the most out of every moment. By curating a set of tools that share clean interfaces, intuitive designs, and seamless cross-device syncing, I’ve crafted a digital ecosystem that genuinely supports my lifestyle. Whether it’s tackling to-do lists, discovering new music, keeping tabs on my health, or simply enjoying a well-told story, these daily drivers help me live better through technology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbf0d4fa5fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Angular Features Developers Often Overlook]]></title>
            <link>https://javascript.plainenglish.io/top-10-angular-features-developers-often-overlook-746883b6a8a0?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/746883b6a8a0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 20:51:46 GMT</pubDate>
            <atom:updated>2024-12-04T16:17:26.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNtKImX6yc_YNPvDY9w86w.png" /></figure><p>Angular is a robust framework that developers either love or hate, but let’s admit it: there’s a lot to it, and some gems are easy to miss. Here’s a list of Angular features that deserve more love. Whether you’re an Angular veteran or just starting out, these insights might level up your game.</p><h3>1. Standalone Components (Angular 14+)</h3><h4>Why It’s Overlooked</h4><p>Most developers are so used to the NgModules that they ignore this game-changing feature. Standalone components simplify app structure and make lightweight components a breeze.</p><h4>Code Example</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br><br>@Component({<br>  selector: &#39;app-hello&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  template: `&lt;h1&gt;Hello, Standalone!&lt;/h1&gt;`,<br>})<br>export class HelloComponent {}</pre><h4>Key Takeaway</h4><p>Skip the boilerplate of NgModules when you don’t need them. Use standalone: true and simplify your codebase.</p><h3>2. Signals (Angular 16+)</h3><h4>Why It’s Overlooked</h4><p>Signals introduce a new reactivity model that’s an alternative to RxJS. Developers who aren’t keeping up with Angular updates might miss out.</p><pre>import { signal, effect } from &#39;@angular/core&#39;;<br><br>const counter = signal(0);<br><br>function increment() {<br>  counter.set(counter() + 1);<br>}<br><br>// effect tracks changes on each used signal<br>// and is evoked again on each change<br>effect(() =&gt; {<br>  console.log(`The current count is: ${counter()}`);<br>});</pre><h4>Key Takeaway</h4><p>Signals provide a cleaner, simpler way to handle reactivity compared to traditional RxJS streams.</p><h3>3. Router Scroller</h3><h4>Why It’s Overlooked</h4><p>Scroll management might seem mundane, but the Angular Router Scroller can solve a ton of UX headaches with minimal effort.</p><h4>Code Example</h4><pre>RouterModule.forRoot(routes, {<br>  scrollPositionRestoration: &#39;enabled&#39;,<br>  anchorScrolling: &#39;enabled&#39;,<br>})</pre><h4>Key Takeaway</h4><p>Make scroll behavior seamless across navigation with scrollPositionRestoration and anchorScrolling.</p><h3>4. Dependency Injection Hierarchy Debugging</h3><h4>Why It’s Overlooked</h4><p>If you’ve ever struggled to figure out why Angular is giving you the wrong instance of a service, this tool can save you hours.</p><h4>Code Example</h4><pre>import { ApplicationRef } from &#39;@angular/core&#39;;<br><br>const appRef = inject(ApplicationRef);<br>const root = appRef.components[0].injector;<br>console.log(root);</pre><h4>Key Takeaway</h4><p>Inspect the dependency injection hierarchy directly in the console. No more guessing!</p><h3>5. Intersection Observer API in Directives</h3><h4>Why It’s Overlooked</h4><p>Directives are powerful, but many developers forget how they can integrate modern browser APIs like the Intersection Observer for performance optimizations.</p><h4>Code Example</h4><pre>import { Directive, ElementRef, EventEmitter, Output } from &#39;@angular/core&#39;;<br><br>@Directive({ selector: &#39;[appLazyLoad]&#39; })<br>export class LazyLoadDirective {<br>  @Output() visible = new EventEmitter&lt;void&gt;();<br><br>  constructor(el: ElementRef) {<br>    const observer = new IntersectionObserver(entries =&gt; {<br>      entries.forEach(entry =&gt; {<br>        if (entry.isIntersecting) {<br>          this.visible.emit();<br>          observer.unobserve(entry.target);<br>        }<br>      });<br>    });<br><br>    observer.observe(el.nativeElement);<br>  }<br>}</pre><h4>Key Takeaway</h4><p>Use directives to lazily load elements like images or heavy components with zero extra libraries.</p><h3>6. Optimized Zone.js (Angular 19)</h3><h4>Why It’s Overlooked</h4><p>Many developers overlook how Angular’s improved Zone.js can significantly boost app performance.</p><h4>Code Example</h4><pre>// Enable advanced optimization in `angular.json`<br>{<br>  &quot;projects&quot;: {<br>    &quot;app&quot;: {<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;options&quot;: {<br>            &quot;zone-opt&quot;: true<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><h4>Key Takeaway</h4><p>Angular 19’s Zone.js optimizations reduce unnecessary change detection cycles, improving performance.</p><h3>7. Preloading Strategies</h3><h4>Why It’s Overlooked</h4><p>Most developers stick with NoPreloading or PreloadAllModules and forget they can create custom preloading strategies.</p><h4>Code Example</h4><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Route, PreloadingStrategy } from &#39;@angular/router&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class CustomPreloadingStrategy implements PreloadingStrategy {<br>  preload(route: Route, load: () =&gt; Observable&lt;any&gt;): Observable&lt;any&gt; {<br>    return route.data &amp;&amp; route.data[&#39;preload&#39;] ? load() : of(null);<br>  }<br>}</pre><p>Add it to your Router:</p><pre>RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy });</pre><h4>Key Takeaway</h4><p>Control exactly what loads in the background with a custom preloading strategy.</p><h3>8. ngTemplateOutlet</h3><h4>Why It’s Overlooked</h4><p>Developers often struggle with reusable templates, not realizing ngTemplateOutlet makes it easy to pass templates dynamically.</p><h4>Code Example</h4><pre>&lt;ng-template #template let-name=&quot;name&quot;&gt;<br>  &lt;h1&gt;Hello {{ name }}&lt;/h1&gt;<br>&lt;/ng-template&gt;<br><br>&lt;div *ngTemplateOutlet=&quot;template; context: { name: &#39;Angular&#39; }&quot;&gt;&lt;/div&gt;</pre><h4>Key Takeaway</h4><p>Reuse templates dynamically without messy workarounds.</p><h3>9. DevTools Integration</h3><h4>Why It’s Overlooked</h4><p>The Angular DevTools extension isn’t just for debugging — it’s a powerhouse for performance tuning and inspecting change detection.</p><h4>Key Takeaway</h4><p>Install the Angular DevTools Chrome extension and use it to visualize component lifecycles and change detection trees.</p><h3>10. Strict Mode</h3><h4>Why It’s Overlooked</h4><p>Many developers skip enabling strict mode because they think it’s optional. Spoiler alert: It’s not optional if you want clean code.</p><h4>Code Example</h4><p>Enable it in tsconfig.json:</p><pre>{<br>  &quot;angularCompilerOptions&quot;: {<br>    &quot;strictTemplates&quot;: true<br>  }<br>}</pre><h4>Key Takeaway</h4><p>Strict mode catches errors early and enforces best practices, saving you headaches in production.</p><p>— — — — — — — — — — — — — — — — — — —</p><p>Angular’s ecosystem is vast, and features like these can help you write cleaner, faster, and more maintainable code. Which of these features are you going to try out? Let me know on <a href="https://bsky.app/profile/ppolivka.com">Blue Sky</a>!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=746883b6a8a0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/top-10-angular-features-developers-often-overlook-746883b6a8a0">Top 10 Angular Features Developers Often Overlook</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaning Up My Bluesky: A Journey into Orderliness]]></title>
            <link>https://python.plainenglish.io/cleaning-up-my-bluesky-a-journey-into-orderliness-4e81212d1446?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e81212d1446</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[blue-sky]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 21:55:42 GMT</pubDate>
            <atom:updated>2024-12-03T12:03:27.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMdJUi8OMHQOD2ES" /><figcaption>Photo by <a href="https://unsplash.com/@cdc?utm_source=medium&amp;utm_medium=referral">CDC</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bluesky is one of the freshest decentralized social networks out there. While seeing new connections and following accounts that pique your interest is exciting, things can quickly get messy. Over time, I realized my following list was filled with inactive accounts, repost machines, and others that didn’t add much to my daily scroll. So, I decided to clean it up, and as a developer, I built a script. Here’s the story behind it, a quick dive into the code, and some ideas for future improvements.</p><h3>The Motivation: Why Clean Up?</h3><p>Social media can easily get overwhelming. Following too many accounts dilutes the experience, making it hard to engage with the content you care about. For Bluesky, where network effects are still growing, having a clean following list feels even more important. It ensures that your timeline remains relevant and manageable.</p><p>I wanted to unfollow accounts that:</p><ol><li><strong>Haven’t posted in a long time.</strong> Why follow if they’re inactive?</li><li><strong>Only repost others’ content.</strong> Originality matters to me.</li></ol><p>And with the Bluesky API being relatively easy to work with, I decided to automate this cleanup process.</p><h3>Introducing the Cleanup Script</h3><p>You can check out the full script <a href="https://gist.github.com/PavlikPolivka/58070bb2ec5b04eb6f47ad37246b8eff">on this GitHub Gist</a>. It’s a Python script leveraging Bluesky’s API to analyze and unfollow accounts based on specific criteria. Here’s a high-level overview of how it works:</p><h3>The Process</h3><p><strong>1. Authenticate with Bluesky API:</strong> The script uses your API credentials to connect securely.</p><p><strong>3. Fetch Following List:</strong> It retrieves the list of accounts you’re following.</p><p><strong>3. Analyze Accounts:</strong> For each account, it:</p><ul><li>Check their last active date.</li><li>Counts how much of their content is original versus reposted.</li></ul><p><strong>4. Unfollow Accounts:</strong> If an account meets the cleanup criteria, the script unfollows it.</p><h3>The Code Walkthrough</h3><p>Here are some of the key sections of the script:</p><h4>Authentication</h4><pre>from atproto import Client<br><br>client = Client()<br>handle = &#39;YOUR_HANLDE&#39;<br>password = &#39;YOUR_APP_PASSWORD&#39;<br>client.login(handle, password)</pre><p>This snippet sets up authentication using your Bluesky username and app password, initializing the agent for API calls.</p><h4>Fetching Followed Accounts</h4><pre>def get_follows():<br>    &quot;&quot;&quot;Fetch the list of people you are currently following.&quot;&quot;&quot;<br>    follows = []<br>    response = client.get_follows(handle, None, 100)<br>    follows.extend(response.follows)<br>    while response.cursor:<br>        response = client.get_follows(handle, response.cursor, 100)<br>        follows.extend(response.follows)<br>    return follows</pre><p>This function retrieves your list of followed accounts through the agent’s get_follows method.</p><h4>Is Account Inactive</h4><pre>def get_last_post_date(user):<br>    &quot;&quot;&quot;Fetch the date of the last post of a user.&quot;&quot;&quot;<br>    response = client.get_author_feed(user.handle)<br>    if len(response.feed) &gt; 0:<br>        return datetime.datetime.fromisoformat(response.feed[0].post.indexed_at)<br>    return None<br><br>def is_inactive(user, days=15):<br>    fifteen_days_ago = datetime.datetime.now(timezone.utc) - datetime.timedelta(days=days)<br>    last_post_day = get_last_post_date(user)<br>    return last_post_day is None or last_post_day &lt; fifteen_days_ago</pre><p>This checks the date of the latest post in the user’s feed, if it’s older than the required days, it will mark the user as inactive.</p><h4>Is Account Reposter</h4><pre>def is_reposter(user, ratio=0.8):<br>    &quot;&quot;&quot;Check if a user is a reposter.&quot;&quot;&quot;<br>    response = client.get_author_feed(user.handle)<br>    reposts = 0<br>    for post in response.feed:<br>        if post.post.author.handle != user.handle:<br>            reposts += 1<br>    actual_ration = reposts / len(response.feed)<br>    return actual_ration &gt; ratio</pre><p>This calculates the ratio of reposts and actual posts. If the ratio is bigger than the required rate, the account gets marked as reposter.</p><h4>Unfollowing</h4><pre>def unfollow(user):<br>    &quot;&quot;&quot;Unfollow users.&quot;&quot;&quot;<br>    client.delete_follow(user.viewer.following)</pre><p>The unfollow is as easy as the above snippet.</p><h4>Putting It All Together</h4><pre>def action_on_users(follows, days, repost):<br>    &quot;&quot;&quot;Identify users to unfollow based on posting activity.&quot;&quot;&quot;<br>    inactiveCount = 0<br>    reposterCount = 0<br>    for user in follows:<br>        if is_inactive(user, days):<br>            inactiveCount += 1<br>            print(f&quot;User {user.handle} has not posted in the last {days} days.&quot;)<br>            if not dry:<br>                unfollow(user)<br>        if is_reposter(user, repost):<br>            reposterCount += 1<br>            print(f&quot;User {user.handle} is a reposter.&quot;)<br>            if not dry:<br>                unfollow(user)<br>    print(f&quot;Unfollowed {inactiveCount} inactive users and {reposterCount} reposters.&quot;)<br><br>def main(days=15, repost=0.8):<br>    follows = get_follows(recursive)<br>    action_on_users(follows, days, repost)</pre><p>The main script brings everything together, iterating through your following list and applying the cleanup rules.</p><h3>What’s Next? Possible Improvements</h3><p>While the script works well, there’s always room for improvement. Here are a few ideas:</p><ol><li><strong>UI for Simplicity:</strong> Add a web or desktop interface for non-developers.</li><li><strong>Enhanced Metrics:</strong> Analyze engagement (e.g., likes or comments) to better assess value.</li><li><strong>Batch Processing:</strong> Handle larger following lists more efficiently.</li></ol><h3>Final Thoughts</h3><p>Building this script was both a practical necessity and a fun project. If you’re also overwhelmed by an unmanageable following list on Bluesky, give it a try or fork the code to suit your needs. And if you’re like me and obsessed with clean slates, this might just be the productivity boost you’ve been looking for.</p><p>Got feedback or suggestions? Drop me a line on <a href="https://bsky.app/profile/ppolivka.com">Bluesky</a> or leave a comment on the Gist. Let’s make our timelines better together!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e81212d1446" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/cleaning-up-my-bluesky-a-journey-into-orderliness-4e81212d1446">Cleaning Up My Bluesky: A Journey into Orderliness</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Most Awesome Tools I Use on My Mac: A Developer’s Guide]]></title>
            <link>https://polivka-pavel.medium.com/the-most-awesome-tools-i-use-on-my-mac-a-developers-guide-f05d185673b7?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05d185673b7</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 08:56:32 GMT</pubDate>
            <atom:updated>2024-11-23T08:56:32.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keypUt0WFgk05U5fuhF0GA.jpeg" /></figure><p>As a developer, I’ve come to rely on an assortment of fantastic tools that make my Mac experience productive, enjoyable, and even a little magical. Below, I’ve organized the tools I use into categories that make sense — grouping similar tools together to create a more coherent flow. Whether you’re looking for command line power, productivity enhancements, or just something to make your life easier, there’s something here for everyone.</p><h3>Command Line &amp; Terminal Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EurJI7HxL9uun7Thhyp9_A.png" /></figure><h4><a href="https://brew.sh/">Homebrew</a></h4><p>Homebrew is the package manager that every Mac user needs. It makes installing, updating, and managing software incredibly simple, all from the command line. Need a specific tool or library? Chances are, you can install it with a quick brew install &lt;package&gt;. Homebrew takes the hassle out of installing developer tools and makes managing dependencies a breeze.</p><h4><a href="https://iterm2.com/">iTerm2</a></h4><p>If you’re still using the default Terminal app, iTerm2 is like upgrading from a toy car to a Ferrari. It offers split panes, rich customization, advanced search, and the ability to navigate with hotkeys — features that make working in the command line far more enjoyable. For me, it’s all about speed and the ability to multitask, and iTerm2 does that beautifully.</p><h4><a href="https://ohmyz.sh/">Oh My Zsh</a></h4><p>This is the tool that makes my command line look, feel, and work exactly the way I want it to. Oh My Zsh is a delightful framework for managing Zsh configuration, packed with plugins and themes that make navigating and managing my development environment much smoother. The auto-completions and keyboard shortcuts save me loads of time, and it just makes terminal life a lot more fun.</p><h3>Productivity Boosters</h3><h4><a href="https://www.raycast.com/">Raycast</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGplURvaZIptejBdAJDCFA.png" /></figure><p>Raycast is my productivity Swiss army knife. Think of it as Spotlight on steroids. I use it to launch apps, run shortcuts, do quick calculations, and more — all without lifting my hands from the keyboard. It integrates with a bunch of other tools, making it a great hub for all my Mac workflows. The extensibility of Raycast is what makes it so powerful; it’s one of those tools that you keep finding new uses for.</p><h4><a href="https://rectangleapp.com/">Rectangle</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlY7PAT5Tw91ssfVUaey2A.png" /></figure><p>Window management can get messy, but Rectangle keeps everything organized. This handy tool lets me snap windows into place using keyboard shortcuts — perfect for when I’m multitasking and need a tidy workspace. It’s lightweight, simple, and keeps my screen clutter under control, which is a huge help when juggling multiple code editors, terminals, and browser windows.</p><h4><a href="https://maccy.app/">Maccy</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QM76HR8WxdY5msd4wHE5Q.png" /></figure><p>Maccy is a clipboard manager, and it’s one of those tools I didn’t know I needed until I tried it. It keeps track of everything I copy, making it easy to find something I copied hours or even days ago. No more copying over something important by mistake — Maccy makes sure everything is saved in one convenient place.</p><h4><a href="https://app.grammarly.com/">Grammarly</a></h4><p>Grammarly is my go-to tool for writing, whether it’s code comments, documentation, or even emails. It catches grammar mistakes, suggests improvements, and generally makes my writing clearer and more professional. It integrates well with browsers and other apps, so it’s always there to lend a hand when I need it. With Grammarly, I can focus on the content without worrying about the nitty-gritty details of grammar and style.</p><h3>Focus and Comfort</h3><h4><a href="https://apps.apple.com/cz/app/amphetamine/id937984704?l=cs&amp;mt=12">Amphetamine</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*4YZrmg81jCB-UI1KuvUiPQ.png" /></figure><p>Sometimes you just don’t want your Mac to sleep or turn off the screen, especially during those long coding sessions or while running a lengthy script. Amphetamine lets me keep my Mac awake with just a click. It’s simple, effective, and a lot easier than digging through system settings to adjust sleep options.</p><h4><a href="https://icemenubar.app/">Ice</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnuVvDOQ2dhHjUiLJUFGXA.png" /></figure><p>Ice helps keep my Mac’s fans under control. As someone who pushes their Mac pretty hard, it’s essential to keep an eye on temperatures and fan speeds. Ice does a great job of managing this and helps me make sure my machine is always running smoothly without getting too hot under the collar.</p><h3>Development Tools</h3><h4><a href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcXyIqOtzI6cH43VxGdv4w.png" /></figure><p>Whether I’m using the Ultimate edition or a combination of the Community edition with WebStorm, IntelliJ is my IDE of choice. It’s incredibly powerful, with a wealth of plugins that make my development workflow smooth. The intelligent code completion, debugging tools, and overall user experience are unparalleled for any development.</p><h4><a href="https://chatgpt.com/">ChatGPT</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbcKXE1gPJLN1dLdivcToA.png" /></figure><p>Yes, even an AI assistant makes it to my list! Whether I’m stuck on a particular piece of code, need a second opinion on my implementation, or just want to brainstorm a bit, ChatGPT is a great companion to have by my side. It’s like having a very patient programming buddy who’s always ready to help. Also, its desktop map can directly work with files from your IDE.</p><h3>Security and Convenience</h3><h4><a href="https://1password.com/">1Password</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQLI_2T6zGv6LovFW42nGQ.png" /></figure><p>Passwords are a necessary evil, but 1Password makes managing them easy. It keeps all my credentials, sensitive notes, and even software licenses in one place, securely. It also integrates seamlessly with browsers and apps, making logging in or filling out secure information painless. Security without the hassle — that’s 1Password. This is the only not a free option on this list, but its fully worth the money.</p><p>— — — — —</p><p>These tools make my Mac a powerhouse for development, productivity, and just getting things done in general. Each one plays its own role, from managing my terminal environment to keeping me organized and focused. I hope you find something here that can make your workflow a little smoother, too. If there’s a tool you love that I’ve missed, drop a comment — I’m always on the lookout for something new!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05d185673b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert All: A Journey to Create a Simple, Universal File Conversion Tool]]></title>
            <link>https://python.plainenglish.io/convert-all-a-journey-to-create-a-simple-universal-file-conversion-tool-99508d67d456?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/99508d67d456</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 22:06:55 GMT</pubDate>
            <atom:updated>2024-11-19T09:38:35.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bDadhfVDwuXNxgWD" /><figcaption>Photo by <a href="https://unsplash.com/@pjswinburn?utm_source=medium&amp;utm_medium=referral">Philip Swinburn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For a while, I’ve been fascinated with the idea of having a <strong>one-stop tool for converting files between formats</strong>. The process can be annoyingly complex with multiple tools, whether it’s converting a .pdf to .docx, an image from .png to .jpg, or a text file to .pdf. I wanted to create something simple yet extensible — a command-line tool that anyone could use effortlessly.</p><p>Enter <strong>“Convert All,” </strong>a Python-powered CLI tool that allows you to convert files between various formats with a single command.</p><p>In this post, I’ll walk you through:</p><ul><li><strong>What the tool does and how to use it.</strong></li><li><strong>How I built it.</strong></li><li><strong>What I learned while publishing to PyPI and automating releases with GitHub Actions.</strong></li></ul><p>By the end, I hope to inspire you to bring your next project idea to life!</p><h3><strong>What Is “Convert All”?</strong></h3><p>At its core, “Convert All” is a simple CLI tool. The goal is to allow you to run something like this:</p><pre>convert file.docx file.pdf</pre><p>…and voilà! Your .docx is converted into a .pdf.</p><p>Supported conversions include:</p><ul><li><strong>Documents</strong>: .pdf ⇆ .docx, .docx ⇆ .txt, .pdf → .txt.</li><li><strong>Images</strong>: .png ⇆ .jpg.</li><li><strong>Audio/Video</strong>: .mp3 ⇆ .wav, .mp4 ⇆ .avi.</li></ul><p>What makes “Convert All” unique is its <strong>modular design</strong>. Each conversion module is independent, meaning developers can contribute new modules for additional formats easily.</p><h3><strong>Why Build It?</strong></h3><p>Like many developers, I often deal with the need for a different format of a file that I currently have. I usually go online to find some free converter, that would do the conversion.</p><p>More importantly, I wanted to <strong>learn the full lifecycle of creating a Python package, publishing it to PyPI, and automating the development pipeline</strong>. This project provided the perfect opportunity.</p><h3><strong>Installing “Convert All”</strong></h3><p>You can install the tool directly from PyPI using pip:</p><pre>pip install convert-anything</pre><p>After installation, you can start converting files right away:</p><pre>convert input.docx output.pdf</pre><h3><strong>How I Built It</strong></h3><p>The journey from idea to publishable package involved several steps, and each taught me something valuable.</p><h4><strong>1. Creating the Core Functionality</strong></h4><p>The heart of the tool is its <strong>modular design</strong>. Each file type conversion (e.g., .pdf to .docx, .png to .jpg) is implemented as a separate module. Here’s a snippet of how one of these modules works:</p><pre>import ffmpeg<br><br>SUPPORTED_FORMATS = {<br>    &quot;input&quot;: [&quot;.mp3&quot;, &quot;.wav&quot;, &quot;.ogg&quot;, &quot;.flac&quot;, &quot;.aac&quot;, &quot;.m4a&quot;],<br>    &quot;output&quot;: [&quot;.mp3&quot;, &quot;.wav&quot;, &quot;.ogg&quot;, &quot;.flac&quot;, &quot;.aac&quot;, &quot;.m4a&quot;]<br>}<br><br><br>def convert(input_file, output_file):<br>    ffmpeg.input(input_file).output(output_file).run()</pre><p>This modular approach ensures the tool is easily extensible. Adding support for a new format is as simple as writing a new function.</p><h4><strong>2. Packaging the Project for PyPI</strong></h4><p>Learning how to package a Python project was one of the most rewarding parts of this journey. The setup.py file is key — it defines the package metadata and dependencies. Here’s what mine looked like:</p><pre>from setuptools import setup, find_packages<br><br>setup(<br>    name=&quot;convert-all&quot;,<br>    version=&quot;1.0.0&quot;,<br>    author=&quot;Your Name&quot;,<br>    description=&quot;A simple CLI tool to convert files between formats&quot;,<br>    packages=find_packages(),<br>    install_requires=[<br>        &quot;click&quot;,<br>        &quot;python-docx&quot;,<br>        &quot;PyMuPDF&quot;<br>    ],<br>    entry_points={<br>        &quot;console_scripts&quot;: [<br>            &quot;convert=converter.core:convert&quot;<br>        ],<br>    },<br>)</pre><p><strong>Lessons Learned:</strong></p><ul><li><strong>Dependencies</strong>: Ensure all libraries your project uses (like python-docx and PyMuPDF) are included in the install_requires list.</li><li><strong>Testing Your Package Locally</strong>: Before publishing, I used pip install . to test the package locally and catch any errors.</li></ul><h4><strong>3. Publishing to PyPI</strong></h4><p>Publishing to PyPI was simpler than I expected, thanks to tools like twine. The steps involved were:</p><p>1. <strong>Build the Package</strong>:</p><pre>python setup.py sdist bdist_wheel</pre><p>2. <strong>Upload Using Twine</strong>:</p><pre>twine upload dist/*</pre><h4><strong>4. Automating Releases with GitHub Actions</strong></h4><p>One of the highlights of this project was integrating <strong>GitHub Actions</strong> to automate the release pipeline. Now, every time I tag a new release, the following happens:</p><ol><li>The package is built.</li><li>It’s uploaded to PyPI.</li><li>The tests are run to ensure everything works.</li></ol><p>Here’s a simplified version of my GitHub Actions workflow:</p><pre>name: Publish to PyPI<br><br>on:<br>  push:<br>    tags:<br>      - &quot;v*.*.*&quot;<br><br>jobs:<br>  publish:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v3<br><br>      - name: Set up Python<br>        uses: actions/setup-python@v4<br>        with:<br>          python-version: &quot;3.9&quot;<br><br>      - name: Install dependencies<br>        run: pip install setuptools wheel twine<br><br>      - name: Build package<br>        run: python setup.py sdist bdist_wheel<br><br>      - name: Publish to PyPI<br>        env:<br>          TWINE_USERNAME: &quot;__token__&quot;<br>          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}<br>        run: twine upload dist/*</pre><p><strong>Lessons Learned:</strong></p><ul><li>Automating repetitive tasks like testing and publishing saves so much time.</li><li>Using PyPI tokens ensures secure access to the repository.</li></ul><h3><strong>What I Learned</strong></h3><p><strong>1. Working with PyPI</strong>:</p><ul><li>Packaging isn’t scary once you understand setup.py.</li><li>Tools like twine make publishing a breeze.</li></ul><p><strong>2. The Power of GitHub Actions</strong>:</p><ul><li>Automating builds and tests gives peace of mind, especially as the project grows.</li><li>Setting up CI/CD workflows is a skill every developer should learn.</li></ul><p>3. <strong>Embracing Open-Source Principles</strong>:</p><ul><li>Documenting the project, writing tests, and thinking about extensibility made me appreciate the challenges (and rewards) of open-source contributions.</li></ul><h3><strong>What’s Next for “Convert All”?</strong></h3><p>While I’m proud of the first version, there’s so much more I want to add:</p><ul><li><strong>More Format Support</strong>: Expanding to cover more formats.</li><li><strong>Better Error Handling</strong>: Improving user feedback for unsupported formats.</li><li><strong>Cross-Platform Optimization</strong>: Ensuring smooth performance on Windows, macOS, and Linux.</li></ul><h3><strong>Final Thoughts</strong></h3><p>Building “Convert All” has been an incredibly rewarding journey. Not only did I create a tool that solves a real problem, but I also learned how to package, publish, and automate Python projects like a pro.</p><p>If you’re interested in the project, check it out on <a href="https://github.com/PavlikPolivka/convert-anything">GitHub</a> or install it from PyPI:</p><pre>pip install convert-all</pre><p>Let me know what you think and what features you’d like to see next! 🚀</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99508d67d456" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/convert-all-a-journey-to-create-a-simple-universal-file-conversion-tool-99508d67d456">Convert All: A Journey to Create a Simple, Universal File Conversion Tool</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Meme Generator with Angular and OpenAI]]></title>
            <link>https://javascript.plainenglish.io/building-a-meme-generator-with-angular-and-openai-d30c99d0bfb5?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30c99d0bfb5</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[memes]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 21:05:52 GMT</pubDate>
            <atom:updated>2024-11-13T01:44:33.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bj4uM6CLKkO5mkdu" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating a meme generator is a fun and engaging way to explore new technologies and APIs. Let me walk you through my journey of building one using Angular, the OpenAI API, and Giphy. I’ll share what I learned along the way, including calling the OpenAI API, deploying serverless functions, and working with Angular Material UI components.</p><h3><strong>Overview</strong></h3><p>The goal was to build a web application where users can enter a topic or phrase, and the app generates a meme with a caption based on that input. Here’s a high-level overview of the steps involved:</p><ol><li><strong>Set up the Angular front end with Material UI components.</strong></li><li><strong>Create a backend function to generate captions using the OpenAI API.</strong></li><li><strong>Deploy the backend function to Vercel.</strong></li><li><strong>Handle Cross-Origin Resource Sharing (CORS) issues between the front end and back end.</strong></li><li><strong>Integrate the backend API with the Angular front end.</strong></li><li><strong>Enhance the meme display with styling and additional features.</strong></li></ol><p>Let’s dive into each of these steps.</p><h3><strong>Setting Up the Angular Frontend with Angular Material</strong></h3><p><strong>What I learned:</strong> Integrating Angular Material components can significantly speed up the development process and enhance the UI/UX of the application.</p><h4><strong>Installing Angular Material</strong></h4><p>First, I added Angular Material to the project:</p><pre>ng add @angular/material</pre><h4><strong>Implementing the UI</strong></h4><p>I created a simple form where users can input a topic or phrase:</p><pre>&lt;mat-card&gt;<br>  &lt;mat-card-title&gt;Meme Generator&lt;/mat-card-title&gt;<br>  &lt;mat-card-content&gt;<br>    &lt;mat-form-field appearance=&quot;fill&quot;&gt;<br>      &lt;mat-label&gt;Enter a topic or phrase&lt;/mat-label&gt;<br>      &lt;input matInput [(ngModel)]=&quot;userInput&quot; /&gt;<br>    &lt;/mat-form-field&gt;<br>    &lt;button mat-raised-button color=&quot;primary&quot; (click)=&quot;generateMeme()&quot;&gt;Generate Meme&lt;/button&gt;<br>  &lt;/mat-card-content&gt;<br>&lt;/mat-card&gt;</pre><h3><strong>Creating the Backend Function with OpenAI API</strong></h3><p><strong>What I learned:</strong> Interacting with the OpenAI API and deploying serverless functions to Vercel is straightforward and efficient.</p><h4><strong>Writing the Backend Function</strong></h4><p>I created a generateMeme function that:</p><ul><li>Accepts user input from the front end.</li><li>Calls the OpenAI API to generate a meme caption.</li><li>Fetches relevant images from the Giphy API.</li></ul><pre>const axios = require(&#39;axios&#39;);<br><br>module.exports = async (req, res) =&gt; {<br><br>  // Load environment variables (only in development)<br>  if (!process.env.OPENAI_API_KEY || !process.env.GIPHY_API_KEY) {<br>    require(&#39;dotenv&#39;).config();<br>  }<br><br>  const OPENAI_API_KEY = process.env.OPENAI_API_KEY;<br>  const GIPHY_API_KEY = process.env.GIPHY_API_KEY;<br><br>  if (req.method !== &#39;POST&#39;) {<br>    return res.status(405).json({ error: &#39;Method not allowed, use POST&#39; });<br>  }<br><br>  const userInput = req.body.userInput;<br><br>  if (!userInput) {<br>    return res.status(400).json({ error: &#39;Missing &quot;userInput&quot; in request body&#39; });<br>  }<br><br>  try {<br>    // Generate Caption using OpenAI Chat Completion API<br>    const captionResponse = await axios.post(<br>      &#39;https://api.openai.com/v1/chat/completions&#39;,<br>      {<br>        model: &#39;gpt-4&#39;,<br>        messages: [<br>          {<br>            role: &#39;user&#39;,<br>            content: `<br>              Create a meme caption based on the following topic: &quot;${userInput}&quot;.<br>              Provide the caption split into a top and bottom text.<br>              Generate a concise and specific search query (2-3 words) to find an appropriate image on Giphy.<br>              Format your response exactly as JSON: {&quot;topText&quot;: &quot;Top caption&quot;, &quot;bottomText&quot;: &quot;Bottom caption&quot;, &quot;searchQuery&quot;: &quot;Search Query&quot;}.<br>              Do not include any extra text outside of the JSON format.<br>              `<br>          }<br>        ],<br>        max_tokens: 60,<br>        temperature: 0.8,<br>        n: 1,<br>      },<br>      {<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          &#39;Authorization&#39;: `Bearer ${OPENAI_API_KEY}`,<br>        },<br>      }<br>    );<br><br>    let topText = &#39;&#39;;<br>    let bottomText = &#39;&#39;;<br>    let searchQuery = &#39;&#39;;<br><br>    try {<br>      const jsonResponse = captionResponse.data.choices[0].message.content.trim();<br>      const parsedResponse = JSON.parse(jsonResponse);<br>      topText = parsedResponse.topText || &#39;&#39;;<br>      bottomText = parsedResponse.bottomText || &#39;&#39;;<br>      searchQuery = parsedResponse.searchQuery || &#39;&#39;;<br>    } catch (parseError) {<br>      console.error(&#39;Error parsing caption JSON:&#39;, parseError);<br>      return res.status(500).json({ error: &#39;Failed to generate meme captions.&#39; });<br>    }<br><br>    // Fetch Images from Giphy API using the search query<br>    const giphyResponse = await axios.get(&#39;https://api.giphy.com/v1/gifs/search&#39;, {<br>      params: {<br>        api_key: GIPHY_API_KEY,<br>        q: searchQuery,<br>        limit: 10,<br>        rating: &#39;PG-13&#39;,<br>      },<br>    });<br><br>    const images = giphyResponse.data.data.map((gif) =&gt; ({<br>      id: gif.id,<br>      title: gif.title,<br>      imageUrl: gif.images.downsized_still.url,<br>    }));<br><br>    // Return Combined Response<br>    return res.status(200).json({ topText, bottomText, searchQuery, images, userInput });<br>  } catch (error) {<br>    console.error(&#39;Error:&#39;, error.response ? error.response.data : error.message);<br>    return res.status(500).json({ error: &#39;An error occurred while generating the meme.&#39; });<br>  }<br>};</pre><h4><strong>Deploying to Vercel</strong></h4><p>Deploying the backend function to Vercel was as simple as:</p><pre>vercel link<br>vercel deploy --prod</pre><h3><strong>Handling CORS Issues</strong></h3><p><strong>What I learned:</strong> CORS errors can occur when the front end and back end are on different domains or ports. Setting appropriate headers in the backend resolves these issues.</p><h4><strong>Setting CORS Headers</strong></h4><p>I added the following headers to the backend response:</p><pre>res.setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>res.setHeader(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, OPTIONS&#39;);<br>res.setHeader(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type&#39;);</pre><h4><strong>Handling Preflight Requests</strong></h4><p>I ensured that the backend function properly handles OPTIONS requests:</p><pre>if (req.method === &#39;OPTIONS&#39;) {<br>  return res.status(200).end();<br>}</pre><h3><strong>Integrating the Backend API with Angular Frontend</strong></h3><p><strong>What I learned:</strong> Consuming a backend API in Angular involves creating services and handling HTTP requests using HttpClient.</p><h4><strong>Creating a Service</strong></h4><p>I created a CaptionService to interact with the backend API:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { map, Observable } from &#39;rxjs&#39;;<br><br>export interface MemeResponse {<br>  topText: string;<br>  bottomText: string;<br>  image: string;<br>  userInput: string;<br>  searchQuery: string;<br>}<br><br>interface MemeResponseWithImages {<br>  topText: string;<br>  bottomText: string;<br>  searchQuery: string;<br>  userInput: string;<br>  images: Array&lt;{ id: string; title: string; imageUrl: string }&gt;;<br>}<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class CaptionService {<br>  private apiUrl = &#39;https://meme-generator-backend.vercel.app/api/generateMeme&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  generateMeme(userInput: string): Observable&lt;MemeResponse&gt; {<br>    return this.http.post&lt;MemeResponseWithImages&gt;(this.apiUrl, { userInput }).pipe(<br>      map((response) =&gt; {<br>          // default 404 image if nothing is found<br>          let image = &#39;https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcm5iNXNrd3NjYWY3cjRjcjA0YXlteXhub3k4ZWsycmpxYzJ4NmhncCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/UHAYP0FxJOmFBuOiC2/giphy.gif&#39;;<br>          if (response.images.length &gt; 0) {<br>            const randomImage = response.images[Math.floor(Math.random() * response.images.length)];<br>            image = randomImage.imageUrl;<br>          }<br>          return {<br>              topText: response.topText,<br>              bottomText: response.bottomText,<br>              userInput: response.userInput,<br>              searchQuery: response.searchQuery,<br>              image: image<br>          } as MemeResponse;<br>      })<br>    );<br>  }<br>}</pre><h4><strong>Consuming the Service in the Component</strong></h4><p>In the component, I called the service and handled the response by passing the data to meme component:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;<br>import { MatInputModule } from &#39;@angular/material/input&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { MatProgressSpinnerModule } from &#39;@angular/material/progress-spinner&#39;;<br>import { MatCardModule } from &#39;@angular/material/card&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { CaptionService } from &#39;../../services/caption.service&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br><br><br>@Component({<br>  selector: &#39;app-home&#39;,<br>  standalone: true,<br>  imports: [ CommonModule, MatFormFieldModule, MatInputModule, FormsModule, MatProgressSpinnerModule, MatButtonModule, MatCardModule ],<br>  templateUrl: &#39;./home.component.html&#39;,<br>  styleUrl: &#39;./home.component.scss&#39;<br>})<br>export class HomeComponent {<br><br>  userInput = &#39;&#39;;<br>  isLoading = false;<br><br>  constructor(<br>    private captionService: CaptionService,<br>    private router: Router<br>  ) {}<br><br>  generateMeme() {<br>    if (!this.userInput.trim()) {<br>      alert(&#39;Please enter a topic or phrase.&#39;);<br>      return;<br>    }<br>    this.isLoading = true;<br><br>    // Call the backend to generate the meme<br>    this.captionService.generateMeme(this.userInput).subscribe(<br>      (response) =&gt; {<br>        this.router.navigate([&#39;/meme&#39;], { state: { data: response } });<br>        this.isLoading = false;<br>      },<br>      (error) =&gt; {<br>        console.error(error);<br>        this.isLoading = false;<br>        alert(&#39;An error occurred while generating the meme.&#39;);<br>      }<br>    );<br>  }<br><br>}</pre><h3><strong>Meme Display</strong></h3><p><strong>What I learned:</strong> Styling and positioning elements using Angular Material and CSS enhances the user experience.</p><h4><strong>Displaying the Meme</strong></h4><p>I updated the meme component to display the image and caption in a classic meme style:</p><pre>&lt;div class=&quot;meme-container&quot;&gt;<br>  &lt;mat-card class=&quot;card&quot;&gt;<br>    &lt;mat-card-title&gt;<br>      {{ searchQuery }}<br>    &lt;/mat-card-title&gt;<br>    &lt;mat-card-content&gt;<br>      &lt;div class=&quot;meme-image&quot; id=&quot;meme&quot;&gt;<br>        &lt;img [src]=&quot;image&quot; alt=&quot;Meme Image&quot; /&gt;<br>        &lt;div class=&quot;caption top-caption&quot;&gt;{{ topText }}&lt;/div&gt;<br>        &lt;div class=&quot;caption bottom-caption&quot;&gt;{{ bottomText }}&lt;/div&gt;<br>        &lt;div class=&quot;watermark&quot;&gt; Pavel Polivka &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/mat-card-content&gt;<br>  &lt;/mat-card&gt;<br>&lt;/div&gt;</pre><h4><strong>Styling the Meme</strong></h4><p>I added CSS to position the captions appropriately:</p><pre>.meme-container {<br>  position: relative;<br>  display: inline-block;<br>}<br><br>.meme-container img {<br>  max-width: 100%;<br>  height: auto;<br>}<br><br>.caption {<br>  position: absolute;<br>  left: 0;<br>  right: 0;<br>  padding: 0 10px;<br>  color: white;<br>  font-size: 2em;<br>  font-weight: bold;<br>  text-shadow: 2px 2px 4px #000;<br>  text-align: center;<br>  text-transform: uppercase;<br>}<br><br>.top-caption {<br>  top: 10px;<br>}<br><br>.bottom-caption {<br>  bottom: 10px;<br>}</pre><h3><strong>Conclusion</strong></h3><p>Building this meme generator was an exciting journey that taught me a lot about integrating APIs, handling CORS issues, and enhancing user interfaces with Angular Material. Here’s a recap of what I learned:</p><p>• <strong>Calling the OpenAI API</strong>: Interacting with powerful AI models to generate content dynamically.</p><p>• <strong>Deploying Backend Functions to Vercel</strong>: Leveraging serverless functions for scalable backend solutions.</p><p>• <strong>Working with Angular Material UI</strong>: Utilizing pre-built UI components to accelerate development and improve UX.</p><p>• <strong>Handling CORS Issues</strong>: Understanding how to set appropriate headers and manage cross-origin requests.</p><p><strong>Next Steps</strong></p><p>Feel free to clone the repository and try it out yourself. Experiment with different APIs, customize the styling and add new features to make it your own.</p><p><a href="https://github.com/PavlikPolivka/meme-generator-backend">Back end repository</a></p><p><a href="https://github.com/PavlikPolivka/meme-generator">Front end repository</a></p><p><em>Thank you for reading! If you enjoyed this post, please clap and share it with others who might find it useful.</em></p><p><em>Happy coding!</em></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30c99d0bfb5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-meme-generator-with-angular-and-openai-d30c99d0bfb5">Building a Meme Generator with Angular and OpenAI</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing AI-powered Javadoc IntelliJ plugin]]></title>
            <link>https://python.plainenglish.io/developing-ai-powered-javadoc-intellij-plugin-b3b89052aa5e?source=rss-82ff2277907f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b89052aa5e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pavel Polívka]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 22:08:16 GMT</pubDate>
            <atom:updated>2024-11-11T04:29:25.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U9R7wLIGfWR8OePj" /><figcaption>Photo by <a href="https://unsplash.com/@barbarazandoval?utm_source=medium&amp;utm_medium=referral">Barbara Zandoval</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I decided to do a bunch of AI side projects to sharpen my AI knowledge. In this article, I want to go over my latest one, an AI-powered Javadoc IntelliJ plugin.</p><h3>The idea</h3><p>The idea behind the plugin is straightforward. You have a function in your Java code; it’s missing Javadoc. If you hit a button (keyboard shortcut), it will add a Javadoc to the function. GenAI generates that Javadoc, so it has meaningful text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5bBn1I8cQvy6OOnW7MoPQ.gif" /></figure><h3>Training the model</h3><p>I did my research and figured out that I would need to fine-tune one of the already existing models. I narrowed it down to either using <a href="https://github.com/microsoft/CodeBERT">CodeBert</a> or <a href="https://github.com/salesforce/CodeT5">CodeT5</a>. In the end, I went with T5 small. But this would work with any other model.</p><p>To train the model, I need to have some training data. Google and the open-source community to the rescue, there is a <a href="https://huggingface.co/datasets/code-search-net/code_search_net">code-search-net</a> dataset already. It’s 2 million comments to code pairs that are scrapped from GitHub. That&#39;s exactly what I needed.</p><p>I am doing all of this on my MacBook Air M1, so I do not have a GPU. Training even the small variant of the model with this dataset would take over 80 hours. So, I started looking at how to run this on GPU somewhere. I came across Google Colab, where you can run on GPU (somewhat limited) for free. Or you can buy some credits for 10 euros.</p><p>So I have my model, training data, and environment. Let’s start coding.</p><p>We will start with some imports:</p><pre>from datasets import load_dataset<br>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, Trainer, TrainingArguments<br>import torch<br>import wandb<br>from google.colab import drive</pre><p>And some light setup. Here we log in to <a href="https://wandb.ai/site">Wandb</a> and <a href="https://drive.google.com/">Google Drive</a>. We can you wandb to monitor some metrics during training and drive for storing our model and training checkpoints.</p><pre>drive.mount(&#39;/content/drive&#39;)<br>wandb.login(key=&quot;YOUR_FREE_ACCOUNT_API_KEY&quot;)<br>wandb.init()</pre><p>Prepare the training data. We load the code_search_net data set from hugging face and tokenize it.</p><pre># Load the CodeSearchNet dataset for Java<br>dataset = load_dataset(&quot;code_search_net&quot;, &quot;java&quot;)<br><br># Display an example<br>print(dataset[&#39;train&#39;][0])<br><br>def tokenize_function(examples):<br>    # Tokenize code as input<br>    inputs = tokenizer(examples[&quot;func_code_string&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=128)<br>    # Tokenize docstring as target<br>    targets = tokenizer(examples[&quot;func_documentation_string&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=128)<br><br>    # Set input_ids and target_ids<br>    inputs[&quot;labels&quot;] = targets[&quot;input_ids&quot;]<br>    return inputs<br><br>tokenized_datasets = dataset.map(tokenize_function, batched=True)</pre><p>And train the model. In the example below I have it set up so that it stores checkpoints during the training. If for some reason your training gets interrupted, when you run it again it will resume where it left off. The final trained model will be again stored on Google Drive.</p><pre>model_name = &quot;Salesforce/codet5-small&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForSeq2SeqLM.from_pretrained(model_name)<br><br>training_args = TrainingArguments(<br>    eval_strategy=&quot;epoch&quot;,<br>    learning_rate=2e-5,<br>    per_device_train_batch_size=20,<br>    per_device_eval_batch_size=16,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>    logging_dir=&quot;./logs&quot;,<br>    save_total_limit=2,<br>    output_dir = &quot;/content/drive/MyDrive/model_checkpoints&quot;<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_datasets[&quot;train&quot;],<br>    eval_dataset=tokenized_datasets[&quot;validation&quot;],<br>)<br>trainer.train(resume_from_checkpoint=True)<br><br>model.save_pretrained(&quot;/content/drive/MyDrive/final_model&quot;)<br>tokenizer.save_pretrained(&quot;/content/drive/MyDrive/final_model&quot;)</pre><h3>API development and deployment</h3><p>Great now we have our model. Let’s do a quick check it does what we need.</p><pre>def generate_javadoc(code_snippet):<br>    # Tokenize the code snippet as input<br>    inputs = tokenizer(code_snippet, return_tensors=&quot;pt&quot;, max_length=128, truncation=True)<br><br>    # Generate summary IDs with the fine-tuned model<br>    summary_ids = model.generate(<br>        inputs[&quot;input_ids&quot;],<br>        max_length=128,<br>        min_length=30,<br>        length_penalty=2.0,<br>        num_beams=4,<br>        early_stopping=True<br>    )<br><br>    # Decode the generated Javadoc comment<br>    javadoc = tokenizer.decode(summary_ids[0], skip_special_tokens=True)<br>    return javadoc<br><br>code_example = &quot;&quot;&quot;<br>    public void storeRecord(Optional&lt;Metadata&gt; metadata) throws BadDataExpection {<br>        fillMissingData(metadata);<br>        metadataRepository.store(metadata);<br>    }<br>&quot;&quot;&quot;<br><br># Generate Javadoc<br>print(&quot;Generated Javadoc:&quot;)<br>print(generate_javadoc(code_example))</pre><p>Success. It printed the desired Javadoc. Now we need to store that model to hugging face so that we can retrieve it anywhere. To do so, you log in to <a href="https://huggingface.co/">hugging face</a> and click “create new”. It will create a git repo for you, you just need to push all the files from the final_model folder into that git repo. As easy as it gets.</p><p>Next. We need to create a simple python app, that would take the code that we want to generate the Javadoc for as input and returns the generated Javadoc. I used FastAPI library for that.</p><pre>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>from transformers import AutoModelForSeq2SeqLM, AutoTokenizer<br><br>app = FastAPI()<br><br>model_path = &quot;/app/model&quot; <br>model = AutoModelForSeq2SeqLM.from_pretrained(model_path)<br>tokenizer = AutoTokenizer.from_pretrained(model_path)<br><br>class CodeInput(BaseModel):<br>    code: str<br><br>@app.get(&quot;/&quot;)<br>async def health_check():<br>    return {&quot;status&quot;: &quot;running&quot;}<br><br>@app.post(&quot;/generate_javadoc&quot;)<br>async def generate_javadoc(code_input: CodeInput):<br>    try:<br>        inputs = tokenizer(code_input.code, return_tensors=&quot;pt&quot;)<br>        outputs = model.generate(**inputs)<br>        javadoc = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>        return {&quot;javadoc&quot;: javadoc}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))</pre><p>You can see it’s loading the model from /app/model this is the folder where I store the model. It’s very simple and elegant.</p><p>To deploy this, I dockerized this app with this simple dockerfile .</p><pre>FROM python:3.9-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>RUN pip install huggingface-hub transformers<br><br>RUN python -c &quot;from transformers import AutoModelForSeq2SeqLM, AutoTokenizer; \<br>    model = AutoModelForSeq2SeqLM.from_pretrained(&#39;PavelPolivka/javadocer-small&#39;); \<br>    tokenizer = AutoTokenizer.from_pretrained(&#39;PavelPolivka/javadocer-small&#39;); \<br>    model.save_pretrained(&#39;/app/model&#39;); \<br>    tokenizer.save_pretrained(&#39;/app/model&#39;)&quot;<br><br># Copy the rest of the application code into the container<br>COPY . .<br><br># Expose the FastAPI app&#39;s port<br>EXPOSE 8000<br><br># Run the FastAPI app<br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Here, you can see that I downloaded my model from hugging face during the docker build. It ensures that the container can spin very fast if need be.</p><p>To deploy this, I used <a href="https://sliplane.io/">SlipLane</a>. Again, it is as easy as giving it access to the GitHub repo, where you have that simple Python app and the dockerfile.</p><p>To this this new API you can call it with curl like so:</p><pre>curl -X POST &quot;https://sliplane.instance.com/generate_javadoc&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;code&quot;: &quot;public int add(int a, int b) { return a + b; }&quot;}&#39;</pre><p>You can see the whole code on my <a href="https://github.com/PavlikPolivka/ai-auto-javadoc-api">GitHub</a>.</p><h3>Plugin development</h3><p>Now we have all the building blocks we need to create that IntelliJ plugin.</p><p>Create an empty Gradle Java project. I used Kotlin pipelines, so the examples will be with Kotlin pipelines.</p><p>Your build file will look something like this.</p><pre>plugins {<br>    id(&quot;java&quot;)<br>    id(&quot;org.jetbrains.intellij&quot;) version &quot;1.17.4&quot;<br>}<br><br>group = &quot;com.ppolivka&quot;<br>version = &quot;1.0.1&quot;<br><br>repositories {<br>    mavenCentral()<br>}<br><br>java {<br>    sourceCompatibility = JavaVersion.VERSION_17<br>}<br><br>intellij {<br>    version.set(&quot;2023.3.7&quot;)<br>    plugins.set(listOf(&quot;com.intellij.java&quot;))<br>}<br><br>dependencies {<br>    implementation(&quot;org.json:json:20240303&quot;)<br>}<br><br>tasks {<br>    buildSearchableOptions {<br>        enabled = false<br>    }<br><br>    patchPluginXml {<br>        version.set(&quot;${project.version}&quot;)<br>        sinceBuild.set(&quot;233&quot;)<br>        untilBuild.set(&quot;242.*&quot;)<br>    }<br>}</pre><p>Gradle will take care of everything and prepare the project for you.</p><p>Now you need to create plugin.xml file and GenerateJavadocAction class. Your file structure should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vz_gZCr20WC_5_qWhCUPlg.png" /></figure><p>In the plugin.xml we will define our new action, that we depend on Java, who we are, what is the name of the plugin.</p><pre>&lt;idea-plugin&gt;<br>    &lt;id&gt;com.ppolivka.javadocer&lt;/id&gt;<br>    &lt;name&gt;AI Auto Javadoc Generator&lt;/name&gt;<br>    &lt;description&gt;Generates Javadoc for methods using an AI-powered API.&lt;/description&gt;<br>    &lt;vendor email=&quot;polivka.pavel@gmail.com&quot; url=&quot;https://ppolivka.com&quot;&gt;Pavel Polivka&lt;/vendor&gt;<br><br>    &lt;depends&gt;com.intellij.modules.platform&lt;/depends&gt;<br>    &lt;depends&gt;com.intellij.modules.java&lt;/depends&gt;<br><br>    &lt;actions&gt;<br>        &lt;action id=&quot;GenerateJavadocAction&quot; class=&quot;com.ppolivka.javadocer.GenerateJavadocAction&quot;<br>                text=&quot;Generate Javadoc&quot; description=&quot;Generates Javadoc for the selected method&quot;&gt;<br>            &lt;add-to-group group-id=&quot;GenerateGroup&quot; anchor=&quot;last&quot;/&gt;<br>            &lt;keyboard-shortcut keymap=&quot;$default&quot; first-keystroke=&quot;ctrl alt shift J&quot;/&gt;<br>        &lt;/action&gt;<br>    &lt;/actions&gt;<br>&lt;/idea-plugin&gt;</pre><p>In the action Java class we will do the actual Javadoc generation and placement.</p><p>Let’s define what will happen when the action is triggered.</p><pre>@Override<br>public void actionPerformed(AnActionEvent event) {<br>    Project project = event.getProject();<br>    Editor editor = event.getData(com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR);<br>    PsiFile psiFile = event.getData(com.intellij.openapi.actionSystem.CommonDataKeys.PSI_FILE);<br><br>    if (project == null || editor == null || psiFile == null) {<br>        return;<br>    }<br><br>    PsiElement elementAtCaret = psiFile.findElementAt(editor.getCaretModel().getOffset());<br>    PsiMethod method = PsiTreeUtil.getParentOfType(elementAtCaret, PsiMethod.class);<br><br>    if (method == null) {<br>        JOptionPane.showMessageDialog(null, &quot;No method found at cursor position.&quot;);<br>        return;<br>    }<br><br>    String javadoc = generateJavadocFromApi(method);<br>    if (javadoc != null) {<br>        insertJavadoc(project, psiFile, method, javadoc);<br>    }<br>}</pre><p>We are looking where the caret is in the editor. Trying to see if its inside a method. If so we will take that method and call our API for it.</p><pre>private String generateJavadocFromApi(PsiMethod method) {<br>    try {<br>        String apiUrl = &quot;https://sliplane.instance.com/generate_javadoc&quot;;<br>        URL url = new URL(apiUrl);<br>        HttpURLConnection connection = (HttpURLConnection) url.openConnection();<br>        connection.setRequestMethod(&quot;POST&quot;);<br>        connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json; utf-8&quot;);<br>        connection.setDoOutput(true);<br><br>        // Create JSON payload using JSONObject for valid JSON encoding<br>        JSONObject payload = new JSONObject();<br>        payload.put(&quot;code&quot;, method.getText());<br><br>        try (OutputStream os = connection.getOutputStream()) {<br>            byte[] input = payload.toString().getBytes(&quot;utf-8&quot;);<br>            os.write(input, 0, input.length);<br>        }<br><br>        // Read API response<br>        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), &quot;utf-8&quot;));<br>        StringBuilder response = new StringBuilder();<br>        String responseLine;<br>        while ((responseLine = br.readLine()) != null) {<br>            response.append(responseLine.trim());<br>        }<br><br>        // Extract Javadoc comment from JSON response (assuming API returns {&quot;javadoc&quot;: &quot;...&quot;})<br>        String jsonResponse = response.toString();<br>        JSONObject jsonResponseObject = new JSONObject(jsonResponse);<br>        return jsonResponseObject.getString(&quot;javadoc&quot;);<br><br>    } catch (Exception e) {<br>        e.printStackTrace();<br>        JOptionPane.showMessageDialog(null, &quot;Error calling API: &quot; + e.getMessage());<br>    }<br>    return null;<br>}</pre><p>Then we take that generated Javadoc and place it into the editor.</p><pre>private void insertJavadoc(Project project, PsiFile psiFile, PsiMethod method, String javadoc) {<br>    ApplicationManager.getApplication().invokeLater(() -&gt;<br>            WriteCommandAction.runWriteCommandAction(project, () -&gt; {<br>                // Format the Javadoc to ensure correct multiline structure<br>                StringBuilder formattedJavadoc = new StringBuilder(&quot;/**\n&quot;);<br>                for (String line : javadoc.split(&quot;\n&quot;)) {<br>                    formattedJavadoc.append(&quot; * &quot;).append(line.trim()).append(&quot;\n&quot;);<br>                }<br>                formattedJavadoc.append(&quot; */&quot;);<br><br>                // Create the Javadoc comment element<br>                PsiElement comment = JavaPsiFacade.getElementFactory(project)<br>                        .createCommentFromText(formattedJavadoc.toString(), null);<br><br>                // Insert the formatted Javadoc before the method&#39;s parent to ensure proper placement<br>                PsiElement addedComment = method.getParent().addBefore(comment, method);<br><br>                // Commit the document to ensure it reflects the changes<br>                PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(<br>                        PsiDocumentManager.getInstance(project).getDocument(psiFile)<br>                );<br>                PsiDocumentManager.getInstance(project).commitDocument(<br>                        PsiDocumentManager.getInstance(project).getDocument(psiFile)<br>                );<br>            })<br>    );<br>}</pre><p>And that’s it. To test it we can call ./gradlew runIde it will open a new IntelliJ instance where the plugin is already “installed”. To build it you can call ./gradlew buildPlugin . It will build a .zip file that you can upload to the <a href="https://plugins.jetbrains.com/">JetBrains Store</a>.</p><p>You can view the full source code for this on my <a href="https://github.com/PavlikPolivka/ai-javadoc">GitHub</a>.</p><p>And you can check out the plugin on <a href="https://plugins.jetbrains.com/plugin/25759-ai-auto-javadoc-generator">JetBrains Marketplace</a>.</p><h3>Summary</h3><p>I learned a lot during this whole project. I feel like I grasped the basics of AI development, and got more comfortable with Python. This whole plugin is not “production ready”, the model I trained is based on the T5 small so it’s not as smart as it could be but did not want to spend a huge amount of time on this, this was more or less a learning exercise.</p><p>Hope this article helps you to understand that AI development does not need to be hard or complicated. To get speak peaks from my next side project you can follow me on <a href="https://x.com/pavel_polivka">X</a>.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b89052aa5e" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/developing-ai-powered-javadoc-intellij-plugin-b3b89052aa5e">Developing AI-powered Javadoc IntelliJ plugin</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>