<?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"><channel><title><![CDATA[madco]]></title><description><![CDATA[madco]]></description><link>https://blog.madco.me</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1604093431056/a7tYDK_ga.jpeg</url><title>madco</title><link>https://blog.madco.me</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 19 Nov 2026 00:15:49 GMT</lastBuildDate><atom:link href="https://blog.madco.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to get a Base wallet and claim your winnings as a DigiByte miner]]></title><description><![CDATA[You can mine DigiByte on PotPool without a wallet or any ETH. You only need both to claim your winnings on Base. Here is how the wallet part works.]]></description><link>https://blog.madco.me/how-to-get-a-base-wallet-and-claim-your-winnings-as-a-digibyte-miner</link><guid isPermaLink="true">https://blog.madco.me/how-to-get-a-base-wallet-and-claim-your-winnings-as-a-digibyte-miner</guid><category><![CDATA[digibyte]]></category><category><![CDATA[Ethereum]]></category><category><![CDATA[base]]></category><category><![CDATA[crypto wallet]]></category><category><![CDATA[Web3]]></category><category><![CDATA[mining]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Thu, 29 Oct 2026 12:24:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5f9c832465cd015fab581598/1d3a2774-f889-4f65-9f99-cd7392f39fc4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PotPool is a 0% fee <a href="https://www.digibyte.org/">DigiByte</a> pool. Its block rewards buy <a href="https://megapot.io/r/VMD83F">Megapot</a> lottery tickets once a day, and winnings are paid in USDC on <a href="https://base.org">Base</a>. For a miner who has only worked with BTC and its forks, the chain part is the unfamiliar bit. This is what you need to know.</p>
<h2>Mining needs an address, not a wallet</h2>
<p>Set your worker name to <code>0xYourAddress.rig1</code>, point the rig at the pool and you are mining. The pool does not need ETH or a deposit. Winnings can only be claimed by the address in the username, so use one you can open.</p>
<h2>EVM and Base in two paragraphs</h2>
<p>The EVM (Ethereum Virtual Machine) is the shared computer that Ethereum and its sibling chains run smart contracts on. PotPool's payout contract is one of those programs.</p>
<p>Base is a layer 2 built on Ethereum. It bundles many transactions into one and posts that to Ethereum, like a bus lane on the same highway. Fees stay at a few cents and confirmation is fast, and the result still ends up on Ethereum. So almost any wallet that supports Ethereum also supports Base, and the address is the same <code>0x…</code> string. The same address also works on other EVM chains such as Arbitrum, Optimism and Polygon.</p>
<h2>Pick a wallet</h2>
<p>Three wallets I can point you to. Each has a plain link and a referral link:</p>
<ul>
<li>MetaMask: <a href="https://metamask.io">plain link</a> or <a href="https://link.metamask.io/rewards?referral=AJV1GE">referral link</a></li>
<li>Zerion: <a href="https://zerion.io">plain link</a> or <a href="https://link.zerion.io/referral?code=8E5TFYKXV">referral link</a></li>
<li>Coinbase Wallet: <a href="https://wallet.coinbase.com">plain link</a> or <a href="https://wallet.coinbase.com/invite/friends/WQHRGD59">referral link</a></li>
</ul>
<p>The referral links may earn me a reward and cost you nothing. The plain links earn me nothing. Rainbow, Rabby and plenty more work just as well. Create one, copy the address and keep the recovery phrase offline. Use a wallet you control, not an exchange deposit address.</p>
<h2>Why claiming costs a little ETH</h2>
<p>Claiming is a transaction on Base, so it needs a few cents of ETH for gas. The network requires it, and the fee goes to the network, not to me or the pool.</p>
<p>It looks like the classic scam, but a scam asks you to send money to someone before they release your winnings. Gas is paid by your own wallet when you sign the claim. It works like the fee you pay to send BTC, or like paying for gas to go on a trip in a car you already own.</p>
<p>The contract checks your claim against a Merkle proof, so only the winning address can pull its share, and only once. A second claim on the same round is rejected.</p>
<p>Claim from the round page and nowhere else, and never send ETH or USDC to anyone who messages you about your winnings. I will never ask for that.</p>
<h2>Is the contract safe to read?</h2>
<p>The contract is immutable by design. If I find a bug, I deploy a new contract and retire the old one. Basescan is linked from every round page. Round 1's contract is the one exception: its source isn't verified, so it shows as raw bytecode instead of readable code.</p>
<p>If you have no ETH on Base yet, wait until a round shows winnings for your address, then buy or bridge a few dollars of ETH on Base and claim. Do it within 14 days: unclaimed USDC goes back into later ticket buys.</p>
<h2>Links</h2>
<ul>
<li>The original post: <a href="https://potpool.party/blog/new-to-the-chain-thing">https://potpool.party/blog/new-to-the-chain-thing</a></li>
<li>The X article: <a href="https://x.com/Mobilpadde/status/2115778678869155852">https://x.com/Mobilpadde/status/2115778678869155852</a></li>
<li>How it works: <a href="https://potpool.party/how-it-works">https://potpool.party/how-it-works</a></li>
<li>Past rounds: <a href="https://potpool.party/rounds">https://potpool.party/rounds</a></li>
<li>Telegram: <a href="https://t.me/potpoolparty">https://t.me/potpoolparty</a></li>
</ul>
<p>It's a lottery, so most tickets win little or nothing.</p>
<hr />
<p>Not financial advice 🫠</p>
]]></content:encoded></item><item><title><![CDATA[I changed PotPool's payout window from 6 hours to the whole round]]></title><description><![CDATA[PotPool, a 0% fee DigiByte pool, now counts your whole round instead of the last 6 hours, so a short outage will not cost you your share.]]></description><link>https://blog.madco.me/potpool-payouts-whole-round</link><guid isPermaLink="true">https://blog.madco.me/potpool-payouts-whole-round</guid><category><![CDATA[digibyte]]></category><category><![CDATA[mining]]></category><category><![CDATA[crypto]]></category><category><![CDATA[Web3]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Sun, 25 Oct 2026 21:54:08 GMT</pubDate><content:encoded><![CDATA[<p>PotPool is a 0% fee DigiByte mining pool. Its block rewards buy Megapot lottery tickets once a day. I built it, and this week I changed the rule that decides who shares in the winnings.</p>
<h2>What was wrong</h2>
<p>The old rule counted only the last 6 hours of work before a round closed. A round can run for several days, because it closes when the daily buy at about 16:00 UTC succeeds, and that needs at least 1,000 DGB in the pool.</p>
<p>So a miner could submit work for days, lose their connection 6 hours before the close, and get nothing for any of it. I tried to defend that to myself and couldn't.</p>
<h2>The new rule</h2>
<p>Every share you submit between a round opening and closing adds to your weight, and each share is weighted by the work it took to find. Your payout is:</p>
<blockquote>
<p>round prize × your round weight ÷ total round weight of all eligible miners</p>
</blockquote>
<p>Two checks keep idle connections out. To be eligible you need:</p>
<ul>
<li>at least one valid share in the 24 hours before the round closes</li>
<li>at least 0.05% of the total work of all eligible miners</li>
</ul>
<p>A reboot or a router hiccup no longer wipes out the work you already did. You only need to be back and submitting before the close.</p>
<h2>The tradeoff</h2>
<p>It's never too late to join. But weight builds up over the whole round, so someone who joins on day three earns less than someone who was there from day one. If you're thinking about it, the best time is before the next round opens, so you get all of it.</p>
<h2>Mobile</h2>
<p>I also fixed the mobile layout of the FAQ and the My stats page, so they no longer overflow the screen.</p>
<h2>The long shot</h2>
<p>It's a lottery, and most days win little or nothing. I built it for the long shot, and you can see every round so far on the <a href="https://potpool.party/rounds">rounds page</a>.</p>
<hr />
<p>Original post: <a href="https://potpool.party/blog/potpool-payouts-are-now-fairer">PotPool payouts are now fairer</a></p>
<p>Announcements and setup help happen in the <a href="https://t.me/potpoolparty">PotPool Telegram</a>.</p>
<p><em>Not financial advice.</em></p>
]]></content:encoded></item><item><title><![CDATA[All about the Bubble Sorting Algorithm]]></title><description><![CDATA[Micro-optimizations #3]]></description><link>https://blog.madco.me/all-about-the-bubble-sorting-algorithm</link><guid isPermaLink="true">https://blog.madco.me/all-about-the-bubble-sorting-algorithm</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[sorting]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Benchmark]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Tue, 15 Mar 2022 06:49:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647325117997/g_33HQWbW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-bubble-sort">Bubble Sort</h1>
<h2 id="heading-what">What</h2>
<p>The <code>Bubble Sort</code> is - of cause - an sorting algorithm. It's a simple one of it's kind, as you'll later see.</p>
<p>If you in the wild, wild west of CompSci sees an alorithm called <code>Sinking Sort</code>, it'll look a lot like the <code>Bubble Sort</code>, and really, it is the same thing. These are sometimes refered to as one or the other.</p>
<p>A <code>Bubble Sort</code> is not nearly as perfomant as some of its successors - and is mainly used as an educational algorithm nowadays.</p>
<h2 id="heading-performance">Performance</h2>
<p>As I mentioned, <code>Bubble Sort</code> is definitely not one of the fastest sorting algorithms out there, meaning its <a target="_blank" href="https://en.wikipedia.org/wiki/Bubble_sort#Performance">O-notion is <code>O(n^2)</code></a>. which is never too good. Meaning it's slow.</p>
<h2 id="heading-why">Why</h2>
<p>Why would you use the <code>Bubble Sort</code> then? Well, it's super easy to implement, which is also why people use it, and learn from it as - again - it's a great starting point.</p>
<h2 id="heading-try">Try</h2>
<p>Below is an embed from <a target="_blank" href="https://hasty.dev">hasty.dev</a>, this is interactive. Try it yourself and check if you can speed up the <code>Bubble Sort</code>!</p>
<iframe style="border:none;border-radius:5px" src="https://hasty.dev/e/3JMz13IUz9qrnsiOEyFz5A" width="100%" height="600"></iframe>

<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Micro-optimizations #2]]></title><description><![CDATA[Sorting Algorithms - Short]]></description><link>https://blog.madco.me/micro-optimizations-2</link><guid isPermaLink="true">https://blog.madco.me/micro-optimizations-2</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[sorting]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Benchmark]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Tue, 15 Mar 2022 06:16:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647323544861/fr9VbL9Vo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-sorting-algorithms">Sorting Algorithms</h1>
<p>If you have ever studied the field of Computer Science [CompSci], you might have heard about the algorithms known as <code>Sorting Algorithms</code>. </p>
<p>These are quite common in a lot of CompSci algorithms - especially, you've gussed it, in sorting of lists - even though you might not be using it yourselves, it is actually a common use-case for interviewers to ask you to implement during the job inetrview. Thus, will post about some of these algorithms to help you through it.</p>
<h2 id="heading-what">What</h2>
<p>Since the dawn of CompSci, researchers have been wondering how to sort - and even more importantly - optimize lists. This can be useful for a magnitude of reasons, but mainly to show a sorted list of sorts. Be it numbers or alphabetical - or even alpha-numeric, or something completely fourth!</p>
<h2 id="heading-why">Why</h2>
<p>A lot of reasearcher do sorting for the fun of it, another reason to do this, is to find an even better implementation of even the fastest sorting algorithm out there. This will of course bring a fame with it, and be honest, who doesn't want to have that fame of the inventor of a great sorting algorithm.</p>
<p>Because, as most of us knows, with fame comes money and money rules the world nowadays.</p>
<h2 id="heading-how">How</h2>
<p>Further in this series, I'll be exploring some sorting algorithms in JavaScript. All of which can be found - and compared - here: https://hasty.dev/shorts</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Pages are like Notebooks]]></title><description><![CDATA[I've for a while have been tinkering with what I think JavaScript'ers have been missing - namely a way to make Jupyter-like notebooks! So I started…]]></description><link>https://blog.madco.me/pages-are-like-notebooks</link><guid isPermaLink="true">https://blog.madco.me/pages-are-like-notebooks</guid><category><![CDATA[Benchmark]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Fri, 11 Mar 2022 23:05:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647039844971/uHJg-2b1s.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-the-idea">The Idea</h1>
<p>I've for a while have been tinkering with what I think JavaScript'ers have been missing - namely a way to make Jupyter-like notebooks!</p>
<p>So I started building. Actually been on this since November 12th - so about a month. Lot's of stuff is going to happen still!</p>
<h2 id="heading-the-past">The past</h2>
<p>Back on the 12th of November it couldn't do much, in fact you were only able to build a page using the source code!</p>
<p>This couldn't spark much joy to any people, so that brings us to the present. </p>
<h2 id="heading-the-present">The present</h2>
<p>Now you are able to build pages as your heart desires! still missing some documentation on how to use the page-builder, but it's definitely a step in the right direction!</p>
<h2 id="heading-the-future">The future</h2>
<p>No one knows what the future will bring, not even me for this project! What I do know, though, is that there wil have to be some docs upon how to use the scripting of the pages. Hopefully also a more intuitive way to use the page builder and so on.</p>
<p>I'd love to get some way to work on a saved notebook again, as for now it is not possible to get working on an old saved notebook, which is quite a shame! </p>
<h1 id="heading-the-page-itself">The page itself</h1>
<p>The notebooks are easily managed by a notion-esque idea-inspired way to build a page - in this case, a notebook.</p>
<p>You start with mostly nothing, then add along all the fields you'd possibly need for a long coding experiment.</p>
<p>It all starts with a box - a magic box one might say. This box allows you to add any element you'd like.</p>
<p>For now though, there are four elements to choose from:</p>
<ul>
<li>Header - A header element</li>
<li>Text - A text-area element</li>
<li>Code - The snippets to run and global to run from</li>
<li>Comment - A super simple comment - for less text that Text, but not quite a heading</li>
</ul>
<p>Checkout the <a target="_blank" href="https://hasty.dev/page">/page</a> to get a taste off all the elements. It'll show off all of the elements!</p>
<h1 id="heading-the-end">The End</h1>
<p>Thanks for reading! </p>
<p>By now you must be super excited to get the pages - notbooks - a try! You without further ado, <a target="_blank" href="https://hasty.dev/page">hasty.dev/page</a> and a demo is also available on <a target="_blank" href="https://hasty.dev/page/demo">hasty.dev/page/demo</a> 🥰</p>
<p>Pst. There's also a shortcut to get a compelely clean slate by navigating to <a target="_blank" href="https://hasty.dev/page/new">hasty.dev/page/new</a> 💡</p>
]]></content:encoded></item><item><title><![CDATA[Micro-optimizations #0]]></title><description><![CDATA[The Prequel]]></description><link>https://blog.madco.me/micro-optimizations-0</link><guid isPermaLink="true">https://blog.madco.me/micro-optimizations-0</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Benchmark]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Thu, 18 Nov 2021 00:16:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637192642958/hjVtfaJ_A.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="prequel">Prequel</h1>
<p>On the 27th of October, I started a new - launched - a new project. This is a project about one thing, and one thing only. Namely benchmarking code.</p>
<p>As for now, it's only available in JavaScript, but I <em>might</em> be on to adding another.</p>
<p>I realized that this tool was best for micro-benchmarking as everthing is on one line only. This has been fixed in the later releases of <a target="_blank" href="https://hasty.dev">hasty.dev</a> - which is the name of the project and also the url.</p>
<p>Though, in this series I'll be working with micro-optimizations of JS.</p>
<p>Not much else to say in this post.</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Micro-optimizations #1]]></title><description><![CDATA[Spread and Numbers]]></description><link>https://blog.madco.me/micro-optimizations-1</link><guid isPermaLink="true">https://blog.madco.me/micro-optimizations-1</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Benchmark]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Wed, 17 Nov 2021 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637191787247/KhN76WtcB.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-spread">Spread</h1>
<p>The love, and arguebly one of my favourites, things of ES6 is the <code>Spread</code>-operator. This has made my work so much easier. Also, makes everything look so lovely!</p>
<p>Here comes the question:</p>
<blockquote>
<p>Is the <code>Spread</code>-operator faster or slower than using the complete object?</p>
</blockquote>
<iframe style="border:none;border-radius:5px;box-shadow:rgba(0, 0, 0, 0.1) 0px 4px 6px -1px, rgba(0, 0, 0, 0.06) 0px 2px 4px -1px" src="https://embed.hasty.dev/#eyJnbG9iYWwiOiJjb25zdCBkYXRhID0gWyB7IHRoaW5nOiB0cnVlIH0seyB0aGluZzogZmFsc2UgfSBdIiwidGFza3MiOlt7ImlkIjoiUXBrNDZkMjV6ZGVULVcwaWxTelpVIiwiY29kZSI6ImRhdGEuZmlsdGVyKCh4KSA9PiB4LnRoaW5nKSIsIm9wcyI6MCwicGN0IjowLCJlcnJvciI6IiIsImNvbG9yIjp7Im1vZGVsIjoicmdiIiwiY29sb3IiOls1NSwxOTAsMTA2Ljk5OTk5OTk5OTk5OTk3XSwidmFscGhhIjoxfX0seyJpZCI6ImZRVHJ5NkU2N3hpV2JIRlJIdExjSyIsImNvZGUiOiJkYXRhLmZpbHRlcigoeyB0aGluZyB9KSA9PiB0aGluZykiLCJvcHMiOjAsInBjdCI6MCwiZXJyb3IiOiIiLCJjb2xvciI6eyJtb2RlbCI6InJnYiIsImNvbG9yIjpbNTUsMTkwLDEzOC45NTk4MTQ4NTQ3Mjc4XSwidmFscGhhIjoxfX1dfQ%3D%3D" width="100%" height="564"></iframe>

<p>As you can see, using the complete object everytime seems like a better choice. Except for readability, which I do prefer over a such small optimization.</p>
<h1 id="heading-numbers">Numbers</h1>
<p>How about numbers? Imagine you're in an interview. The interviewer asks you how to parse an <em>integer</em>. You think to yourself:</p>
<blockquote>
<p>Huh? That's a silly question.</p>
</blockquote>
<p>Though, is it? Is it really a <em>silly</em> question? Well, I don't think it is, there are a magnitude of ways to parse an integer in JavaScript.</p>
<p>Imagine we have this variable</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> n = <span class="hljs-string">"1"</span>;
</code></pre>
<p>How would you parse <code>n</code> into an integer <code>d</code>? You could for example do:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> d = <span class="hljs-built_in">parseInt</span>(n);
</code></pre>
<p>Easy peasy! Well, if I were to be your interviewer, I'd say: </p>
<blockquote>
<p>Sure, but are there any other ways?</p>
</blockquote>
<p>To this, you should not hesitate, but prompt answer:</p>
<blockquote>
<p>Yes! There are many ways. Do you want to see another?</p>
</blockquote>
<p>Then you quickly write another way below like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> d = <span class="hljs-built_in">Number</span>(n);
</code></pre>
<p>This would show that you do know some options, but what if you swiftly wrote below the like again, whilst talking</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> d = +n;
</code></pre>
<p>I ofr one, would be super happy and kind of proud, that you'd know at least three options. I wouldn't have to more questions about numbers.</p>
<p>How about 10 options in total? Well, these might still just be some of the options, but heck. It's enough for a proper micro-benchmark.</p>
<iframe style="border:none;border-radius:5px;box-shadow:rgba(0, 0, 0, 0.1) 0px 4px 6px -1px, rgba(0, 0, 0, 0.06) 0px 2px 4px -1px" src="https://embed.hasty.dev/#eyJnbG9iYWwiOiJjb25zdCBuID0gXCIxMDFcIiIsInRhc2tzIjpbeyJpZCI6IlFwazQ2ZDI1emRlVC1XMGlsU3paVSIsImNvZGUiOiJjb25zdCBkID0gK24iLCJvcHMiOjAsInBjdCI6MCwiZXJyb3IiOiIiLCJjb2xvciI6eyJtb2RlbCI6InJnYiIsImNvbG9yIjpbNTUsMTkwLDE3OC4zOTE1Njg3MDk4NDk1NF0sInZhbHBoYSI6MX19LHsiaWQiOiJmUVRyeTZFNjd4aVdiSEZSSHRMY0siLCJjb2RlIjoiY29uc3QgZCA9IE51bWJlcihuKSIsIm9wcyI6MCwicGN0IjowLCJlcnJvciI6IiIsImNvbG9yIjp7Im1vZGVsIjoicmdiIiwiY29sb3IiOls1NSwxOTAsMTA2Ljk5OTk5OTk5OTk5OTk3XSwidmFscGhhIjoxfX0seyJpZCI6IlhjNV9nRFlON0ZqdmJsTWVyS18tZiIsImNvZGUiOiJjb25zdCBkID0gbioxIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzU1LDE5MCwxMTIuOTk4MTYyOTQ0MTEyNjRdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiUmdoNEZNSGxlYnlvZUxaQm9fa1FlIiwiY29kZSI6ImNvbnN0IGQgPSB%2Bfm4iLCJvcHMiOjAsInBjdCI6MCwiZXJyb3IiOiIiLCJjb2xvciI6eyJtb2RlbCI6InJnYiIsImNvbG9yIjpbNTUsMTA2LjcwMTYyOTM2OTEzODA4LDE5MF0sInZhbHBoYSI6MX19LHsiaWQiOiJCZ0t5SG03R0ZqVTBPNE9HOVBjU2ciLCJjb2RlIjoiY29uc3QgZCA9IE1hdGgucm91bmQobikiLCJvcHMiOjAsInBjdCI6MCwiZXJyb3IiOiIiLCJjb2xvciI6eyJtb2RlbCI6InJnYiIsImNvbG9yIjpbNTUsMTkwLDE3MC43NzYwMTM3MTAyMDQ5OF0sInZhbHBoYSI6MX19LHsiaWQiOiI3X2ttRWROeC1hRUtSeTZrYnplWFAiLCJjb2RlIjoiY29uc3QgZCA9IE1hdGguZmxvb3IobikiLCJvcHMiOjAsInBjdCI6MCwiZXJyb3IiOiIiLCJjb2xvciI6eyJtb2RlbCI6InJnYiIsImNvbG9yIjpbNTUsMTgwLjEyOTE1MTM3Mjg2NTE4LDE5MF0sInZhbHBoYSI6MX19LHsiaWQiOiIwUVhjMGpFNjdNM21IU2hsVmVkNTkiLCJjb2RlIjoiY29uc3QgZCA9IE1hdGguY2VpbChuKSIsIm9wcyI6MCwicGN0IjowLCJlcnJvciI6IiIsImNvbG9yIjp7Im1vZGVsIjoicmdiIiwiY29sb3IiOls1NSwxOTAsMTY4LjI5MjUyNjA2NjU3Njc4XSwidmFscGhhIjoxfX0seyJpZCI6IlpjNUo1RGRCSUFfNERXNk1mR3pvZCIsImNvZGUiOiJjb25zdCBkID0gcGFyc2VJbnQobiwgMTApIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzU1LDE5MCwxNzMuMzc0NjY0OTE2MTQ2ODhdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiVkZWdXFjRkZoY2ZmR0piVmhWcGpIIiwiY29kZSI6ImNvbnN0IGQgPSBwYXJzZUZsb2F0KG4pIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzU1LDE5MCwxNzIuMjA0NjI0OTg5NTM5MTNdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiZTI5c0R5TnAwODBONmtIX2h2M0lKIiwiY29kZSI6ImNvbnN0IGQgPSBwYXJzZUludChuKSIsIm9wcyI6MCwicGN0IjowLCJlcnJvciI6IiIsImNvbG9yIjp7Im1vZGVsIjoicmdiIiwiY29sb3IiOls1NSwxOTAsMTEwLjY0MzY4NzY0NTYwNzldLCJ2YWxwaGEiOjF9fV19" width="100%" height="564"></iframe>

<p>In your journey of bettering yourself in the world of JS, you'd try such a benchmark, just to check which of those <strong>ten</strong> options is the best. Of course, this small website can't give you advice when to use which options in which situation, but it can help you along some of the way, but lowering the guess work.</p>
<p>I found the best options, both for readability and speed, is the <code>parseInt(n, 10)</code>, as this actually tells the reader that it'll parse an integer <code>n</code> in the <code>base 10</code> format.</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Embeddable hasties 🤯]]></title><description><![CDATA[I recently - 28/10/2021 - launched a new side-project. hasty.dev is the name of it, or rather Hasty. I've an old version of this laying around for a while,]]></description><link>https://blog.madco.me/embeddable-hasties</link><guid isPermaLink="true">https://blog.madco.me/embeddable-hasties</guid><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[performance]]></category><category><![CDATA[tools]]></category><category><![CDATA[Developer Tools]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Fri, 29 Oct 2021 23:25:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1635548869481/LGqAW6lO4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="prequel-what-is-hastydevhttpshastydev">Prequel - What Is <a target="_blank" href="https://hasty.dev">Hasty.dev</a>?</h1>
<p>I recently - 28/10/2021 - launched a new side-project. <a target="_blank" href="https://hasty.dev">hasty.dev</a> is the name of it, or rather Hasty.</p>
<p>I've an old version of this laying around for a while,
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635549237954/4l5pJRQ7y.png" alt="hasty - old.png" /></p>
<p>I didn't like the design of it, so I decided to redesign it, and boom, it now looks like it does as of today. The new design speaks much more sleekness and UX, if you ask me. But I'm no designer.</p>
<blockquote>
<p>See the <code>cover</code>-image of this post or navigate to <a target="_blank" href="https://hasty.dev">hasty.dev</a>, or read even further! <a class="post-section-overview" href="#the-how">The How</a> explains it. </p>
</blockquote>
<p>I'll be repeating myself a little in this post, but not much. It's simply because, the reasoning behind this tool is quite simple, and mostly cannot be explained in many ways. Maybe.</p>
<p>Anyways, what <a target="_blank" href="https://hasty.dev">hasty.dev</a> does is to check for which line of code is faster. It does this, by you providing a <code>global</code> line of code to test from, and then a few test cases. These will then be ran by the back-end - in a super sophisticated room full of super computers (that's a lie, it's on my home server). It'll then return the results to you, for free! Yes, it's free of charge. Not even a cookie to find!</p>
<p>Now, let's get on with the embeddables.</p>
<h1 id="sequel-the-hasties">Sequel - The Hasties</h1>
<h2 id="the-what">The What</h2>
<p>What feature does any great tool require? You got it! An embeddable component! This is exactly what I just added as the latest feature of #hasty.</p>
<p>With <a target="_blank" href="https://hasty.dev">hasty.dev</a> you've got the ability to add the globals along with (or without) some tests and simply press the <em>"Embed"</em> button to get an easily embeddable piece of code, which you can embed any- and everywhere amongst the web - sometimes even natively, but this depends on the software.</p>
<p>So, what are you waiting for? Go check out the new embeddable feature, if you don't know which code to test, I've even prepared one for you: <a target="_blank" href="https://hasty.dev/#eyJnbG9iYWwiOiJjb25zdCBkYXRhID0gWyAuLi5uZXcgQXJyYXkoMTAwMCkua2V5cygpIF0iLCJ0YXNrcyI6W3siaWQiOiJOLXdQMnlGdHRNYUZLZ05SRFJnRWIiLCJjb2RlIjoiZGF0YS5maW5kKHggPT4geCA9PSA4MDApIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzE1Ni4yNTExODM4MTU0MzUzNSw1NSwxOTBdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiNU9haDV0V1YxSFV0UHZfSy0zZG04IiwiY29kZSI6ImRhdGEuZmlsdGVyKHggPT4geCA9PSA4MDApIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzE5MCw1NSwxODIuNjg0MDMzNjM1MzM5MzhdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiVHlmd3dOb29yWVpUN2VmdWk4a29aIiwiY29kZSI6ImNvbnN0IGluZGV4ID0gZGF0YS5pbmRleE9mKDgwMCk7IGRhdGFbaW5kZXhdIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzU1LDE5MCwxMDYuOTk5OTk5OTk5OTk5OTddLCJ2YWxwaGEiOjF9fV19">https://hasty.dev/#eyJnbG9iYW...</a>.</p>
<h2 id="the-why">The Why</h2>
<p>Is this even useful, you may ask. The answer to that is - of course - <strong>yes</strong>, very!</p>
<p>I, for one, am going to be using these in some posts in the future. These can even be used educationally. Simply think about it, the professor scolds the student, that some piece of code is <em>waaay</em> faster than their code, but the student won't listen without proof, but how do they test it? Well, simply hasty those two code-pieces; and bam! The student was right all along.</p>
<h2 id="the-how">The How</h2>
<p>Just navigate to <a target="_blank" href="https://hasty.dev">hasty.dev</a>, write your <em>"global"</em> code, a few test cases, and press <em>"Embed"</em>. Simple as that!</p>
<p>PS. This is an embedded hasty:</p>
<iframe style="border:none;border-radius:5px;box-shadow:var(0 0 #0000, 0 0 #0000), var(0 0 #0000, 0 0 #0000),
      var(0 0 #0000)" src="https://embed.hasty.dev/#eyJnbG9iYWwiOiJjb25zdCBkYXRhID0gWyAuLi5uZXcgQXJyYXkoMTAwMCkua2V5cygpIF0iLCJ0YXNrcyI6W3siaWQiOiJOLXdQMnlGdHRNYUZLZ05SRFJnRWIiLCJjb2RlIjoiZGF0YS5maW5kKHggPT4geCA9PSA4MDApIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzE1Ni4yNTExODM4MTU0MzUzNSw1NSwxOTBdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiNU9haDV0V1YxSFV0UHZfSy0zZG04IiwiY29kZSI6ImRhdGEuZmlsdGVyKHggPT4geCA9PSA4MDApIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzE5MCw1NSwxODIuNjg0MDMzNjM1MzM5MzhdLCJ2YWxwaGEiOjF9fSx7ImlkIjoiVHlmd3dOb29yWVpUN2VmdWk4a29aIiwiY29kZSI6ImNvbnN0IGluZGV4ID0gZGF0YS5pbmRleE9mKDgwMCk7IGRhdGFbaW5kZXhdIiwib3BzIjowLCJwY3QiOjAsImVycm9yIjoiIiwiY29sb3IiOnsibW9kZWwiOiJyZ2IiLCJjb2xvciI6WzU1LDE5MCwxMDYuOTk5OTk5OTk5OTk5OTddLCJ2YWxwaGEiOjF9fV19" width="752" height="652"></iframe>

<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Generate 16 unique avatar faces from 40 lines of easy code]]></title><description><![CDATA[In v1.0.0 I've added the ability to change the color of images. The updates are specified at the bottom of this post. Link. NB. Thanks to Lucas for this…]]></description><link>https://blog.madco.me/generate-16-unique-avatar-faces-from-40-lines-of-easy-code</link><guid isPermaLink="true">https://blog.madco.me/generate-16-unique-avatar-faces-from-40-lines-of-easy-code</guid><category><![CDATA[vanilla-js]]></category><category><![CDATA[js]]></category><category><![CDATA[generators]]></category><category><![CDATA[creativity]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Sun, 17 Oct 2021 23:44:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634507796808/DjzzZ-jv6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="my-avatars">my-avatars</h1>
<hr />
<p>In <code>v1.0.0</code> I've added the ability to change the color of images. The updates are specified at the bottom of this post. <a class="post-section-overview" href="#v100">Link</a>.</p>
<hr />
<blockquote>
<p>NB. Thanks to <a target="_blank" href="https://hashnode.com/@DemiPixel">Lucas</a> for <a target="_blank" href="https://madco.me/generate-16-unique-avatar-faces-from-40-lines-of-easy-code#ckuw60eoo0d0inus117ux1oom">this</a> comment. The math is now correct 🥳</p>
<p>If anything is wrong, please do not hesitate to correct me either 😍</p>
</blockquote>
<p>I've for a while had an idea to create avatars like https://getavataaars.com/ and such other services. Though I don't have the necessary graphical skills nor the imagination, but what I do have is code experience.</p>
<p>Thus, I decided to create a npm-package for fun. This is not the most useful package, but it's a package nonetheless. It's been quite a while since I created my last package, and to be honest, none of my packages are worth anything 🤷 But you'll only better by trying!</p>
<h2 id="why-only-16">Why only <code>16</code>?</h2>
<p>Well, to answer this question shortly, this is because I'm not good at creating graphics, nor am I not enjoying doing so. But I do enjoy to code. So I threw together a small face made in (inkscape)[https://inkscape.org/], this wasn't enough, so I decided to create another, much uglier, one too.</p>
<p>Gave me the option to pick from one of two faces. Easily! But is two enough? Nop, and now that I had two faces to choose from, I decided to create a library, that could take the individual unique pieces from each face, and generate a new unique one!</p>
<p>But how did I come to the <code>16</code> unique faces? Well, the math is simple. I have four (<code>4</code>) item-collections, each with two (<code>2</code>) items in them. By using these collections, I am able to generate <code>16</code> completely unique avatars. This can be calculated by <code>2 * 2 * 2 * 2</code> which equals to <code>16</code>.</p>
<h2 id="how-about-another">How about another?</h2>
<p>If I would add another, say, mouth the equation would be <code>2 * 2 * 2 * 3</code> which now equals to <code>24</code>! That's an increase of <code>50%</code>!</p>
<p>How about that. One more mouth and an <code>50%</code> increase. That's not too bad.</p>
<h3 id="one-more-of-each">One more of each?</h3>
<p>What if, on the other hand, I'd add another face, pair of eyes, a nose and a mouth. Then the equation would be <code>3 * 3 * 3 * 3</code> which equals to <code>81</code>! This an <code>406.25%</code> increase of unique faces! Whoop.</p>
<h3 id="more">More</h3>
<p>You can probably imagine how the equations only go up from there. Add two more mouths, a pair of eyes and five funny noses. No new faces added here. The equation is now: <code>3 * 4 * 8 * 5</code> which equals to <code>480</code> unique avatars! </p>
<p>Holy moly! This is an increase of <code>2900%</code> from the original <code>16</code>. And it only goes up from there.</p>
<h2 id="a-piece-a-day-keeps-the-repetition-away">A piece a day, keeps the repetition away</h2>
<p>What if we made an experiment, and wanted to make <code>2500</code> unique faces by the end of November. But didn't want to start until November 1st?</p>
<ul>
<li>By the end of the first day you only have a single piece, which is one (<code>1</code>) unique face. </li>
<li>By day two (<code>2</code>) you'll still have one (<code>1</code>) unique face, as a face needs at least four (<code>4</code>) items to be complete, thus you'll need four (<code>4</code>) days to generate one unique face. </li>
<li>On the fifth (<code>5</code>) day, you have two (<code>2</code>) unique faces! </li>
<li>On the sixth (<code>6</code>) day, you have four (<code>4</code>) unique faces! </li>
<li><code>...</code></li>
<li>On the ninth (<code>9</code>) day, you have <code>24</code> unique faces! </li>
<li><em>...and so fourth...</em></li>
</ul>
<p>Thus, in these <code>30</code> days you'll have <code>2500</code> unique avatars! That's a great start.</p>
<p>Imagine if you had a great day, and made two (<code>2</code>) or three(<code>3</code>) pieces instead of one (<code>1</code>)! This could easily become <code>15000</code> unique faces!</p>
<h2 id="code">Code</h2>
<p>Enough talk, show me some code, please!</p>
<p>To use this library, you can choose to use my library <a target="_blank" href="https://www.npmjs.com/package/my-avatars">my-avatars</a>, which can be downloaded from <a target="_blank" href="https://www.npmjs.com/">npm</a>. Or take a look at the source code on <a target="_blank" href="https://github.com/Mobilpadde/my-avatars">github</a>.</p>
<p>Anyways, let's get to the code.</p>
<pre><code class="lang-js"><span class="hljs-comment">// import the library and take the important classes from it. </span>
<span class="hljs-keyword">import</span> { Generator, Layer, Item } <span class="hljs-keyword">from</span> <span class="hljs-string">'my-avatars'</span>
</code></pre>
<p>As you can see, there is only three (<code>3</code>) things to import, these will make up the complete generator at last.</p>
<pre><code class="lang-js"><span class="hljs-comment">// create two face items from the example images.</span>
<span class="hljs-keyword">const</span> faceItems = [
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/face1.png'</span>),
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/face2.png'</span>),
]

<span class="hljs-comment">// add some eyes.</span>
<span class="hljs-keyword">const</span> eyeItems = [
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/eyes1.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">50</span> }),
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/eyes2.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">50</span> }),
]

<span class="hljs-comment">// a few noses.</span>
<span class="hljs-keyword">const</span> noseItems = [
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/nose1.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">200</span> }),
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/nose2.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">200</span> }),
]

<span class="hljs-comment">// and last, but not least. The mouths.</span>
<span class="hljs-keyword">const</span> mouthItems = [
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/mouth1.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">270</span> }),
  <span class="hljs-keyword">new</span> Item(<span class="hljs-string">'./images/mouth2.png'</span>, { <span class="hljs-attr">y</span>: <span class="hljs-number">270</span> }),
]
</code></pre>
<p>Take a look at the second argument, it states where to draw the item. Also note that not all of the has it. Making it optional.</p>
<p>Lot's of repetition, I'll have to figure a better way, but that will come soon enough.</p>
<p>Next up, we'll create the layers.</p>
<pre><code class="lang-js"><span class="hljs-comment">// create four new layers.</span>
<span class="hljs-keyword">const</span> faceLayer = <span class="hljs-keyword">new</span> Layer(<span class="hljs-string">'faces'</span>, <span class="hljs-number">0</span>)
<span class="hljs-keyword">const</span> eyeLayer = <span class="hljs-keyword">new</span> Layer(<span class="hljs-string">'eyes'</span>, <span class="hljs-number">1</span>)
<span class="hljs-keyword">const</span> noseLayer = <span class="hljs-keyword">new</span> Layer(<span class="hljs-string">'noses'</span>, <span class="hljs-number">2</span>)
<span class="hljs-keyword">const</span> mouthLayer = <span class="hljs-keyword">new</span> Layer(<span class="hljs-string">'mouths'</span>, <span class="hljs-number">3</span>)
</code></pre>
<p>Keep in mind the latter number, it's like the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/z-index">z-index</a> in css, it's super important. The first argument, on the other hand is just for your own convenience. This will be thrown in an error, if one occurs.</p>
<p>Now, let's add the items to the layers.</p>
<pre><code class="lang-js"><span class="hljs-comment">// add each items to the corresponding layer.</span>
faceItems.forEach(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> faceLayer.addItem(x))
eyeItems.forEach(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> eyeLayer.addItem(x))
noseItems.forEach(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> noseLayer.addItem(x))
mouthItems.forEach(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> mouthLayer.addItem(x))
</code></pre>
<p>Now for the last, but still important part.</p>
<pre><code class="lang-js"><span class="hljs-comment">// fetch where to put the generated avatar.</span>
<span class="hljs-keyword">const</span> app = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'app'</span>)

<span class="hljs-comment">// create the generator with 400x400 avatars, and put in the parent elm.</span>
<span class="hljs-keyword">const</span> g = <span class="hljs-keyword">new</span> Generator(<span class="hljs-number">400</span>, <span class="hljs-number">400</span>, app)

<span class="hljs-comment">// add each layer to the generator.</span>
g.addLayer(faceLayer)
g.addLayer(eyeLayer)
g.addLayer(noseLayer)
g.addLayer(mouthLayer)
</code></pre>
<p>Now for that all of that boilerplate is out there, let's get to the fun part!</p>
<pre><code class="lang-js">g.draw()
</code></pre>
<p>Boom! You've drawn a new, unique, avatar!</p>
<p><strong>Congratulations</strong>! 🥳</p>
<blockquote>
<p>NB. The repo with everything is right <a target="_blank" href="https://github.com/Mobilpadde/my-avatars">here</a>.</p>
</blockquote>
<hr />
<h2 id="v100">v1.0.0</h2>
<p>As per <code>v1.0.0</code> you can add now manipulate colors, it's not fast but it's there.</p>
<p>The API documentation goes as:</p>
<ul>
<li><code>Item</code><ul>
<li><code>new Item(path, opts)</code><ul>
<li><code>path</code> is the path to the image</li>
<li><code>opts</code><ul>
<li><code>x</code>: <code>Number</code> - x-coord to place the image</li>
<li><code>y</code>: <code>Number</code> - y-coord to place the image</li>
<li><code>check</code>: <code>Boolean</code> - check if the image can be found - required to <code>replace</code>-colors</li>
<li><code>replace</code>: <code>Array</code> of <code>Object</code>'s - filled with colors to replace from and to<ul>
<li><code>from</code>: <code>String</code> - color to replace from, in the format of <code>r,g,b</code> - e.g. <code>128,128,128</code></li>
<li><code>to</code>: <code>String</code> - color to replace to, in the format of <code>r,g,b</code> - e.g. <code>128,128,128</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><code>Layer</code><ul>
<li><code>new Layer(name, idx)</code><ul>
<li><code>name</code>: <code>String</code> - a friendly name to recognise</li>
<li><code>idx</code>: <code>Number</code> - the z-index of the layer</li>
</ul>
</li>
</ul>
</li>
<li><code>Generator</code><ul>
<li><code>new Generator(width, height, parentElm)</code><ul>
<li><code>width</code>: <code>Number</code> - width of the avatar</li>
<li><code>height</code>: <code>Number</code> - height of the avatar</li>
<li><code>parentElm</code>: <code>Element</code> - element to place avatar within</li>
</ul>
</li>
</ul>
</li>
</ul>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Typescripting WASM]]></title><description><![CDATA[There will be no code, whatsoever, in this article. Sorry! I'll even be a small one! But quite a few links for you. I been super interested in WebAssembly…]]></description><link>https://blog.madco.me/typescripting-wasm</link><guid isPermaLink="true">https://blog.madco.me/typescripting-wasm</guid><category><![CDATA[wasm]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Game Development]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Fri, 06 Aug 2021 20:22:33 GMT</pubDate><content:encoded><![CDATA[<h2 id="notice">Notice</h2>
<p>There will be no code, whatsoever, in this article. Sorry! I'll even be a small one! But quite a few links for you. </p>
<h2 id="the-article">The Article</h2>
<p>I been super interested in <a target="_blank" href="https://webassembly.org/">WebAssembly</a> (WASM) for quite some years, ever after I found <a target="_blank" href="https://www.rust-lang.org/">Rust</a>. Though, I've never managed to get into Rust - thus not WASM.</p>
<p>Does this have to be true though? Not exactly. I recently found this super language called <a target="_blank" href="https://www.assemblyscript.org/">AssemblyScript</a>. It's like <a target="_blank" href="https://www.typescriptlang.org/">Typescript</a> (TS), but for WebAssembly! Actually it's not quite as scary as it may sound, especially for small scripts.</p>
<p>I decided it was time to optimize my <a target="_blank" href="https://github.com/Mobilpadde/downwards">game</a>, and what better way, than to use WASM. I've heard so much great stuff about performance and speed with it.</p>
<p>So, let's get into it! </p>
<p>My game is small, and written in <a target="_blank" href="https://www.javascript.com/">Javascript</a> (JS), and I like to make stuff with it. Even games! Believe me, it's a great experience, I've made quite a few games, most of which can be found on my <a target="_blank" href="https://github.com/Mobilpadde">Github</a> - but that's not important.</p>
<p>Anyways, let's get going.</p>
<p>I've made the game in smaller components, just the way I like it, thus making it easier to switch out any of them if needed.</p>
<p>I had one component which I knew I'd do with WASM instead of plain ol' JS. Namely the <code>dither.js</code>-component.</p>
<p>Before ...</p>
<blockquote>
<p>Or rather afterwards, but let's imagine I started by doing this.</p>
</blockquote>
<p>... I did a small performance test using the Chrome Dev-Tools, with a 4x CPU slow-down.</p>
<p>Now, I'm not an expert - by any means - in the performance tab of the Dev-Tools, but I can read some numbers.</p>
<p>It ended up with an idle - only number I looked for - time of <code>291ms</code>, which is fine, but I wanted to do better! So I wrote a dither function in the new AssemblyScript I found.</p>
<p>Then it was time to do another performance test. This time the idle, with the same settings, has gone up to <code>356ms</code>!</p>
<p>That's an increase of <code>~22%</code>!</p>
<p>That's it. Thanks for reading!</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Batch importing 6.8k entries in go]]></title><description><![CDATA[I've recently decided to import 6.8k entries of crypto currencies into a database - namely Rethink. I have an old side-hustle, that never got into…]]></description><link>https://blog.madco.me/batch-importing-68k-entries-in-go</link><guid isPermaLink="true">https://blog.madco.me/batch-importing-68k-entries-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Fri, 16 Jul 2021 00:39:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626395913963/EGq9gKUK0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="what-its-all-about">What it's all about</h2>
<p>I've recently decided to import 6.8k entries of crypto currencies into a database - namely <a target="_blank" href="https://rethinkdb.com/">Rethink</a>. </p>
<p>I have an old side-hustle, that never got into business, but I still have fun making it. I started on this project four years ago, and just yet decided to pick it back up. Back then I were just getting started with <a target="_blank" href="https://golang.org/">Go</a>, and wasn't a particularly seasoned go-dev.</p>
<p>In this project I had this one function that bothered the heck out of me, as it took forever to run, alas I only had to run it once every time I re-created the database. But still too much waiting time for little <em>moi</em>.</p>
<p>Read along in the next chapter.</p>
<h2 id="the-structs">The Structs</h2>
<p>All of the scructs used in the below code are as follows:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Coin <span class="hljs-keyword">struct</span> {
    ID          <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:"id" gorethink:"id,omitempty"`</span>
    Name        <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:"name" gorethink:"name" mapstructure:"CoinName"`</span>
    Symbol      <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:"symbol" gorethink:"symbol"`</span>
    Algorithm   <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:"algorithm" gorethink:"algorithm"`</span>
    Price       <span class="hljs-keyword">float64</span> <span class="hljs-string">`json:"price" gorethink:"price"`</span>
}

<span class="hljs-keyword">type</span> Data <span class="hljs-keyword">struct</span> {
    Data <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]Coin
}
</code></pre>
<h2 id="the-usual-suspect">The Usual Suspect</h2>
<p>This one function, I decided to time using <code>time</code>. This would be done like so:</p>
<pre><code class="lang-sh">time go run . -fetch
</code></pre>
<p>The <code>fetch</code>-flag were to tell it to populate my database, stupid name now that I think about it, but it's not the one to be questioned as for now.</p>
<p>The timing returned <code>2.5m</code>, that's a lot of waiting time a busy little bee like me. The total response is below:</p>
<pre><code class="lang-sh">go run . -fetch  2.24s user 1.12s system 2% cpu 2:25.31 total
</code></pre>
<p>As you see it didn't take much CPU, but a hecka long time! So I decided to re-write it as in the next chapter.</p>
<h3 id="code">Code</h3>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">FetchCrypto</span><span class="hljs-params">(d *db.DB)</span></span> {
    dat, _ := ioutil.ReadFile(<span class="hljs-string">"coins.json"</span>)

    <span class="hljs-keyword">var</span> data Data
    json.Unmarshal(dat, &amp;data)

    <span class="hljs-keyword">for</span> _, c := <span class="hljs-keyword">range</span> data.Data {
        c.ID = <span class="hljs-string">""</span>
        <span class="hljs-keyword">if</span> c.Algorithm == <span class="hljs-string">"N/A"</span> {
            c.Algorithm = <span class="hljs-string">""</span>
        }

        r.Table(<span class="hljs-string">"coin"</span>).
            Insert(c).
            Exec(d.S)
    }
}
</code></pre>
<h2 id="the-batch-answer">The Batch Answer</h2>
<p>Now, how would one go along and rewrite such a beautifully old function? The answer might surprise you!</p>
<p><strong>Batching</strong>! Why, just because I wanted to see if I could. And success! I done it! It takes batches of one hundred currencies for every go-routine and process that, and waits for the rest to complete.</p>
<p>The timing of this one is as follows:</p>
<pre><code class="lang-sh">go run . -fetch  1.89s user 0.81s system 47% cpu 5.683 total
</code></pre>
<p>Easy peasy, right? It was - A tad more complicated though, but I love how it turned out.</p>
<h3 id="code">Code</h3>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">FetchCryptoV2</span><span class="hljs-params">(d *db.DB)</span></span> {
    dat, _ := ioutil.ReadFile(<span class="hljs-string">"coins.json"</span>)

    <span class="hljs-keyword">var</span> data Data
    json.Unmarshal(dat, &amp;data)

    <span class="hljs-keyword">var</span> wg sync.WaitGroup
    batch := <span class="hljs-number">100</span>

    coins := []coin.Coin{}
    <span class="hljs-keyword">for</span> _, c := <span class="hljs-keyword">range</span> data.Data {
        coins = <span class="hljs-built_in">append</span>(coins, c)
    }

    length := <span class="hljs-built_in">len</span>(coins)
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; length; i += batch {
        wg.Add(<span class="hljs-number">1</span>)
        <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-keyword">int</span>)</span></span> {
            b := coins[i:]
            <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(b) &gt; batch {
                b = b[:batch]
            }

            <span class="hljs-keyword">for</span> _, c := <span class="hljs-keyword">range</span> b {
                c.ID = <span class="hljs-string">""</span>
                <span class="hljs-keyword">if</span> c.Algorithm == <span class="hljs-string">"N/A"</span> {
                    c.Algorithm = <span class="hljs-string">""</span>
                }

                r.Table(<span class="hljs-string">"coin"</span>).
                    Insert(c).
                    Exec(d.S)
            }

            wg.Done()
        }(i)
    }

    wg.Wait()
}
</code></pre>
<h2 id="bonus-chapter">Bonus Chapter</h2>
<p>I also decided to make use of the slice insertion of Rethink. This is super fast!</p>
<p>Even faster than mine, I haven't tweaked mine to use anything other than one hundred in batch, but I suspect that lowering the batch-size will speed it up a bit.</p>
<p>The timing of this is:</p>
<pre><code class="lang-sh">go run . -fetch  1.02s user 0.26s system 28% cpu 4.488 total
</code></pre>
<h3 id="code">Code</h3>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">FetchCryptoV3</span><span class="hljs-params">(d *db.DB)</span></span> {
    dat, _ := ioutil.ReadFile(<span class="hljs-string">"coins.json"</span>)

    <span class="hljs-keyword">var</span> data Data
    json.Unmarshal(dat, &amp;data)

    coins := []coin.Coin{}
    <span class="hljs-keyword">for</span> _, c := <span class="hljs-keyword">range</span> data.Data {
        c.ID = <span class="hljs-string">""</span>
        <span class="hljs-keyword">if</span> c.Algorithm == <span class="hljs-string">"N/A"</span> {
            c.Algorithm = <span class="hljs-string">""</span>
        }

        coins = <span class="hljs-built_in">append</span>(coins, c)
    }

    r.Table(<span class="hljs-string">"coin"</span>).
        Insert(coins).
        Exec(d.S)
}
</code></pre>
<h2 id="final-thoughts">Final thoughts</h2>
<p>No error checking has been taken into account, but if you use any of these functions, you probably should, especially in production environments.</p>
<p>Again, you should play around with the batching sizes too, if you want to use anything long the lines of the second function.</p>
<h2 id="edit">Edit</h2>
<p>I just did a new test with a batching size of <code>10</code>, this more than halved the time it took to insert into the database, thus making it faster than the standard one now.</p>
<p>Making it a meer <code>2.9s</code>.</p>
<pre><code class="lang-sh">go run . -fetch  1.67s user 0.49s system 74% cpu 2.917 total
</code></pre>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Create A Tree Generator (in less than 100 lines of V)]]></title><description><![CDATA[In this post, I'll show you how to do what you've always wanted. Namely a magical tree generator - and of course, learn V in the making of this. This will…]]></description><link>https://blog.madco.me/create-a-tree-generator-in-less-than-100-lines-of-v</link><guid isPermaLink="true">https://blog.madco.me/create-a-tree-generator-in-less-than-100-lines-of-v</guid><category><![CDATA[generators]]></category><category><![CDATA[code]]></category><category><![CDATA[fun]]></category><category><![CDATA[Christmas Hackathon]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Wed, 30 Dec 2020 01:51:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1609291638155/5nWfnq-OS.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="a-magical-tree-generator">A Magical Tree Generator</h1>
<p>In this post, I'll show you how to do what you've always wanted. Namely a magical tree generator - and of course, learn V in the making of this.</p>
<p>This will all be done in exactly 90 lines of code.</p>
<h2 id="v">V</h2>
<p>First of all, what is V? This is easy, I'll just simply refer you to my other post: https://madco.me/code-in-v</p>
<h2 id="tree-generator">Tree Generator</h2>
<p>Let's get started!</p>
<p>As V is much like Go in it's code, we need a module and some imports</p>
<pre><code class="lang-v">module main

import gg
import gx
import math
import rand
import sokol.sapp
</code></pre>
<p>These are just a few things V provides for us to use, and that we'll need.</p>
<ul>
<li><code>gg</code> is our drawing tool, think of it as the plain ol' plaint buddy from MS.</li>
<li><code>gx</code> is the a plalette of colours for us to use.</li>
<li><code>math</code> is for <code>PI</code>.</li>
<li><code>rand</code> to gain some randomness. We do not want the same thing multiple times.</li>
<li><code>sokol.sapp</code>, to be honest, I have yet to figure this.</li>
</ul>
<pre><code class="lang-v">const (
    win_width  = 600
    win_height = 600
)
</code></pre>
<p>This will be the size of our canvas.</p>
<pre><code class="lang-v">struct App {
mut:
    gg    &amp;gg.Context
}
</code></pre>
<p>This <code>struct</code> will be in charge of drawing.</p>
<pre><code class="lang-v">struct Branch {
mut:
    x f32
    y f32
    cx f32
    cy f32
    rad f32
    len f32
}
</code></pre>
<p>This struct, however, just simply a branch of our tree.</p>
<pre><code class="lang-v">fn main() {
    mut app := &amp;App{
        gg: 0
    }

    app.gg = gg.new_context({
        bg_color: gx.rgba(255, 155, 155, 0)
        width: win_width
        height: win_height
        use_ortho: true
        create_window: true
        window_title: 'Tree Vv'
        keydown_fn: frame
        user_data: app
    })

    app.gg.run()
}
</code></pre>
<p>This is more fun, but to keep this simple, just know that this will create our paint brush.</p>
<pre><code class="lang-v">fn frame(c sapp.KeyCode, m sapp.Modifier, app &amp;App) {
    b1 := &amp;Branch{
        x: f32(win_width / 2)
        y: f32(win_height)
        cx: f32(win_width / 2)
        cy: f32(win_height)
        rad: f32(math.pi / 2)
        len: rand.f32n(100)
    }

    app.gg.begin()
    app.draw_branch(b1, 1)
    app.draw_branch(b1, -1)
    app.gg.end()
}
</code></pre>
<p>The <code>frame</code> is where the fun happens! It's in charge of generating a new tree for every key-press.</p>
<p>We start with a simple branch, on <code>X</code> &amp; <code>Y</code> positions, along with the old postions <code>CX</code> &amp; <code>CY</code>.</p>
<p>We also generate the start radians, and a random length of the branch.</p>
<pre><code class="lang-v">fn (app &amp;App) draw_branch(b &amp;Branch, mul f32) {
    cos := f32(math.cos(b.rad))
    sin := f32(math.sin(b.rad))

    x_tmp := b.cx - cos * b.len
    y_tmp := b.cy - sin * b.len

    app.gg.draw_line(b.cx, b.cy, x_tmp, y_tmp, gx.black)

    rad := rand.f32n(math.pi / 4)

    b1 := &amp;Branch{
        x: b.cx
        y: b.cy
        cx: x_tmp
        cy: y_tmp
        rad: b.rad + rad * mul
        len: b.len - rand.f32n(25)
    }

    if b1.len &gt; 10 {
        app.draw_branch(b1, 1)
        app.draw_branch(b1, -1)
    } else {
        app.gg.draw_circle(b1.cx, b1.cy, 4, gx.white)
    }
}
</code></pre>
<p>Here we simply calulate the branch's new <code>X</code> &amp; <code>Y</code> positions. Re-use our old to as the new <code>CX</code> &amp; <code>CY</code>.</p>
<p>We then draw a new line. Randomizes a number between <code>0</code> and <code>PI / 4</code>, and generaets a new rbanch from those values.</p>
<p>If the length of our branch is then above <code>10</code>, we does the exact same thing again, becasue insanity, right?</p>
<p>If the branch's length is below or equals to <code>10</code> we draw a leaf.</p>
<p>Easy, right? The complete code is below my plug.</p>
<h2 id="shameless-plug">Shameless Plug</h2>
<p>Before you turn to the complete code, please take a look at this beauty! <a target="_blank" href="https://placetree.art"><img src="https://placetree.art/tree?w=750&amp;h=800&amp;random=1" alt="placetree.art" /></a></p>
<blockquote>
<p>I'd recommend you to click on the image to gain access to a tree placeholder!</p>
</blockquote>
<h2 id="our-generator">Our Generator</h2>
<p>The generator we've just created will of not be as beautiful as the above out-put, but it's a start nonetheless.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1609292334156/mf6wd0JDG.png" alt="Screenshot from 2020-12-30 02-37-39.png" /></p>
<h2 id="complete-code">Complete Code</h2>
<pre><code class="lang-v">module main

import gg
import gx
import math
import rand
import sokol.sapp

const (
    win_width  = 600
    win_height = 600
)

struct App {
mut:
    gg    &amp;gg.Context
}

struct Branch {
mut:
    x f32
    y f32
    cx f32
    cy f32
    rad f32
    len f32
}

fn main() {
    mut app := &amp;App{
        gg: 0
    }

    app.gg = gg.new_context({
        bg_color: gx.rgba(255, 155, 155, 0)
        width: win_width
        height: win_height
        use_ortho: true
        create_window: true
        window_title: 'Tree Vv'
        keydown_fn: frame
        user_data: app
    })

    app.gg.run()
}

fn frame(c sapp.KeyCode, m sapp.Modifier, app &amp;App) {
    b1 := &amp;Branch{
        x: f32(win_width / 2)
        y: f32(win_height)
        cx: f32(win_width / 2)
        cy: f32(win_height)
        rad: f32(math.pi / 2)
        len: rand.f32n(100)
    }

    app.gg.begin()
    app.draw_branch(b1, 1)
    app.draw_branch(b1, -1)
    app.gg.end()
}

fn (app &amp;App) draw_branch(b &amp;Branch, mul f32) {
    cos := f32(math.cos(b.rad))
    sin := f32(math.sin(b.rad))

    x_tmp := b.cx - cos * b.len
    y_tmp := b.cy - sin * b.len

    app.gg.draw_line(b.cx, b.cy, x_tmp, y_tmp, gx.black)

    rad := rand.f32n(math.pi / 4)

    b1 := &amp;Branch{
        x: b.cx
        y: b.cy
        cx: x_tmp
        cy: y_tmp
        rad: b.rad + rad * mul
        len: b.len - rand.f32n(25)
    }

    if b1.len &gt; 10 {
        app.draw_branch(b1, 1)
        app.draw_branch(b1, -1)
    } else {
        app.gg.draw_circle(b1.cx, b1.cy, 4, gx.white)
    }
}
</code></pre>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[A Dead man's Switch in Go]]></title><description><![CDATA[repo I found this video, and found the concept a rather intriguing. Though, instead of the whole switching it on before the encryption starts, is…]]></description><link>https://blog.madco.me/a-dead-mans-switch-in-go</link><guid isPermaLink="true">https://blog.madco.me/a-dead-mans-switch-in-go</guid><category><![CDATA[golang]]></category><category><![CDATA[Go]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Wed, 25 Nov 2020 00:00:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1606262414621/W1JY9axgV.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="dead-men-tell-no-tales">Dead Men Tell No Tales</h1>
<p><a target="_blank" href="https://github.com/Mobilpadde/dead-mans-switch">repo</a></p>
<h2 id="why">Why</h2>
<p>I found this <a target="_blank" href="https://www.youtube.com/watch?v=b6LoNZXkwSA">video</a>, and found the concept a rather intriguing. Though, instead of the whole switching it on before the encryption starts, is definitely not how I would do it. </p>
<p>For me, a dead man's switch should be switched on by default, and only decrypt upon asked along with the proper password of course.</p>
<h3 id="the-idea">The Idea</h3>
<p>The whole plan is simple enough, let's make a small go-program to encrypt a file on start, then, when we receive the password it shall decrypt out file again. Such, as before you go out to do the all the <em>nastinesses</em>, you start the program.</p>
<p>Now, for <em>funzies</em> and making this a tad more secure and obscure we will be using an e-mail to unlock our file again.</p>
<h2 id="the-research">The Research</h2>
<h3 id="the-e-mail">The E-mail</h3>
<p>First of all, we need a way to receive e-mails, this is definitely the hardest part. </p>
<p>For this post, though, we will go with <a target="_blank" href="https://github.com/emersion/go-imap"><em>emersion</em>'s <code>go-imap</code></a>.</p>
<h3 id="the-encryption">The Encryption</h3>
<p>To be completely honest, I do not know much about encryption, hashes and decryption. So I will just <strong>go</strong> with what what seems like a great encryption algorithm, namely the <code>AES 256</code>.</p>
<blockquote>
<p>AES 256 is virtually impenetrable using brute-force methods. While a 56-bit DES key can be cracked in less than a day, AES would take billions of years to break using current computing technology. Hackers would be foolish to even attempt this type of attack. </p>
<ul>
<li>https://www.solarwindsmsp.com/blog/aes-256-encryption-algorithm</li>
</ul>
</blockquote>
<h2 id="the-code">The Code</h2>
<h3 id="32-characters">32 characters</h3>
<p>First we need to create a secure 32 character password for our AES:</p>
<p><code>echo 'madco.me' | sha256sum | base64 | head -c 32 ; echo</code></p>
<blockquote>
<p>Please, do not use <code>madco.me</code> as your password.</p>
</blockquote>
<h3 id="code">Code</h3>
<p>First, let's set some rights for our files that will be created. These are stolen from https://stackoverflow.com/a/42718395/754471.</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> (
    <span class="hljs-comment">// https://stackoverflow.com/a/42718395/754471</span>
    OS_READ       = <span class="hljs-number">04</span>
    OS_WRITE      = <span class="hljs-number">02</span>
    OS_USER_SHIFT = <span class="hljs-number">6</span>

    OS_USER_R = OS_READ &lt;&lt; OS_USER_SHIFT
    OS_USER_W = OS_WRITE &lt;&lt; OS_USER_SHIFT
)
</code></pre>
<p>I use this helper function a lot, to check for <code>errors</code>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">e</span><span class="hljs-params">(err error)</span></span> {
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatalln(err)
    }
}
</code></pre>
<p>Now we need an <code>encrypt</code>-func</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">encrypt</span><span class="hljs-params">(key <span class="hljs-keyword">string</span>, bytes []<span class="hljs-keyword">byte</span>)</span> []<span class="hljs-title">byte</span></span> {
    c, err := aes.NewCipher([]<span class="hljs-keyword">byte</span>(key))
    e(err)

    gcm, err := cipher.NewGCM(c)
    e(err)

    nonce := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, gcm.NonceSize())

    _, err = io.ReadFull(rand.Reader, nonce)
    e(err)

    <span class="hljs-keyword">return</span> gcm.Seal(nonce, nonce, bytes, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>And  of course a way to decrypt our file again</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">decrypt</span><span class="hljs-params">(key, bytes []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-params">([]<span class="hljs-keyword">byte</span>, error)</span></span> {
    c, err := aes.NewCipher([]<span class="hljs-keyword">byte</span>(key))
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> []<span class="hljs-keyword">byte</span>(<span class="hljs-string">""</span>), err
    }

    gcm, err := cipher.NewGCM(c)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> []<span class="hljs-keyword">byte</span>(<span class="hljs-string">""</span>), err
    }

    nonceSize := gcm.NonceSize()
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(bytes) &lt; nonceSize {
        <span class="hljs-keyword">return</span> []<span class="hljs-keyword">byte</span>(<span class="hljs-string">""</span>), err
    }

    nonce, cipherText := bytes[:nonceSize], bytes[nonceSize:]
    plain, err := gcm.Open(<span class="hljs-literal">nil</span>, nonce, cipherText, <span class="hljs-literal">nil</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> []<span class="hljs-keyword">byte</span>(<span class="hljs-string">""</span>), err
    }

    <span class="hljs-keyword">return</span> plain, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>Great, now that these are done, let's build the e-mail checker</p>
<p>We use these two modules to access the gmail imap:</p>
<ul>
<li>github.com/emersion/go-imap/client</li>
<li>github.com/emersion/go-imap</li>
</ul>
<p>In here we read five messages, and return a true if we receive the <code>Unlock</code> subject along with the proper passphrase, we generated this <a class="post-section-overview" href="#32-characters">here</a>. </p>
<p>We then split our body of the e-mail into smaller strings, and use the third one as our code. I had to fiddle a bit to figure this. So try out yourselves if you want to checkout what values the body provides.</p>
<p>If we receive the proper code, we decrypt and write the back a new and decrypted version of the encrypted file.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">checker</span><span class="hljs-params">(user, pass, file <span class="hljs-keyword">string</span>, bytes []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-title">bool</span></span> {
    c, err := client.DialTLS(<span class="hljs-string">"imap.gmail.com:993"</span>, <span class="hljs-literal">nil</span>)
    e(err)

    <span class="hljs-keyword">defer</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        err := c.Logout()
        e(err)
    }()

    err = c.Login(user, pass)
    e(err)

    mbox, err := c.Select(<span class="hljs-string">"INBOX"</span>, <span class="hljs-literal">true</span>)
    e(err)

    seqset := <span class="hljs-built_in">new</span>(imap.SeqSet)
    seqset.AddRange(mbox.Messages<span class="hljs-number">-5</span>, mbox.Messages)

    section := &amp;imap.BodySectionName{}
    items := []imap.FetchItem{section.FetchItem()}

    msgs := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> *imap.Message, <span class="hljs-number">5</span>)
    done := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> error, <span class="hljs-number">1</span>)

    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        done &lt;- c.Fetch(seqset, items, msgs)
    }()

    <span class="hljs-keyword">for</span> msg := <span class="hljs-keyword">range</span> msgs {
        m, err := mail.ReadMessage(msg.GetBody(section))
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            log.Println(err)
            <span class="hljs-keyword">break</span>
        }

        subject := m.Header.Get(<span class="hljs-string">"Subject"</span>)
        <span class="hljs-keyword">if</span> subject == <span class="hljs-string">"Unlock"</span> {
            body, err := ioutil.ReadAll(m.Body)
            <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
                log.Println(err)
                <span class="hljs-keyword">break</span>
            }

            bodies := strings.Split(<span class="hljs-keyword">string</span>(body), <span class="hljs-string">"\r\n"</span>)

            dat, err := decrypt([]<span class="hljs-keyword">byte</span>(bodies[<span class="hljs-number">3</span>]), bytes)
            e(err)

            orig := strings.Split(file, <span class="hljs-string">".enc"</span>)[<span class="hljs-number">0</span>]
            <span class="hljs-keyword">return</span> ioutil.WriteFile(orig, dat, OS_USER_R|OS_USER_W) == <span class="hljs-literal">nil</span>
        }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
}
</code></pre>
<p>Finally we have the main func, in here we set two flags:</p>
<ul>
<li><code>e</code>: To choose if the file has already been encrypted - which is great for testing, as the original file <strong>will</strong> be deleted upon running this program.</li>
<li><code>f</code>: The file to encrypt and remove.</li>
</ul>
<p>Next-up we read in the lines from a pipe, I'll explain how to do this in after the code. Basically we read all the piped in lines and use those - There should always be - at least - three(<strong>!</strong>).</p>
<p>Finally we check the mail server every 2 seconds, just to set a limit.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    encryptFile := flag.Bool(<span class="hljs-string">"e"</span>, <span class="hljs-literal">false</span>, <span class="hljs-string">"To encrypt before running?"</span>)
    file := flag.String(<span class="hljs-string">"f"</span>, <span class="hljs-string">"./data.txt"</span>, <span class="hljs-string">"File to encrypt"</span>)

    flag.Parse()

    reader := bufio.NewReader(os.Stdin)

    <span class="hljs-keyword">var</span> inputs []<span class="hljs-keyword">string</span>
    <span class="hljs-keyword">for</span> {
        input, _, err := reader.ReadLine()
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            <span class="hljs-keyword">break</span>
        }

        inputs = <span class="hljs-built_in">append</span>(inputs, <span class="hljs-keyword">string</span>(input))
    }

    base := filepath.Base(*file)
    dir := filepath.Dir(*file)

    <span class="hljs-keyword">var</span> err error
    <span class="hljs-keyword">var</span> encrypted []<span class="hljs-keyword">byte</span>

    <span class="hljs-keyword">if</span> *encryptFile {
        <span class="hljs-comment">// If not encrypted, let's encrypt out file first</span>
        fileBytes, err := ioutil.ReadFile(*file)
        e(err)

        key := inputs[<span class="hljs-number">0</span>]
        encrypted = encrypt(key, fileBytes)

        err = ioutil.WriteFile(dir+<span class="hljs-string">"/"</span>+base+<span class="hljs-string">".enc"</span>, encrypted, OS_USER_R|OS_USER_W)
        e(err)

        os.Remove(*file)
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// Read the contents of the already encrypted file</span>
        encrypted, err = ioutil.ReadFile(*file + <span class="hljs-string">".enc"</span>)
        e(err)
    }

    mail, pass := inputs[<span class="hljs-number">1</span>], inputs[<span class="hljs-number">2</span>]
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">range</span> time.Tick(<span class="hljs-number">2</span> * time.Second) {
        <span class="hljs-keyword">if</span> succ := checker(mail, pass, *file+<span class="hljs-string">".enc"</span>, encrypted); succ {
            <span class="hljs-keyword">break</span>
        }
    }
}
</code></pre>
<h2 id="running">Running</h2>
<p>To run this program is quite easy.</p>
<p>We simply create a credentials file first - make sure this stays secret for absolutely everybody. This file should contain three lines:</p>
<ul>
<li>The 32 char secret</li>
<li>Your e-mail</li>
<li>An app password for your e-mail, as we always want to call back the password, if needed.</li>
</ul>
<blockquote>
<p>To make an app password you simply navigate to this page: https://myaccount.google.com/apppasswords and sign-in. Then you choose <code>mail</code> and choose <code>Other</code>, give it a name and you'll see a password. Save this, as you won't be able to see it again.</p>
</blockquote>
<h2 id="prod">Prod?</h2>
<p>You should not take this code as no way near production ready. But hack on it, and I believe in you! You'll make something out off this.</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Colly for Scraping in Go]]></title><description><![CDATA[You can choose to watch the price changes manually, this is hard work and labour. This is great in some cases, but well, who wants to navigate to a page…]]></description><link>https://blog.madco.me/colly-for-scraping-in-go</link><guid isPermaLink="true">https://blog.madco.me/colly-for-scraping-in-go</guid><category><![CDATA[Go]]></category><category><![CDATA[Amazon]]></category><category><![CDATA[web scraping]]></category><category><![CDATA[Scraping]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Wed, 11 Nov 2020 22:03:38 GMT</pubDate><content:encoded><![CDATA[<h1 id="price-watching-the-new-bird-watching">Price Watching - The New Bird Watching</h1>
<h2 id="manual-labour">Manual Labour</h2>
<p>You can choose to watch the price changes manually, this is hard work and labour. This is great in some cases, but well, who wants to navigate to a page, search for our desired products, open them in new tabs, take a look at the price to only figure it's still too expensive.</p>
<p>So I ask you this, why would you watch price changes yourself, when you can have a service doing it for you?</p>
<p>Granted, a lot of SaaS products are out there, to help you through this, alas why not make something yourselves, and learn from the experiences? </p>
<h2 id="saas">SaaS</h2>
<p>I know there's a lot of scraping services out there, a simple google search of <code>scraping services</code> and the whole page is filled with more than 44 million results.</p>
<h2 id="creating-the-service">Creating The Service</h2>
<h3 id="manual-labour-again">Manual Labour - Again</h3>
<p>First, we have a lot of manual work ahead of us, but well, this could turn us into developers, so why not?</p>
<p>Like a wrote in the begining of this post, we still need to navigate to all of our desired products, notice the url and that is it, really! Simply copy the urls and save them for later.</p>
<p>Now we need to go to one of these urls, find the title of the product.</p>
<p>I've chosen these two <code>urls</code> for testign purposes:</p>
<ul>
<li>https://www.amazon.com/s?k=roku+streaming+stick</li>
<li>https://www.amazon.com/s?k=xiaomi+mi+10</li>
</ul>
<p>These two we'll look for manual price changes of a <code>Roku Steaming Stick</code> and the <code>Xiaomi Mi 10</code>.</p>
<h3 id="mvp">MVP</h3>
<p>First, let's add the necessary code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"regexp"</span>

    <span class="hljs-string">"github.com/gocolly/colly"</span>
)

<span class="hljs-keyword">var</span> lines = regexp.MustCompile(<span class="hljs-string">"(\r|\n)"</span>)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    links := []<span class="hljs-keyword">string</span>{
        <span class="hljs-string">"https://www.amazon.com/s?k=roku+streaming+stick"</span>,
        <span class="hljs-string">"https://www.amazon.com/s?k=xiaomi+mi+10"</span>,
    }

    c := colly.NewCollector(
        colly.CacheDir(<span class="hljs-string">"./sites"</span>),
        colly.Async(<span class="hljs-literal">true</span>),
        colly.AllowURLRevisit(),
    )

    c.OnRequest(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(r *colly.Request)</span></span> {
        r.Headers.Set(<span class="hljs-string">"User-Agent"</span>, <span class="hljs-string">"PriceWatch/v1.0"</span>)
    })

    c.OnError(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(r *colly.Response, err error)</span></span> {
        log.Println(err)
    })

    c.OnScraped(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(r *colly.Response)</span></span> {
        log.Println(<span class="hljs-string">"Done"</span>, r.Request.URL)
    })

    c.OnHTML(<span class="hljs-string">"#search"</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(h *colly.HTMLElement)</span></span> {

    })

    <span class="hljs-keyword">for</span> _, link := <span class="hljs-keyword">range</span> links {
        c.Visit(link)
    }

    c.Wait()
}
</code></pre>
<p>The imports will come by themselves, if you use any integrated go IDE.</p>
<p>Next few lines in the <code>func main() {</code> are the links we will be watching. After the links are a new Colly constructor, we add a <code>CacheDir</code>, to cache the sites, so we don't get IP banned by Amazon.</p>
<blockquote>
<p><em>Note:</em> I'm not sure if they ban us, but just to be sure.</p>
</blockquote>
<p>Next-up we set the <code>User-Agent</code> to <code>PriceWatch/v1.0</code>. Which is somewhat of the standard of how to set user agents for scrapers or bots.</p>
<h3 id="the-scraping">The Scraping</h3>
<p>Let's add some scraping functionallity to our scraper.</p>
<pre><code class="lang-go">c.OnHTML(<span class="hljs-string">"#search"</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(h *colly.HTMLElement)</span></span> {
    h.ForEach(<span class="hljs-string">"div.s-main-slot.s-result-list.s-search-results.sg-row &gt; div &gt; div"</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(_ <span class="hljs-keyword">int</span>, e *colly.HTMLElement)</span></span> {
        title := e.ChildText(<span class="hljs-string">"h2.a-size-mini.a-spacing-none.a-color-base.s-line-clamp-2"</span>)
        price := e.ChildText(<span class="hljs-string">"span.a-price"</span>)

        title = lines.ReplaceAllString(title, <span class="hljs-string">""</span>)
        price = lines.ReplaceAllString(price, <span class="hljs-string">""</span>)

        title = strings.TrimSpace(title)
        price = strings.TrimSpace(price)

        priceStrs := strings.Split(price, <span class="hljs-string">"$"</span>)
        prices := []<span class="hljs-keyword">float64</span>{}

        <span class="hljs-keyword">for</span> _, priceStr := <span class="hljs-keyword">range</span> priceStrs {
            p, err := strconv.ParseFloat(priceStr, <span class="hljs-number">64</span>)
            <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {
                prices = <span class="hljs-built_in">append</span>(prices, p)
            }
        }

        log.Println(title, prices)
    })
})
</code></pre>
<p>As you see, I've added four custom <code>JS-paths</code> to the scraper, namely:</p>
<ul>
<li><code>#search</code></li>
<li><code>div.s-main-slot.s-result-list.s-search-results.sg-row &gt; div &gt; div</code></li>
<li><code>h2.a-size-mini.a-spacing-none.a-color-base.s-line-clamp-2</code></li>
<li><code>span.a-price</code></li>
</ul>
<p>To find these paths, has been quite hit or miss. Trial and error. But in the end, I succeeded to find them. You can too, I believe in you!</p>
<p>Now, if we run our program:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605131843107/4dAhpLYuM.png" alt="1_results.png" /></p>
<p>Which is exactly what we want!</p>
<h2 id="watching">Watching</h2>
<p>I did kinda lure you into this post by saying we'd watch the prices, but now it's simply to save our products in a datastore of sorts, be it a database or JSON/CSV file. It's up to you.</p>
<p>I'll leave this next part as an exercise for you to complete.</p>
<p>Please, by any means! Do post the results of how you do it in a gist or simply an simple explanation as a comment, if you want to, that is.</p>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item><item><title><![CDATA[Code in V]]></title><description><![CDATA[You might have heard of the new kid in town. V. The forbidden love-child of Go and Rust in my mind, that is. Really it's not some new obscure language…]]></description><link>https://blog.madco.me/code-in-v</link><guid isPermaLink="true">https://blog.madco.me/code-in-v</guid><category><![CDATA[programming languages]]></category><category><![CDATA[markdown]]></category><dc:creator><![CDATA[Mads B. Cordes]]></dc:creator><pubDate>Fri, 30 Oct 2020 23:04:32 GMT</pubDate><content:encoded><![CDATA[<h1 id="what-the-v">What the V?</h1>
<p>You might have heard of the new kid in town. V. The forbidden love-child of Go and Rust in my mind, that is.</p>
<p>Really it's not some new obscure language, that won't stay around. It has a couple of years in the bag. Working hard to come build version 1. As of this writing the latest version is <code>0.1.29</code>, which was released on August 6. 2020.</p>
<blockquote>
<p>Fun fact #0:</p>
<p>It was initially written in Go, but now able to compile itself, thus making it possible to be written in 100% V - and Go is now obsolete of any V compiler.</p>
</blockquote>
<h2 id="what-makes-v-special">What makes V special?</h2>
<p>As I mentioned earlier, V is Go and Rust. Also in speed. Actually it's as fast as C. Compiled and safe to write. Along with the ability to write unsafe code - like the parts in Rust. Yet simple to write as Go.</p>
<p>Another feature it uses, that is quite popular in the Rust ecosystem, is the fast that it can catch run-time errors at compile time. </p>
<p>V can compile V in under a second. As for disk required, you do not even need large TB disk, not even half a TB. Actually, you can install the complete language on an small SD-card as the actual size is less than 0.025% of the space required to install GCC, a C++ compiler.</p>
<p>It's as easy as <code>v fmt . -w</code> to format a project in V. Pretty much as in Go. Making it super simple to agree in a company of a coding style for V.</p>
<p>WASM is also at the core of V, it compiles - as lots of other languages - to WASM, for the web.</p>
<blockquote>
<p>Fun fact #1:</p>
<p>The creator, Alexander Medvednikov, dubbed the language V, to not conflict with any other language extensions he were using.</p>
</blockquote>
<h2 id="is-v-fast">Is V fast?</h2>
<p>Is this a joke. No, the simplicity of Go and speed of C. Super simple to understand. V even have a site to check if V is (<em>still</em>) fast: fast.vlang.io.</p>
<p>It has C interop without any costs along with a minimal amount of allocations. Thus not just fast, but also makes a small impact on the machine that has to run the V program(s).</p>
<p>One of V's proudest libraries, if you ask me, is the <code>pico.v</code> one of the fastest web-frameworks out there! (techempower.com/benchmarks)</p>
<blockquote>
<p>Fun fact #2:</p>
<p>V has a <code>[live]</code> macro for functions in the language. Meaning they are live-reloaded!</p>
</blockquote>
<h1 id="a-taste">A taste</h1>
<p>I've decided the best way to give a proper taste in V, is to implement a big, sophisticated AI. Namely, one that can guess if coding is fun or not.</p>
<p>We start the code simply by naming our main-function, no package names or any bloat like that.</p>
<pre><code class="lang-v">fn main() {
</code></pre>
<p>Next, we add some choices.</p>
<pre><code class="lang-v">  choices := 'Choose `Yes` or No'
</code></pre>
<p>Notice, I'm not making it easy for the AI.</p>
<p>Now to fire-up the AI.</p>
<pre><code class="lang-v">  answer := choices.find_between('`',. '`')
</code></pre>
<p>And finally, let's see the result.</p>
<pre><code class="lang-v">  println('Is coding fun? $answer!')
}
</code></pre>
<p>And the complete code is as follows.</p>
<pre><code class="lang-v">fn main() {
  choices := 'Choose `Yes` or No' 
  answer := choices.find_between('`', '`')

  println('Is coding fun? $answer!')
}
</code></pre>
<p>Phew! That was quite an exercise. Now, though, you know how to program in V.</p>
<blockquote>
<p>Note: This has just been a small introduction to V. It should in no where near be used as production code.</p>
</blockquote>
<hr />
<p>{ Best, <a target="_blank" href="https://buymeacoff.ee/mc">Mads Bram Cordes</a> }</p>
]]></content:encoded></item></channel></rss>