<?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 Nebiyu Elias on Medium]]></title>
        <description><![CDATA[Stories by Nebiyu Elias on Medium]]></description>
        <link>https://medium.com/@nebiyuelias1?source=rss-b1544ac23390------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A9a_3O-FV7XolfFUDyW4oQ.jpeg</url>
            <title>Stories by Nebiyu Elias on Medium</title>
            <link>https://medium.com/@nebiyuelias1?source=rss-b1544ac23390------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:23:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nebiyuelias1/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[Top 5 ways you should be using copilot]]></title>
            <link>https://medium.com/@nebiyuelias1/top-5-ways-you-should-be-using-copilot-7fa92e83364e?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa92e83364e</guid>
            <category><![CDATA[copilot-programming]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 05:17:45 GMT</pubDate>
            <atom:updated>2024-06-22T05:17:45.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmho9j9MlJl8B1JS9vd6Jw.jpeg" /><figcaption>Why the goggles man?</figcaption></figure><p>I’m currently in grad school and one of the cool perks I’ve received as a student is the <a href="https://github.com/edu/students">GitHub Student Developer Pack</a>. This pack has tons of offers that would help students in their software engineering journey. Luckily, <a href="https://github.com/features/copilot">GitHub Copilot</a> is also included in this pack. I’m thankful for this opportunity and I’m able to use this tool for free.</p><p>In this article I will show you 5 ways you should utilize the AI pair programming tool. It has personally helped me to be more productive and I hope it will help you too.</p><p>So without further ado, I will show you ways you should be using GitHub Copilot on VS Code from my personal experience.</p><h4>1. Chatting with Copilot</h4><p>After you install the extension, there is a new button for “Chat”. This means you don’t have to leave your favorite coding editor to have a conversation. You can open the chat when you’re feeling lonely as well 😄. Here I asked Copilot “how to start a successful startup in a third world country?”. But the response isn’t what I expected. I guess this tool is not politically motivated as the “you know who” competitor. That’s good to know honestly! Only programming! Yay!</p><p>One thing I like about the chat here is that the history is going to be preserved next time you open the workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*R01vzMHq0psavSJXJ83xCQ.png" /><figcaption>Copilot assists only in programming related questions</figcaption></figure><h4>2. Scaffold a new project</h4><p>Who has time for starting a new project from scratch anyways? On the chat you can type/ for commands and you can use the /new command to create a new workspace. Just explain what you want and it should show you a preview of what the workspace is going to look like. If this ain’t going making you productive then what will?</p><p>As an example I asked it to create a browser extension scaffold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*X743mLbk6yJI_iOx8WxO9w.png" /><figcaption>I’m satisfied with the suggestion</figcaption></figure><p>If you agree and click on the Create Workspace button, it will create the workspace for you automatically.</p><h4>3. Generate commands</h4><p>As developers there are so many commands we need to remember as we work with different projects. It could sometimes be intimidating. But don’t worry too much as the future is bright and you don’t have to remember much.</p><p>Let’s suppose I somehow forgot the git command for initializing a repository. I will use the @terminal option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Zr-yrDwZAOqTrCIGEqvvIw.png" /><figcaption>I forgot git init 😄</figcaption></figure><p>If you hover next to the command, there should be an option to insert the command to your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*1SZDRs5gjqfwl6Bui7F6rQ.png" /><figcaption>You don’t have to type any command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpKkxIDXDjWJUdQQhzW-Og.png" /><figcaption>The command was automatically typed for me and I just pressed enter</figcaption></figure><h4>4. Write commit messages</h4><p>This is one of my favorite features of copilot by far. It will generate commit messages for you automatically. The source control option now has a new button right next to the commit message textbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*S_Z05g5XhadyoLXUn5X0QQ.png" /><figcaption>Look at the stars!</figcaption></figure><p>It will try it’s best to figure out a good commit message based on the changes you’re making and the files you’ve added to the staging area. It’s not always perfect and sometimes it comes up with a very generic message. I would suggest to break your changes into smaller parts and add them separately to the staging area to have a better commit message.</p><p>Look at the commit message it generated for the first commit message. Normally I would use a message like init repo . Not bad I have to say.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*vpAOwVdCE64_6ccv5R1npw.png" /><figcaption>Commit message that was auto generated by Copilot</figcaption></figure><h4>5. Explaining stuff</h4><p>As a developer it’s not uncommon to open a file and have a hard time to understand what the code is doing. So in this kind of situation you can always ask Copilot for explaining it to you like a five year old. Because the CTO is probably busy buying toys online for his kids and would not remember what he wrote 6 months ago.</p><p>I am not well experienced with browser extension development and I don’t know much about the contents of the manifest.json file, so I will ask Copilot for explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5JWmztWGovAjVV79l47Cw.png" /><figcaption>Now there’s a Copilot context menu</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*xbMo9-3_Vk4Fc0uOgdSSnA.png" /><figcaption>The explanation</figcaption></figure><p>This should allow you to understand a lot of things without going to documentation sites or SO hopefully while you’re still in your IDE. Remember, a lot of context switching is going to drain your mental energy throughout the day. Also, that one excuse to check a documentation site is a good excuse to end up in a rabbit hole.</p><h4>Conclusion</h4><p>There you have it folks. I believe we need to embrace the AI revolution. Honestly, I don’t mind if it’s going to make my life easier. What do you think? If you have any thoughts make sure to leave them here in the comments. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa92e83364e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Top 10 VS Code Shortcuts for Productivity]]></title>
            <link>https://medium.com/@nebiyuelias1/my-top-10-vs-code-shortcuts-for-productivity-9e474b3219b1?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e474b3219b1</guid>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[editor]]></category>
            <category><![CDATA[shortcuts]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 13:09:07 GMT</pubDate>
            <atom:updated>2023-11-17T13:09:07.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKyvvJiA_cNRldmb" /><figcaption>Photo by <a href="https://unsplash.com/@atimagodie?utm_source=medium&amp;utm_medium=referral">Godfrey Nyangechi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>VS Code is without a shadow of a doubt one of the most popular IDEs loved by developers. Its lightweight nature and many extensions make it one of my favorite editors. I have been using VS Code for a while and I wanted to share some of my favorite shortcuts that I regularly use for productivity.</p><p>Some people argue that you shouldn’t even use the mouse while coding. That’s the ultimate goal and if you’re interested in doing that you should probably use something like <a href="https://neovim.io/">neovim</a>. In fact, the neovim people think VS Code is for newbies. I haven’t tried neovim yet and it’s something I would like to try but I think VS Code can be a productive tool if used properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OM4dTujf8PMSw9-e-UbWpQ.png" /><figcaption>neovim vs vscode</figcaption></figure><p>I will list my top 10 VS Code shortcuts I’ve come to use in my day-to-day life.</p><h3>1. Navigate to the left/right tabs on the editor</h3><p>When you have so many editor tabs open it becomes handy to navigate left/right without using your mouse.</p><ul><li><strong>macOS</strong>: ⌘ ⌥ ← / ⌘ ⌥ →</li><li><strong>Linux</strong>: Ctrl + [PgUp/PgDn]</li><li><strong>Windows</strong>: Ctrl + [PgUp/PgDn]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJTLdHCUJk4bUkoBspCEGw.gif" /><figcaption>Navigate to the left/right tabs</figcaption></figure><h3>2. Show Integrated Terminal</h3><p>This is a very simple but effective shortcut you can use to easily open or close the integrated IDE of the terminal. It is handy when you want to open your terminal and execute some commands quickly.</p><ul><li><strong>macOS</strong>: ⌃`</li><li><strong>Linux</strong>: Ctrl + `</li><li><strong>Windows</strong>: Ctrl + `</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C82k8W4HO0j8WmoHy9NVRA.gif" /><figcaption>Show/hide terminal</figcaption></figure><h3>3. Bracket Matching</h3><p>Brackets come in pairs and we often want to know where one bracket starts and where it ends. You can use this shortcut to see the opening and closing brackets. Just make sure your cursor is near either the opening or closing bracket.</p><ul><li><strong>macOS</strong>: ⇧⌘\</li><li><strong>Linux</strong>: Ctrl + Shift + \</li><li><strong>Windows</strong>: Ctrl + Shift + \</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMri1MI6DNPNtUA40L5qjQ.gif" /><figcaption>Matching brackets will be highlighted as soon as the cursor is near one of them</figcaption></figure><h3>4. Navigate Back To Your Previous Position</h3><p>When working on a file with hundreds of lines of code, we often jump from one position to another to understand something. Say, for example, from line 900 to 500. After looking at the code, you often want to return to your previous position. Instead of wasting time scrolling the file with your mouse, use this shortcut instead.</p><ul><li><strong>macOS</strong>: ⌃-</li><li><strong>Linux</strong>: Ctrl + Alt + -</li><li><strong>Windows</strong>: Alt+ ←</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-02uh9oIZxh-lZjEdLZFdw.gif" /><figcaption>Go back</figcaption></figure><h3>5. Navigate To The Start/End of Current Word</h3><p>You can use this simple shortcut to move your cursor to either the left or right of the current word.</p><ul><li><strong>macOS</strong>: ⌥ + [← / →]</li><li><strong>Linux</strong>: Ctrl + c</li><li><strong>Windows</strong>: Ctrl + [← / →]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXkSFV_1BCeIZfL3-G84dw.gif" /><figcaption>Navigate to the start/end of the current word</figcaption></figure><h3>6. Select Multiple Occurrences Of The Same Word</h3><p>Let’s say you have some variable called <em>count</em> and you want to select all the occurrences of the word one by one. You can use this shortcut to select all the occurrences one by one.</p><ul><li><strong>macOS</strong>: ⌘D</li><li><strong>Linux</strong>: Ctrl + D</li><li><strong>Windows</strong>: Ctrl + D</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiRsjm1GJEQzwftZqxLRng.gif" /><figcaption>Select all cents variables</figcaption></figure><h3>7. Move Line Up/Down</h3><p>You can use this shortcut to move an entire line of code up/down without using cut and paste.</p><ul><li><strong>macOS</strong>: ⌥↓ / ⌥↑</li><li><strong>Linux</strong>: Alt + [↑ / ↓]</li><li><strong>Windows</strong>: Alt + [↑ / ↓]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asjhbpreG_j-LztoucZERg.gif" /><figcaption>Move a line of code up/down</figcaption></figure><h3>8. Show Search</h3><p>VS Code is very good at indexing the files inside a directory when you open an entire workspace. As a result, it can do a very good job of searching for words across many different files. I often use this shortcut when I’m looking for some word and I don’t know which file has this word. You can simply open the search explorer using this shortcut.</p><ul><li><strong>macOS</strong>: ⇧⌘F</li><li><strong>Linux</strong>: Ctrl + Shift + F</li><li><strong>Windows</strong>: Ctrl + Shift + F</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztq4tyuZl4OhPSJFfP5i6g.gif" /><figcaption>Show search explorer</figcaption></figure><h3>9. Toggle line comment</h3><p>This is also another simple but very good shortcut. We often want to quickly comment and uncomment a line of code inside a file.</p><ul><li><strong>macOS</strong>: ⌘/</li><li><strong>Linux</strong>: Ctrl + /</li><li><strong>Windows</strong>: Ctrl + /</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBf2ltNjAVIzX_s00gBJAw.gif" /><figcaption>Toggle comment</figcaption></figure><h3>10. Close Editor Window</h3><p>Let’s say you are done working with the current open editor tab and you want to close it. Then you can use this very simple but very simple shortcut to close the open editor tab.</p><ul><li><strong>macOS</strong>: ⌘W</li><li><strong>Linux</strong>: Ctrl + W</li><li><strong>Windows</strong>: Ctrl + W</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aojvwZuYLChNaFAK_3MOA.gif" /><figcaption>Close editor tab</figcaption></figure><h3>Conclusion</h3><p>I hope you’ve learned something new from this article. Let me know your favorite shortcuts in the comment section. Here’s an official cheat sheet of vs code shortcuts:</p><ul><li>Windows: <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf</a></li><li>macOS: <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf</a></li><li>Linux: <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e474b3219b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief introduction to WebAssembly]]></title>
            <link>https://medium.com/@nebiyuelias1/a-brief-introduction-to-webassembly-cd283147220c?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd283147220c</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[emscripten]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 13:25:33 GMT</pubDate>
            <atom:updated>2023-02-05T13:29:44.569Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is WebAssembly?</h3><h4>WebAssembly 101 for web developers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*6v_5rrZ6JZHmt4uQe26TJA.png" /><figcaption>WebAssembly logo</figcaption></figure><h4>Introduction</h4><p>If you’ve been in the web development ecosystem long enough you’ve probably heard about <a href="https://webassembly.org/">WebAssembly</a> (or Wasm for short). It’s a nascent technology compared to the general history of the web. You know it’s a relatively new technology because most cool kids have not yet added the term to their resumes. Your initial thought about WebAssembly is that it’s fast and you would be correct. When we say WebAssembly is fast we are comparing it against something and that something is JavaScript. JavaScript is an unavoidable language in web development and it’s undoubtedly the King of the front-end world. But WebAssembly is not trying to dethrone JavaScript by any means. In fact, it’s expected people will use WebAssembly alongside JavaScript for the web.</p><h4>WebAssembly in a nutshell</h4><p>According to <a href="https://developer.mozilla.org/en-US/docs/WebAssembly">MDN’s WebAssembly pages</a>:</p><blockquote>WebAssembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++, C# and Rust with a compilation target so that they can run on the web. It is also designed to run alongside JavaScript, allowing both to work together.</blockquote><p>In a nutshell, it means:</p><ul><li>You can run programming languages other than JavaScript in your browser. Your browser’s engine was only meant to run JavaScript code previously but now it can run code written in other languages such as C/C++, Rust, C#, and even Cobol.</li><li>WebAssembly is a low-level language similar to Assembly and it has a compact binary format. This will allow us to run code on the web at near-native speed.</li><li>It’s not meant to be a replacement for JavaScript on the web. It’s supposed to complement JavaScript. Using the WebAssembly JavaScript APIs, you can load WebAssembly modules into a JavaScript app and share functionality between the two. This allows you to take advantage of WebAssembly’s performance and power and JavaScript’s expressiveness and flexibility in the same apps, even if you don’t know how to write WebAssembly code.</li></ul><p>WebAssembly is being developed as an open standard via the <a href="https://www.w3.org/wasm/">W3C WebAssembly Working Group</a> and <a href="https://www.w3.org/community/webassembly/">Community Group</a>. This is like the ultimate geek club where all the major browser vendors send in their representatives and they geek out all things related to WebAssembly. This guarantees all major modern browsers will have support for WebAssembly by default.</p><figure><img alt="Major browsers will have support for WebAssembly by default." src="https://cdn-images-1.medium.com/max/500/1*N8odUxMf2ORQn_eqMNfQWw.png" /><figcaption>All the major browsers support WebAssembly</figcaption></figure><h4>Why do we need WebAssembly anyways?</h4><p>Now let’s take a bit of JavaScript history lesson to understand the need for WebAssembly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*T89sMiWVYiL4PX3wfeeqfQ.jpeg" /><figcaption>JavaScript history on the History channel</figcaption></figure><p>As I have mentioned earlier when we say WebAssembly is fast we’re comparing it against JavaScript and we’re sort of implying JavaScript isn’t as fast as we wanted it to be. JavaScript is a high-level, flexible, and expressive language. Because of that, it was able to gain good adoption even though it has some quirks. But the ease of use costs performance. There’s always that tradeoff in programming when you do lots of abstraction.</p><figure><img alt="JavaScript has some quirks" src="https://cdn-images-1.medium.com/max/500/1*OcOy6jPLlT2QxkPqegwoCA.png" /><figcaption>JavaScript has some quirks</figcaption></figure><p>When JavaScript was created back in 1995 it wasn’t fast. It was OK for JavaScript not to be fast because the web apps of the time were not that complicated. But slowly web apps started to get more complex and there was an inherent need to make JavaScript fast. Browser engines started adding something called a just-in-time (JIT) compiler to run JavaScript faster. As JavaScript was running, the JIT could see patterns and make the code run faster based on those patterns. I suggest you read <a href="https://hacks.mozilla.org/2017/02/a-crash-course-in-just-in-time-jit-compilers/">this</a> article by <a href="https://twitter.com/linclark">Lin Clark </a>to understand JIT compilers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*K1MhFcbnT98BbOsXsnnCIQ.png" /><figcaption>This image was taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><p>Thanks to the introduction of JIT compilers, browsers are now able to run JavaScript code significantly faster. We have run into performance problems, however, when trying to use JavaScript for more intensive use cases like 3D games, Virtual and Augmented Reality, computer vision, image/video editing, and a number of other domains that demand native performance. WebAssembly is trying to bring that kind of performance to the web. With WebAssembly, hopefully, you will be able to use powerful video editing software like Adobe Premier Pro directly on the web.</p><h4>What makes WebAssembly fast?</h4><p>For you to be able to run JavaScript code, the browser’s JS engine has to turn your high-level instruction into machine code the computer understands. You and the machine talk in a different language. The browser’s JS engine will do a number of tasks to turn your high-level code into machine code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*MqQ2Vs-BmI28-_mD7j_jew.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><p>Let’s try to understand the difference between WebAssembly and JavaScript by zooming in on those tasks:</p><h4>Parsing</h4><p>JavaScript source gets parsed into something called an Abstract Syntax Tree (AST). From there, the AST is converted to an intermediate representation called bytecode. In contrast, WebAssembly<strong> doesn’t</strong> need to go through this transformation because it is already an intermediate representation. It just needs to be decoded and validated to make sure there aren’t any errors in it. This is less time spent by the JS engine for WebAssembly code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*66iokOdzB8TisapYno5EoQ.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><h4>Compiling + optimizing</h4><p>JavaScript is compiled during the execution of the code. Depending on what types are used at runtime, multiple versions of the same code may need to be compiled. But WebAssembly starts off much closer to machine code. The JS engine doesn’t have to spend a lot of time trying to optimize WebAssembly code as it’s already optimized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9Gq3IufJGSx_34jLWILQog.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><h4>Reoptimizing</h4><p>Sometimes the JS engine has to throw out an optimized version of the code and retry it. This happens when assumptions that the JIT makes based on running code turn out to be incorrect. In WebAssembly, the JS engine doesn’t have to go through re-optimization cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*OHK5BpTxAG7j9NC1Dx4rJQ.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><h4>Executing</h4><p>Executing code in WebAssembly is generally faster. Many of the optimizations that JITs make to JavaScript (such as type specialization) just aren’t necessary with WebAssembly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ODPlkaxBOJ3n6FriAkgqsQ.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><h4>Garbage collection</h4><p>In JavaScript, the developer doesn’t have to worry about clearing out old variables from memory when they aren’t needed anymore. Instead, the JS engine does that automatically using something called a garbage collector.</p><p>This can be a problem if you want predictable performance, though. You don’t control when the garbage collector does its work, so it may come at an inconvenient time. Most browsers have gotten pretty good at scheduling it, but it’s still overhead that can get in the way of your code’s execution.</p><p>At least for now, WebAssembly does not support garbage collection at all. Memory is managed manually (as it is in languages like C and C++). While this can make programming more difficult for the developer, it does also make performance more consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qnT0oPfNsM8KLTb9hhM1RA.png" /><figcaption>The image is taken from <a href="https://hacks.mozilla.org/">https://hacks.mozilla.org/</a></figcaption></figure><p>The key takeaways are:</p><ul><li>WebAssembly doesn’t need to be parsed because it’s already in an intermediate format. It just needs to be decoded.</li><li>The JS engine doesn’t spend a lot of time trying to optimize WebAssembly code as it would with JavaScript.</li><li>In WebAssembly there is no re-optimization.</li><li>The execution step is faster.</li><li>Since you will be doing memory management yourself there’s no need for garbage collection by the JS engine.</li></ul><p>In many cases, WebAssembly will outperform JavaScript. This is why it will be better to do performance-intensive tasks with WebAssembly.</p><h4>A Practical Example</h4><p>Now let’s look at a practical demo of WebAssembly. I have a C code that uses the <a href="https://www.opengl.org/">OpenGL</a> library to display a rotating cube. You can find the C source code <a href="https://github.com/nebiyuelias1/wasm_demo/blob/main/cube.c">here</a>. First, let me run it on my local machine to show you it works. This means I have to compile the C code myself using:</p><pre>gcc cube.c -lGL -lGLU -lglut</pre><p>This compiles the code and creates a binary file called <strong>a.out</strong> and I can run the compiled binary using:</p><pre>./a.out</pre><p>When I do this, a new window is opened with the rotating cube:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*XTcv8yWQc7Oz-qoVWpb_DA.png" /><figcaption>A spinning cube example</figcaption></figure><p>Now, let’s use WebAssembly to run this same code on the browser. But we need to compile the C source code into WebAssembly. For that, we will use a tool called <a href="https://emscripten.org/">Emscripten</a>. With Emscripten properly installed on your machine run the following command to compile the C code to WebAssembly:</p><pre>emcc -s LEGACY_GL_EMULATION=1 -o index.html cube.c</pre><p>The options we’ve passed in with the command are as follows:</p><ul><li><strong>-s LEGACY_GL_EMULATION=1 </strong>—<strong> </strong>this enables support for a number of legacy desktop OpenGL 1.x features. This is related to OpenGL and you don’t have to be concerned about it.</li><li>-o index.html — Specifies that we want Emscripten to generate an HTML page to run our code in (and a filename to use), as well as the wasm module and the JavaScript &quot;glue&quot; code to compile and instantiate the wasm so it can be used in the web environment.</li></ul><p>At this point in your source directory you should have:</p><ul><li>The binary wasm module code (index.wasm)</li><li>A JavaScript file containing glue code to translate between the native C functions, and JavaScript/wasm (index.js)</li><li>An HTML file to load, compile, and instantiate your wasm code, and display its output in the browser (index.html)</li></ul><p>Now to run the example we need to run the index.html file using something like <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">LiveServer</a>. You need to run your HTML file through an HTTP server (http://). If everything goes well, you should see the following in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxbPKZbJnBf3QLgc_5EDsQ.png" /><figcaption>A screenshot of the spinning cube on my web browser.</figcaption></figure><p>This is running directly in your web browser all thanks to WebAssembly.</p><h4>Conclusion</h4><p>This brings us to the end of the article. If you’ve reached this stage, thank you very much for your time. I have tried to explain what WebAssembly is and how it brings performance to the web. You have to know WebAssembly is not trying to replace JavaScript. Whenever you have a bottleneck in your JavaScript code you can surgically replace it with WebAssembly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd283147220c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I used cron jobs to automate repetitive tasks on my Django web app]]></title>
            <link>https://medium.com/@nebiyuelias1/how-i-used-cron-jobs-to-automate-repetitive-tasks-on-my-django-web-app-18f2f7a8ab26?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f2f7a8ab26</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 18:44:42 GMT</pubDate>
            <atom:updated>2022-12-29T12:41:09.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cbEVMf7pubAMjUJm" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I needed to build a web app for a client. Because I’m comfortable with Django, I decided to use it. These days I’m being blown away by the <a href="https://fastapi.tiangolo.com/">FastAPI</a> framework, to be honest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*03uYkwMwNoOdgChui61UBw.jpeg" /><figcaption>I created this meme on imgflip.com</figcaption></figure><p>But let’s drop the unnecessary debate about the best framework for now. Instead, let me tell you about the problem I had to solve (as developers that’s our job). There were tasks or jobs that had to be done repetitively. I could do them manually but I have no time to do that, unfortunately (you see I’m a very busy guy) and I don’t have the budget to hire someone (I think it’s not morally right to hire people for boring jobs).</p><p>I needed to do two things:</p><ul><li>Delete images that are no longer used in the app. The web app I was building allows users to upload images. But some of the images might be useless at some point (they may no longer be used). So in order not to waste precious storage resources I have to delete the useless images.</li><li>Send email notifications to users about some important matters. I had to inform users about due payments.</li></ul><p>How would you have solved this problem? I would love to hear about it. Anyways, I decided to use <strong>cron jobs</strong> for this problem.</p><h4>Cron jobs for automating repetitively boring tasks</h4><p>So what is <strong>cron </strong>you ask? Our good old friend Wikipedia says:</p><blockquote>The <strong>cron</strong> command-line utility is a <a href="https://en.wikipedia.org/wiki/Job_scheduler">job scheduler</a> on <a href="https://en.wikipedia.org/wiki/Unix-like">Unix-like</a> <a href="https://en.wikipedia.org/wiki/Operating_system">operating systems</a>. Users who set up and maintain software environments use cron to schedule jobs (commands or <a href="https://en.wikipedia.org/wiki/Shell_script">shell scripts</a>), also known as <strong>cron jobs</strong>, to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the <a href="https://en.wikipedia.org/wiki/Internet">Internet</a> and downloading <a href="https://en.wikipedia.org/wiki/Email">email</a> at regular intervals.</blockquote><p>The <strong><em>cron</em></strong> command line utility has been in existence for a very long. It goes as far as the 70s.</p><p>The two main components of cron are:</p><ul><li>The <strong>crontab (cron table)</strong>: a configuration file to specify which tasks(commands) you want to run.</li><li>The <strong>cron daemon</strong>: a daemon that runs in the background and reads scripts from the crontab.</li></ul><p>You define the tasks you want to run in the crontab file. Then the cron daemon executes the tasks based on a schedule you’ve specified. It’s as simple as that.</p><p>To achieve our requirement we will create a Django management command that will periodically be executed from the UNIX crontab.</p><p>I’m assuming you already have some experience with Django so I’m not going to go over the little details such as creating virtual environments or setting up a Django project. The entire project can be found on <a href="https://github.com/nebiyuelias1/phison-realestate">GitHub</a>.</p><h4>Delete Image Management Command</h4><p>Here’s the <strong>PropertyImage</strong> model that will be responsible for storing the images:</p><pre>class PropertyImage(TimeStampedModel):<br>    &quot;&quot;&quot;A model that represents an image for a property.&quot;&quot;&quot;<br>    image = models.ImageField(<br>        upload_to=&quot;uploads/property_images/&quot;,<br>        null=False,<br>        blank=False,<br>        width_field=&quot;width&quot;,<br>        height_field=&quot;height&quot;,<br>    )<br><br>    property = models.ForeignKey(<br>        Property,<br>        null=True,<br>        blank=True,<br>        related_name=&quot;images&quot;,<br>        on_delete=models.CASCADE,<br>    )<br><br>    # The height of the image.<br>    height = models.IntegerField(editable=False)<br><br>    # The width of the image.<br>    width = models.IntegerField(editable=False)</pre><p>As you can see, it has an <strong>image</strong> field and a foreign key field called <strong>property</strong>. We allow <strong>PropertyImage </strong>objects to be saved to our database without a property<strong>. </strong>This is because the ForeignKey has null set to True. This is where the problem lies. We can have <strong>PropertyImage</strong> objects without a linked property.</p><p>In order to delete PropertyImage objects that are not linked to a property, we will create a custom <a href="https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/">Django management command</a>. Again, I’m assuming you’ve some knowledge about creating custom management commands. So <a href="https://github.com/nebiyuelias1/phison-realestate/blob/main/phison_realestate_backend/phison_realestate_backend/core/management/commands/removeimages.py">here’s the class</a> that we will be using:</p><pre>class Command(BaseCommand):<br>    help = &quot;Deletes product images that are not linked with a product&quot;<br><br>    def handle(self, *args: Any, **options: Any) -&gt; Optional[str]:<br>        property_images = PropertyImage.objects.filter(property=None)<br>        property_images_count = property_images.count()<br><br>        if property_images_count &gt; 0:<br>            try:<br>                property_images.delete()<br>            except Exception:<br>                raise CommandError(&quot;Something went wrong trying to delete images&quot;)<br><br>            self.stdout.write(<br>                self.style.SUCCESS(<br>                    f&quot;Successfully deleted {property_images_count} property images&quot;<br>                )<br>            )<br>        else:<br>            self.stdout.write(<br>                self.style.WARNING(<br>                    &quot;There are no unlinked property images to be deleted&quot;<br>                )<br>            )</pre><p>In a nutshell, the above command looks for images that are not linked to a property. It then deletes them. But unfortunately, this does not delete the images from disk. It only deletes a database row. This is a common problem in Django and someone has created a reusable app called <a href="https://github.com/un1t/django-cleanup">Django Cleanup</a>. It basically listens for the signal sent by the model when it’s deleted and erases the file from disk. We could have done it ourselves but we don’t have to reinvent the wheel you know.</p><p>For the app to work you just need to add it to INSTALLED_APPS in your settings file then it will do everything on its own:</p><pre>INSTALLED_APPS = (<br>    ...,<br>    &#39;django_cleanup.apps.CleanupConfig&#39;,<br>)</pre><p>Because the above command is in a file called <a href="https://github.com/nebiyuelias1/phison-realestate/blob/main/phison_realestate_backend/phison_realestate_backend/core/management/commands/removeimages.py">removeimages.py</a>, we use the following command to run it:</p><pre>python manage.py removeimages</pre><h4>Send Notification Management Command</h4><p>Now onto our second management command. It should send in-app and email notifications to our users who have due payments. So here’s what the command looks like:</p><pre>class Command(BaseCommand):<br>    help = &quot;Send notification to buyers about due payment&quot;<br><br>    def handle(self, *args: Any, **options: Any) -&gt; Optional[str]:<br>        duration = ExpressionWrapper(<br>            F(&quot;deadline&quot;) - F(&quot;today&quot;), output_field=fields.DurationField()<br>        )<br><br>        payment_schedules = BuyerPaymentSchedule.objects.annotate(<br>            today=Now(), duration=duration<br>        ).filter(<br>            status=BuyerPaymentSchedule.PENDING,<br>            duration__lte=timedelta(days=7),<br>            duration__gt=timedelta(days=0),<br>            is_notification_sent=False,<br>        )<br>        payment_schedules_count = payment_schedules.count()<br>        if payment_schedules_count &gt; 0:<br>            try:<br>                context_list = list(<br>                    payment_schedules.values(<br>                        &quot;buyer__customer__name&quot;,<br>                        &quot;buyer__customer__pk&quot;,<br>                        &quot;duration&quot;,<br>                        &quot;buyer__customer__email&quot;,<br>                        &quot;buyer__property__property_type&quot;,<br>                        &quot;deadline&quot;,<br>                        &quot;amount&quot;,<br>                    )<br>                )<br><br>                notify_buyers_about_due_payment(context_list)<br><br>                payment_schedules.update(is_notification_sent=True)<br><br>                self.stdout.write(<br>                    self.style.SUCCESS(<br>                        f&quot;Successfully sent notifications to {payment_schedules_count} buyer(s)&quot;<br>                    )<br>                )<br>            except Exception as e:<br>                raise CommandError(<br>                    &quot;Something went wrong trying to send notifications&quot;, e<br>                )<br>        else:<br>            self.stdout.write(<br>                self.style.NOTICE(&quot;There are no notifications to be sent&quot;)<br>            )</pre><p>Let me briefly explain the above command:</p><ul><li>We define a duration object, which is a time difference between the deadline and the current time.</li><li>We then try to filter objects that are still in a pending state (payment has not been made yet) and have a deadline in 7 days or less.</li><li>After filtering the objects we try to send emails in bulk to the recipients. Here is the code that achieves that:</li></ul><pre>def notify_buyers_about_due_payment(context_list):<br>    connection = mail.get_connection()<br><br>    msgs = []<br>    notifications = []<br><br>    for item in context_list:<br>        body = render_to_string(&quot;email/buyer_due_payment.txt&quot;, item).strip()<br>        msg = EmailMultiAlternatives(<br>            &quot;Reminder about due payment&quot;, body=body, to=[item[&quot;buyer__customer__email&quot;]]<br>        )<br>        msg.attach_alternative(body, &quot;text/html&quot;)<br><br>        msgs.append(msg)<br><br>        notification = Notification(<br>            user_id=item[&quot;buyer__customer__pk&quot;],<br>            notification_type=Notification.PAYMENT_DUE,<br>            data=json.dumps(item, indent=4, sort_keys=True, default=str),<br>        )<br>        notifications.append(notification)<br><br>    # Create in app notification objects<br>    Notification.objects.bulk_create(notifications)<br><br>    # Send the emails in a single call<br>    connection.send_messages(msgs)<br>    # The connection was already open so send_messages() doesn&#39;t close it.<br>    # We need to manually close the connection.<br>    connection.close()</pre><p>We execute this command using the following:</p><pre>python manage.py sendnotification</pre><h4><strong>Adding the cron jobs</strong></h4><p>Now we have the management commands ready, we need to configure our crontab. The following commands are useful for configuring cron jobs:</p><ul><li><strong>crontab -e</strong>: edits crontab entries to add, delete, or edit cron jobs.</li><li><strong>crontab -l</strong>: list all the cron jobs for the current user.</li><li><strong>crontab -u username -l</strong>:<strong> </strong>list another user&#39;s crons.</li><li><strong>crontab -u username -e</strong>:<strong> </strong>edit another user&#39;s crons.</li></ul><p>The<strong>crontab -l </strong>command shows the following output on my environment:</p><pre>MAILTO=&quot;nebiyuelias1@gmail.com&quot;<br>SHELL=&quot;/bin/bash&quot;<br>0 0 * * 0 bash /home/phisonrealestate/repositories/phison-realestate/phison_realestate_backend/utility/remove-images.sh</pre><p>In the above example:</p><ul><li><a href="https://www.cyberciti.biz/faq/linux-unix-crontab-change-mailto-settings/"><strong>MAILTO</strong></a> is a configuration setting that allows me to receive emails about command outputs. Whenever the commands are executed, I get to receive an email of the output from the commands. Here’s an example of the email I’m receiving:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ir7MOndhPXTEzcW9QtsmvQ.png" /><figcaption>Cron job output email</figcaption></figure><ul><li><strong>SHELL </strong>is set to the bash binary.</li><li><strong>0 0 * * 0 </strong>is a schedule configuration<strong>.</strong> We will talk more about this.</li><li><strong>bash /home/phisonrealestate/repositories/phison-realestate/phison_realestate_backend/utility/remove-images.sh </strong>is the command that will be executed.</li></ul><h4>How does cron schedule work?</h4><p>In the above example, we have the schedule: <strong>0 0 * * 0</strong>. What is the meaning? That’s the schedule format for cron and you have to know how it works. Here is the general format:</p><pre>*   *   *   *   *  sh /path/to/script/script.sh<br>|   |   |   |   |              |<br>|   |   |   |   |      Command or Script to Execute        <br>|   |   |   |   |<br>|   |   |   |   |<br>|   |   |   |   |<br>|   |   |   | Day of the Week(0-6)<br>|   |   |   |<br>|   |   | Month of the Year(1-12)<br>|   |   |<br>|   | Day of the Month(1-31)  <br>|   |<br>| Hour(0-23)  <br>|<br>Min(0-59)</pre><p>We use five fields to represent the time to execute the command:</p><ul><li>The first field is for specifying <strong>minutes</strong> (0–59)</li><li>The second field is for specifying <strong>hours</strong> (0–23)</li><li>The third field is for specifying <strong>days</strong> (1–31)</li><li>The fourth field is for specifying the <strong>month of the year</strong> (1–12)</li><li>The fifth field is for specifying the <strong>day of the week </strong>(0–6). Here, 0 is Sunday.</li></ul><p>Let’s look at our cron tab one more time.</p><pre>0 0 * * 0 bash /home/phisonrealestate/repositories/phison-realestate/phison_realestate_backend/utility/remove-images.sh</pre><p>It means we will execute the <strong>remove-images.sh </strong>script every Sunday. The <strong>remove-images.sh</strong> file contains the following:</p><pre>#!/bin/bash<br><br>python manage.py removeimages</pre><p>Now, let’s add another entry to our crontab. Use the following command to edit your crontab:</p><pre>crontab -e</pre><p>This should open the file in your configured editor. Add the following entry to your crontab:</p><pre>0 0 * * * bash /home/phisonrealestate/repositories/phison-realestate/phison_realestate_backend/utility/send-notifications.sh</pre><p>Now, pay closer attention to the schedule: <strong>0 0 * * *</strong>. This means the command will be run at the beginning of every day. This helps us to send important notifications to our users.</p><h4>Conclusion</h4><p>There you’ve it. This is how I used cron jobs to automate tasks on my web app. In this example, I used Django but the same logic could be applied to other frameworks. Cron has nothing to do with programming language or framework. If you’ve reached this point, I really appreciate it. Feel free to ask any questions or make suggestions.</p><h4><strong>References</strong></h4><p>Use the following links to learn more about the inner workings of cron. I have to mention it helped me a lot.</p><ul><li><a href="https://en.wikipedia.org/wiki/Cron">cron</a></li><li><a href="https://www.freecodecamp.org/news/cron-jobs-in-linux/">How to Automate Tasks with cron Jobs in Linux</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f2f7a8ab26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the meaning behind those ~ and ^ symbols in your package.json file?]]></title>
            <link>https://medium.com/@nebiyuelias1/what-is-the-meaning-behind-those-and-symbols-in-your-package-json-file-ef27ba6bf7eb?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef27ba6bf7eb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[semver]]></category>
            <category><![CDATA[packagejson]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 13:43:35 GMT</pubDate>
            <atom:updated>2022-12-14T13:43:35.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M9b444LdKV2Hf5qW" /><figcaption>An example of what you would find in a package.json file</figcaption></figure><p>I’m sure you have something like the following in your package.json file:</p><pre>  &quot;dependencies&quot;: {<br>    &quot;@angular/animations&quot;: &quot;~9.0.1&quot;,<br>    &quot;@angular/cdk&quot;: &quot;^9.0.0&quot;<br>  }</pre><p>Have you ever wondered about the meaning behind those <strong>~</strong> and <strong>^</strong> symbols? Let me explain about <a href="http://Versions of the npm packages in the dependencies section of your package.json file follow what’s called Semantic Versioning (SemVer), an industry standard for software versioning aiming to make it easier to manage dependencies. Libraries, frameworks or other tools published on npm should use SemVer in order to clearly communicate what kind of changes projects can expect if they update.">SemVer</a>.</p><p>Versions of the npm packages in the dependencies section of your package.json file follow what’s called Semantic Versioning (SemVer), an industry standard for software versioning aiming to make it easier to manage dependencies. Libraries, frameworks, or other tools published on npm should use SemVer in order to clearly communicate what kind of changes projects can expect if they update.</p><p>This is how Semantic Versioning works according to the official website:</p><pre>&quot;package&quot;: &quot;MAJOR.MINOR.PATCH&quot;</pre><ul><li>The <strong>MAJOR</strong> version should increment when you make incompatible API changes (breaking changes).</li><li>The <strong>MINOR</strong> version should increment when you add functionality in a backwards-compatible manner.</li><li>The <strong>PATCH</strong> version should increment when you make backwards-compatible bug fixes.</li></ul><p>This means that PATCHes are bug fixes and MINORs add new features but neither of them break what worked before. Finally, MAJORs add changes that won’t work with earlier versions.</p><p>Now suppose our project depends on an npm package called <strong>awesome-package</strong>. In our package.json file, we can pin a specific version of this package like this:</p><pre>&quot;awesome-package&quot;: &quot;1.2.13&quot;</pre><p>But what if the maintainer of the package adds bug fixes? You don’t want to miss out on the latest PATCHes because there might be security vulnerabilities with the previous version. That’s when you’ll use the tilde (~) character. Here’s an example of how to allow updates to any 1.2.x version:</p><pre>&quot;awesome-package&quot;: &quot;~1.2.13&quot;</pre><p>But now what if you also want to get MINOR and PATCH updates? After all, the MINOR and PATCH updates will be backwards-compatible. This means you can update to the latest MINOR and PATCH updates without breaking anything. The caret (^) allows npm to install future MINOR and PATCH updates. If you want to use version 1.x.x of the awesome-package, you would use:</p><pre>&quot;awesome-package&quot;: &quot;^1.2.13&quot;</pre><h4>Conclusion</h4><p>We use the tilde (~) and caret (^) characters to get the latest updates without worrying about breaking changes. I hope you’ve found this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef27ba6bf7eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be careful when using default arguments in Python]]></title>
            <link>https://medium.com/@nebiyuelias1/be-careful-when-using-default-arguments-in-python-fd92df94efee?source=rss-b1544ac23390------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd92df94efee</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[default-arguments]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Nebiyu Elias]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 19:43:13 GMT</pubDate>
            <atom:updated>2021-12-16T19:43:13.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u1wDbfY5fidnUAq7" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I was tasked with fixing a very nasty bug in Python. It’s related to my incorrect assumptions about <strong>default arguments</strong> in the language. I think a lot of beginners like myself make such kinds of assumptions and I wanted to share my experience so that you won’t make the same mistake that I did. I hope Python won’t say “Gotcha” to you after reading this article.</p><p>So I was using a function with a <a href="https://www.geeksforgeeks.org/default-arguments-in-python/amp/">default argument</a> like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497f026ab478d1b99f276f318a07d749/href">https://medium.com/media/497f026ab478d1b99f276f318a07d749/href</a></iframe><p>The <strong>pause_item </strong>function (I should say method since the code is actually defined inside a class, but it’s OK for the time being) has two default arguments, <strong>user</strong> is given a default value of <strong>None </strong>and <strong>paused_at </strong>is<strong> </strong>given a default value of<strong> timezone.now()</strong>. In case you’re wondering about the <a href="https://github.com/django/django/blob/bf7afe9c4e21f5fe5090c47b2b6ffc5a03a85815/django/utils/timezone.py#L208"><strong>timezone.now()</strong></a><strong> </strong>call, it’s a piece of code related to the <a href="https://www.djangoproject.com/">Django</a> framework. It uses Python’s <a href="https://docs.python.org/3/library/datetime.html">datetime</a> module to create a datetime object that is set to the current date and time. The bug is related to the <strong>paused_at</strong> default argument. I’m calling the function that’s defined above like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d955a037d400b562dd435a050938b3c8/href">https://medium.com/media/d955a037d400b562dd435a050938b3c8/href</a></iframe><p>As you can see, I do provide a value for the <strong>user</strong> parameter, but I’m not providing a value for the <strong>paused_at</strong> parameter. My assumption was that whenever I call the <strong>pause_item</strong> function without providing a value it will always be assigned a <strong>timezone.now() </strong>that is set to the current date and time. But my assumption was not right and it comes from me not knowing a very simple fact about the Python language. You have been warned! Of course, since we were dealing with time, the bug that resulted from this incorrect assumption was horrible. It was hard to debug and it was not obvious at all, at least for me that is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Be7soFV-DgoOn6Cy" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s look at a very simple example to understand the problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c87ad09271fbac0e2b58d5571f7b4b23/href">https://medium.com/media/c87ad09271fbac0e2b58d5571f7b4b23/href</a></iframe><p>Here I define a very simple function with a default argument, the empty list. So you might have expected an output that looks like the following:</p><pre>[5]<br>[10]<br>[15]</pre><p>But you will be surprised to see the actual output:</p><pre>[5] <br>[5, 10] <br>[5, 10, 15]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xnt2XoyJ7Lwg4L6E" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You must be saying shut the front door at this point, just bear with me. If you look at Python’s <a href="https://docs.python.org/3.4/tutorial/controlflow.html#default-argument-values">documentation</a> closely, you will find the following warning:</p><blockquote><strong>Important warning:</strong> The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.</blockquote><p>The key point to note here is: <strong>default mutable argument</strong>. The doc is saying if you use a mutable object as a default argument it will be evaluated only once. So in the previous example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c87ad09271fbac0e2b58d5571f7b4b23/href">https://medium.com/media/c87ad09271fbac0e2b58d5571f7b4b23/href</a></iframe><p>When the function is defined for the first time(I am not saying when it’s called, I’m saying when it’s defined), Python evaluates the default argument and accumulates(caches) it somehow. So before you even call the function, the <strong>items</strong> argument has been assigned a value of []. On subsequent calls, items will not be reassigned to an empty list. Instead, it will hold on to whatever result it had previously. This is the key point I was missing.</p><p>Default mutable arguments can be a disaster if you don’t know what you’re doing. In my case <strong>timezone.now() </strong>is the default mutable argument that made me go nuts. To make matters even worse, it was being set before I even call the function, when the Python code is loaded for the first time. To prove this point, let me show you an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e37065c82406bcd898e2d93b04f08dd/href">https://medium.com/media/4e37065c82406bcd898e2d93b04f08dd/href</a></iframe><p>In the above example, I define a <strong>say_selam </strong>function that has a default argument of type <strong>Person </strong>(the mutable default argument in this case) being set. Inside the <strong>Person</strong> class, I have some initialization code. At the time of creation, I added a print statement that says ‘Instantiating a person’. So without me calling anything, I would see the following output by just running the program:</p><pre>Instantiating a person</pre><p>This proves that the default argument is evaluated and will be accumulated for later use. This concludes my attempt to explain a personal experience I had with Python. Thank you for reading till this point!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd92df94efee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>