<?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[〈 RA 〉]]></title><description><![CDATA[Transmuting Coffee into <code>]]></description><link>https://blog.ra101.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 21 Apr 2026 22:18:15 GMT</lastBuildDate><atom:link href="https://blog.ra101.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Beyond SCP: Mastering VM File Transfers with Rsync and HTTPS Accelerators]]></title><description><![CDATA[Transferring files between your local machine and a virtual machine (VM) is one of the most common tasks in tech. We often use scp because it comes natively installed and has similar utilization to ssh, but it is the clunkiest tool for the job.
In th...]]></description><link>https://blog.ra101.dev/mastering-vm-file-transfers</link><guid isPermaLink="true">https://blog.ra101.dev/mastering-vm-file-transfers</guid><category><![CDATA[vm]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Linux]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Wed, 14 Jan 2026 07:52:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1768401578819/ea856de0-60bf-46b4-959c-6145814dcb06.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Transferring files between your local machine and a virtual machine (VM) is one of the most common tasks in tech. We often use <code>scp</code> because it comes natively installed and has similar utilization to <code>ssh</code>, but it is the clunkiest tool for the job.</p>
<p>In this article, we’ll walk through the major CLI tools available, explain how they work under the hood, and highlight when you should use each.</p>
<p>We’ll cover:</p>
<ol>
<li><p><strong>SSH (Secure Shell) Tools</strong></p>
<p> 1.1 SCP (Secure Copy)</p>
<p> 1.2 SFTP (SSH File Transfer Protocol)</p>
<p> 1.3 SSHFS (SSH Filesystem Mount)</p>
</li>
<li><p><strong>Rsync</strong></p>
</li>
<li><p><strong>HTTP(S) + Download Accelerators</strong></p>
<p> 3.1 HTTP Single-thread server (Python)</p>
<p> 3.2 HTTP Multi-thread server (BusyBox httpd)</p>
<p> 3.2.1 <em>Download Accelerators (aria2c, axel)</em></p>
<p> 3.3 HTTPS File Server with Basic Auth (Caddy)</p>
</li>
</ol>
<hr />
<h2 id="heading-1-ssh-secure-shell-tools">1. SSH (Secure Shell) Tools</h2>
<p>These tools leverage the established Secure Shell (SSH) protocol for secure, encrypted transfers and operations.</p>
<h3 id="heading-11-scp-secure-copy">1.1 SCP (Secure Copy)</h3>
<p>SCP is the classic method for transferring files over SSH. It opens a secure channel, encrypts data, and performs a raw byte stream transfer.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>SSH</td><td>Yes</td><td>No</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Upload a file</span>
scp local_file user@remote:/path/to/destination

<span class="hljs-comment"># Download a file</span>
scp user@remote:/path/to/file local_dir/

<span class="hljs-comment"># Copy between two remote SSH hosts</span>
scp user1@remote1:/file user2@remote2:/destination
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Installed by default on nearly all systems.</p>
</li>
<li><p>Simple syntax for quick transfers.</p>
</li>
<li><p>Can copy files directly between two remote SSH servers.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li>No resumability; interrupted transfers start from scratch.</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li><code>scp</code> is best for one-off, quick, and secure transfers where you don’t expect interruptions.</li>
</ul>
<hr />
<h3 id="heading-12-sftp-ssh-file-transfer-protocol">1.2 SFTP (SSH File Transfer Protocol)</h3>
<p>SFTP is more feature-rich than SCP. It supports interactive sessions, directory traversal, file operations, and <strong>resumable transfers</strong> (when the client supports the feature).</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>SSH (subsystem)</td><td>Yes</td><td>Yes</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Interactive session</span>
sftp user@remote
sftp&gt; get -a remote_file local_file  <span class="hljs-comment"># -a for resume/continue or use reget instead.</span>
sftp&gt; put local_file remote_file

<span class="hljs-comment"># One-liner download</span>
sftp user@remote:/path/to/file local_file
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Resumable transfers with most clients (using -a or reget).</p>
</li>
<li><p>Interactive mode for browsing and transferring.</p>
</li>
<li><p>Compatible with GUI clients like FileZilla and WinSCP.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>Slightly slower than SCP due to protocol overhead.</p>
</li>
<li><p>Cannot transfer between two remote servers.</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li>Since <code>sftp</code> is a maintained SSH session, it is useful when there are a lot of small file transfers, and the folder structure is unknown.</li>
</ul>
<hr />
<h3 id="heading-13-sshfs-ssh-filesystem-mount">1.3 SSHFS (SSH Filesystem Mount)</h3>
<p>SSHFS mounts a remote filesystem locally using SSH and FUSE (Filesystem in Userspace). This allows you to use your existing tools and editors as if the files were on your machine.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>SSH (with FUSE)</td><td>Yes</td><td>N/A</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Mount remote filesystem</span>
sshfs user@remote:/remote/path /<span class="hljs-built_in">local</span>/mountpoint

<span class="hljs-comment"># Unmount</span>
fusermount -u /<span class="hljs-built_in">local</span>/mountpoint
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Transparent: Edit remote files with your local IDE/editor seamlessly.</p>
</li>
<li><p>Secure by default via SSH.</p>
</li>
<li><p>Great for exploratory work or ad-hoc editing.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>High latency on every file operation (slow for reading many small files).</p>
</li>
<li><p>Poor throughput for large files or bulk transfers.</p>
</li>
<li><p>Requires sshfs and FUSE support.</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li><code>sshfs</code> is ideal for development workflows where convenience and direct file access matter more than transfer speed.</li>
</ul>
<hr />
<h2 id="heading-2-rsync">2. Rsync</h2>
<p>Rsync is optimized for synchronization and efficiency. Instead of re-copying everything, it calculates file checksums and only sends the differences (deltas). This delta-transfer algorithm, along with built-in compression and partial transfers, makes it a synchronization powerhouse.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>SSH (default) or native TCP daemon</td><td>Yes (if over SSH)</td><td>Yes</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Sync local directory to remote (Archive, Verbose, Compress and Partial Transfer)</span>
rsync -avzP local_dir/ user@remote:/path/to/dir
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Extremely efficient for repeated transfers (only sends deltas).</p>
</li>
<li><p>Built-in compression (-z) and resumability.</p>
</li>
<li><p>Preserves permissions, symlinks, and timestamps.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>Requires rsync on both machines.</p>
</li>
<li><p>More CPU-intensive due to checksum calculations.</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li><code>rsync</code> is the go-to tool when you’re syncing directories with frequent updates or working with limited bandwidth where sending only changes matters most.</li>
</ul>
<p><strong>Performance Note:</strong> For initial full transfers, rsync overhead (checksum calculations) makes it slightly slower than raw HTTP transfers. However, for incremental syncs with only changed files, rsync is dramatically faster since it only transfers deltas.</p>
<hr />
<h2 id="heading-3-https-download-accelerators">3. HTTP(S) + Download Accelerators</h2>
<p>These methods prioritize raw speed by leveraging the lightweight nature of HTTP and the ability of clients to open parallel connections and partial downloads.</p>
<h3 id="heading-31-http-single-thread-server-python">3.1 HTTP Single-thread server (Python)</h3>
<p>Python's built-in HTTP server is the quickest way to share files. It serves the current directory over HTTP with zero configuration.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>HTTP</td><td>No</td><td>No</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Server</span>
python3 -m http.server 8000

<span class="hljs-comment"># Client</span>
wget http://&lt;server-public-ip&gt;:8000/filename.ext
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Works out of the box.</p>
</li>
<li><p>Faster than any of the SSH Tools, No SSH encryption/protocol overhead.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>Single-threaded -&gt; only one client at a time.</p>
</li>
<li><p>No authentication.</p>
</li>
<li><p>An SSH connection or a background job is required.</p>
</li>
<li><p>One-way setup (server -&gt; client).</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li>Transferring non-sensitive medium-sized files on a trusted local network for quick testing.</li>
</ul>
<hr />
<h3 id="heading-32-http-multi-thread-server-busybox-httpd">3.2 HTTP Multi-thread server (BusyBox httpd)</h3>
<p>BusyBox's httpd is a lightweight, multi-threaded HTTP server that handles multiple concurrent connections, making it ideal for serving files to several clients simultaneously.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>HTTP</td><td>No</td><td>Yes (client-dependent)</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Server</span>
busybox httpd -f -p 8000

<span class="hljs-comment"># Client</span>
wget http://&lt;server-public-ip&gt;:8000/filename.ext

<span class="hljs-comment"># download-accelerators http://&lt;server-public-ip&gt;:8000/filename.ext</span>
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Works out of the box.</p>
</li>
<li><p>No SSH encryption overhead.</p>
</li>
<li><p>Handles concurrent connections and multiple clients.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>No authentication.</p>
</li>
<li><p>An SSH connection or a background job is required.</p>
</li>
<li><p>One-way setup (server -&gt; client).</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li>Transferring non-sensitive large-sized files on a trusted local network for quick testing.</li>
</ul>
<hr />
<h4 id="heading-321-download-accelerators-aria2c-axel">3.2.1 Download Accelerators (aria2c, axel)</h4>
<p>Download accelerators are client-side tools that work with any HTTP/HTTPS server. They split downloads into multiple parallel streams, saturating your available bandwidth for maximum speed. These tools can be used with busybox httpd (3.3), or Caddy (3.4).</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>HTTP/HTTPS</td><td>Optional (HTTPS)</td><td>Yes</td></tr>
</tbody>
</table>
</div><ul>
<li><p><strong>aria2c:</strong> multi-source, segmented downloads, resumable (<code>-c</code>).</p>
</li>
<li><p><strong>axel:</strong> lightweight, parallel streams, resumable, simpler than aria2c.</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-comment"># busybox httpd (HTTP) (3.2)</span>
aria2c -c -x 8 -j 8 http://&lt;server-public-ip&gt;:8000/filename.ext

axel -n 8 http://&lt;server-public-ip&gt;:8000/filename.ext

<span class="hljs-comment"># Caddy (HTTPS) (3.3)</span>
aria2c -c -x 8 -j 8 --http-user=&lt;username&gt; --http-passwd=&lt;password&gt; --check-certificate=<span class="hljs-literal">false</span> https://&lt;server-public-ip&gt;/filename.ext

axel -n 8 -k -H <span class="hljs-string">"Authorization: Basic <span class="hljs-subst">$(printf '&lt;username&gt;:&lt;password&gt;' | base64)</span>"</span> https://&lt;server-public-ip&gt;/filename.ext
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Parallel streams saturate bandwidth.</p>
</li>
<li><p>Built-in resume support.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>Requires installation on client.</p>
</li>
<li><p>Background server process needed.</p>
</li>
</ul>
<hr />
<h3 id="heading-34-https-file-server-with-basic-auth-caddy">3.4 HTTPS File Server with Basic Auth (Caddy)</h3>
<p>A multi-threaded HTTP server is fast, but it is not secure. The final solution to file transferring is to go into overdrive mode and use a production server. Here, we are using Caddy for simplicity; we could have used NGINX and CertBot to accomplish the same.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Protocol</td><td>Encrypted</td><td>Resumable</td></tr>
</thead>
<tbody>
<tr>
<td>HTTPS</td><td>Yes</td><td>Yes</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash"><span class="hljs-comment"># Server</span>
caddy hash-password --plaintext &lt;password&gt;
<span class="hljs-comment"># $2a$14$moXJYUFKt1w6d...</span>
cat Caddyfile
</code></pre>
<pre><code class="lang-plaintext">https://localhost, https://127.0.0.1,  https://&lt;server-public-ip&gt; {
     tls internal

     root * /path/to/local_dir
     file_server browse

     basicauth {
         &lt;username&gt;  $2a$14$moXJYUFKt1w6d...
     }
}
</code></pre>
<pre><code class="lang-bash">sudo caddy run --config /path/to/Caddyfile
</code></pre>
<p><strong>Security Note:</strong> The example below uses <code>--check-certificate=false</code> because <code>tls internal</code> in Caddy creates a self-signed certificate. In production, use proper certificates with Let's Encrypt (for public IPs with domain names) or an internal Certificate Authority.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Client</span>

<span class="hljs-comment"># aria2c</span>
aria2c -c -x 8 --http-user=&lt;username&gt; --http-passwd=&lt;password&gt; --check-certificate=<span class="hljs-literal">false</span> https://&lt;server-public-ip&gt;/filename.ext

<span class="hljs-comment"># axel</span>
axel -n 8 -k -H <span class="hljs-string">"Authorization: Basic <span class="hljs-subst">$(printf '&lt;username&gt;:&lt;password&gt;' | base64)</span>"</span> https://&lt;server-public-ip&gt;/filename.ext
</code></pre>
<p>✅ Advantages:</p>
<ul>
<li><p>Authentication and encryption built-in.</p>
</li>
<li><p>Supports parallel downloads.</p>
</li>
</ul>
<p>❌ Drawbacks:</p>
<ul>
<li><p>More complex setup.</p>
</li>
<li><p>One-way setup (server -&gt; client).</p>
</li>
</ul>
<p>💙 Best Use Case:</p>
<ul>
<li>Sharing link for large files over the internet (with auth).</li>
</ul>
<hr />
<h2 id="heading-security-considerations">Security Considerations</h2>
<p>Understanding the security implications of each tool is critical when choosing a file transfer method:</p>
<p><strong>SSH-Based Tools (SCP, SFTP, SSHFS, Rsync over SSH)</strong></p>
<ul>
<li><p>Encrypted by default using SSH protocol</p>
</li>
<li><p>Uses public key authentication (SSH keys) or password authentication</p>
</li>
<li><p>Suitable for transferring sensitive data over untrusted networks</p>
</li>
<li><p>Requires SSH access and proper key management</p>
</li>
</ul>
<p><strong>HTTP Servers (Python, busybox)</strong></p>
<ul>
<li><p>No encryption - data transferred in plain text</p>
</li>
<li><p>No authentication - anyone with network access can download files</p>
</li>
<li><p>Use only on trusted local networks (VPNs, private subnets)</p>
</li>
<li><p>Never use for sensitive data without additional security measures</p>
</li>
</ul>
<p><strong>HTTPS (Caddy)</strong></p>
<ul>
<li><p>Encrypted via TLS</p>
</li>
<li><p>Basic Authentication sends credentials with every request</p>
</li>
<li><p>Self-signed certificates (using <code>tls internal</code>) trigger security warnings and require <code>--check-certificate=false</code></p>
</li>
<li><p>For production use, obtain proper certificates via Let's Encrypt or internal CA</p>
</li>
<li><p>Suitable for transferring files over public networks when configured correctly</p>
</li>
</ul>
<p><strong>Best Practice:</strong></p>
<ul>
<li><p>Use SSH-based tools for sensitive data over untrusted networks.</p>
</li>
<li><p>HTTP servers are perfectly acceptable on trusted networks (VPNs, private subnets) where the network layer already provides security.</p>
</li>
<li><p>Use HTTPS only when transferring files over public internet without VPN protection.</p>
</li>
</ul>
<hr />
<h2 id="heading-performance-comparison-slowest-to-fastest">Performance Comparison: Slowest to Fastest</h2>
<ol>
<li><p><strong>SSHFS</strong>: High latency per operation, every read/write is a round-trip over SSH.</p>
</li>
<li><p><strong>SCP/SFTP</strong>: SSH encryption overhead, single-threaded.</p>
</li>
<li><p><strong>Rsync over ssh</strong>: Efficient delta transfers and compression.</p>
</li>
<li><p><strong>HTTP Single-Threaded</strong>: Direct HTTP with no encryption overhead.</p>
</li>
<li><p><strong>HTTPS Multi-Threaded + Download Accelerators</strong>: Parallel streams that saturate available bandwidth. HTTPS adds ~10-20% overhead.</p>
</li>
</ol>
<hr />
<h2 id="heading-my-daily-workflow">My Daily Workflow</h2>
<p>Here is what I use on a day-to-day basis:</p>
<ul>
<li><p><code>scp</code>: When transferring small files between VMs (and when I forgot rsync flags.)</p>
</li>
<li><p><code>sftp</code>: When I have many small files to operate on, and I also don't know the directory structure, the command has fewer flags and is easier on fingers.</p>
</li>
<li><p><code>sshfs</code>: Never used.</p>
</li>
<li><p><code>rsync over ssh</code>: I have majorly replaced <code>scp</code> with <code>rsync -aivP</code> (I don't use compression <strong>on the fly</strong>). It is especially handy with large files.</p>
</li>
<li><p><code>python3 -m http.server 8000</code>: Not anymore for my setup, but I am debugging someone else's setup, then they probably don't have download accelerators.</p>
</li>
<li><p><code>busybox httpd -f -p 8000</code>: Since most file transfer work happens over VPN with private endpoints. So for large files, this is my go-to choice.</p>
</li>
<li><p><code>HTTPS File Server (Caddy)</code>: Sending public links (outside VPN but still with user and password) for file download.</p>
</li>
</ul>
<p>Each tool addresses the same problem differently. By understanding their trade-offs, you can pick the right tool for your specific requirements instead of defaulting to SCP.</p>
]]></content:encoded></item><item><title><![CDATA[Alias Alchemy - Instant Bash Setup!]]></title><description><![CDATA[Alias Alchemy is a Deno-powered server that fetches aliases from a GitHub repository based on your query. Think of it as your instant alias spellbook, perfect for setting up new environments in seconds.
⚡ Usage:
$ alias-alchemy.ra101.dev/?q=py,shell,...]]></description><link>https://blog.ra101.dev/alias-alchemy</link><guid isPermaLink="true">https://blog.ra101.dev/alias-alchemy</guid><category><![CDATA[Linux]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Python]]></category><category><![CDATA[shell script]]></category><category><![CDATA[shell]]></category><category><![CDATA[Bash]]></category><category><![CDATA[zsh]]></category><category><![CDATA[oh-my-zsh]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[alias]]></category><category><![CDATA[aliases]]></category><category><![CDATA[shell scripting]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Wed, 13 Aug 2025 18:33:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755109892196/fb41d6b8-2a8e-41ae-af1e-0c466a1824f2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Alias Alchemy</strong> is a Deno-powered server that fetches aliases from a GitHub repository based on your query. Think of it as your instant alias spellbook, perfect for setting up new environments in seconds.</p>
<h2 id="heading-usage">⚡ Usage:</h2>
<pre><code class="lang-bash">$ alias-alchemy.ra101.dev/?q=py,shell,k8s &gt; .aliases.sh
$ cat .aliases.sh

<span class="hljs-comment"># Python Aliases (py, py(uv), alembic, django, celery)</span>
...

<span class="hljs-comment"># Shell Aliases (debian, git)</span>
...

<span class="hljs-comment"># Kubernetes Aliases (kubectl, kubecolor, kustomize)</span>
...
</code></pre>
<hr />
<h2 id="heading-why-i-built-it">🤔 Why I built it ?</h2>
<ol>
<li><p>I constantly create new VMs at my job, and the very first command I run usually fails because it was an alias typed by pure muscle memory. Once you start using aliases, it is hard to write full commands, especially those <a target="_blank" href="https://github.com/ra101/kubectl-aliases/blob/core/.kubectl_aliases.zsh">Kubernetes</a> aliases.</p>
</li>
<li><p>Whenever I start a new language, I start building aliases. For example, while learning Java (+ Maven), I made: <code>alias jexec = "mvn exec:java -Dexec.args=$@"</code>. Since there’s no standard alias collection for most tools, I created Alias Alchemy to be that open-source standard — a handy tool for whenever someone starts something new.</p>
</li>
<li><p>I wanted to learn Deno, and this is my "hello-world" project.</p>
</li>
</ol>
<hr />
<h2 id="heading-help-guide">📖 Help Guide:</h2>
<p><strong>Enough Stories ! Let’s look at the help guide !</strong></p>
<p>The current version supports the following</p>
<pre><code class="lang-bash">$ curl -L alal.deno.dev/<span class="hljs-built_in">help</span>

Alias Alchemy - The best way to download aliases <span class="hljs-keyword">for</span> fast setup.

USAGE:
    curl -L <span class="hljs-string">"alias-alchemy.ra101.dev/?q=&lt;category-1&gt;,&lt;category-2&gt;,..."</span>

AVAILABLE CATEGORIES:
    , (null)                   All aliases
    shell, sh                  Shell aliases (Debian, Git, utilities)
    python, py                 Python aliases (py, py(uv), alembic, django, celery)
    docker, dk                 Docker aliases (docker, compose, swarm)
    podman, pd                 Podman aliases (podman, compose)
    kubernetes, k              Kubernetes aliases (kubectl, kubecolor, kustomize)

SHORT DOMAIN:
    alal.deno.dev

SUPPORTED TOOLS:
    curl, wget, httpie, aria2, postman, or any tool with User-Agent: <span class="hljs-string">'alal'</span>

For more information, visit: https://alias-alchemy.ra101.dev
</code></pre>
<hr />
<p><strong>Links:</strong></p>
<ul>
<li><p>Website: <a target="_blank" href="https://alias-alchemy.ra101.dev">https://alias-alchemy.ra101.dev</a></p>
</li>
<li><p>Github Repo: <a target="_blank" href="https://github.com/ra101/alias-alchemy">https://github.com/ra101/alias-alchemy</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[AI Hallucinations: A Future Full of Misconceptions and Mediocre Code]]></title><description><![CDATA[Reader discretion is advised!A good Sus-Saturday to all. In this article, I drag and drown you with my paranoia about AI. Let the mass psychosis begin!
What are AI hallucinations?AI hallucinations are incorrect or misleading results that AI models ge...]]></description><link>https://blog.ra101.dev/ai-hallucinations</link><guid isPermaLink="true">https://blog.ra101.dev/ai-hallucinations</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[AI]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Sat, 04 May 2024 19:19:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714851944353/52a4b8c5-a050-4feb-b41c-91e76c2b44fd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Reader discretion is advised!</strong><br />A good Sus-Saturday to all. In this article, I drag and drown you with my paranoia about AI. Let the mass psychosis begin!</p>
<p><strong>What are AI hallucinations?</strong><br />AI hallucinations are incorrect or misleading results that AI models generate.</p>
<p><strong>Story Time</strong><br />I was looking for "colour quantization algorithms" for a project (I put these words together in my brain and it was an actual thing!). As the name suggests, I wanted to reduce the number of distinct colours in an image. Anyway, I googled it and all the answers were about the K-means clustering algorithm.</p>
<p>Now, this algorithm is quite slow for my use case, So I went to chatGPT for the same, I spit out 5 different algorithms and out of them I selected the "Median Cut" algorithm and asked to write a code in Python, It returned a code using Pillow Library, I asked to re-write the code in using OpenCV and numpy, and it returned another piece of code.</p>
<p>These 2 codes had slightly different implementations. None of them ran in the first go, but after some refactoring, they both yielded results! <strong>Different Results!</strong></p>
<p>Okay, I already had the Algo's name, so I googled "median cut algorithm python" and I found a Github link, 2nd result. This code had different implementations! I can easily find papers and read articles about this algorithm and my issue will be resolved.</p>
<p><strong>That's where the paranoia began!</strong><br />What if this code is AI-generated? It is a 5-year-old code, so probably isn't. But 5 years down the line, Github will be full of mediocre code, full of misunderstood concepts. I see new junior engineers using ChatGPT daily to write small components of code. If there is some dumb code, PR reviewers will catch them. But After 7 years they will be managers and PR reviewers. What then?</p>
<p>Today, every undergrad uses ChatGPT for his/her thesis. Heck, If I had access to it, I would have used it too. When these undergrads will do their PhD, will they use ChatGPT? Yes. From generating topics to writing abstracts and conclusions, even bibliographies, GPT can do it all.</p>
<p>What about checking these papers? One can certainly make AI that could check these. Even if there was a law, that human review is required for any scientific report or article. A Lazy-Smart person will try and automate it. Guess what they would use? AI or Maths?</p>
<p>We can just hope that any hallucinated or out-of-context/sarcastic reference which is interpreted as useful by Students' AI is caught with Teachers' AI.</p>
<p><strong>BTW, This is what ChatGTP 3.5 has to say about it:</strong></p>
<blockquote>
<p>&gt; AI Hallucinations will lead to a mediocre future</p>
<p>While AI hallucinations can be intriguing from a research perspective, they don't necessarily imply a "mediocre future" In fact, AI holds immense potential to revolutionize various fields, from healthcare to transportation, and from education to entertainment.</p>
</blockquote>
<p>AI being biased about AI is probably not ideal, I want my AI to be an insecure nerd (like me), not a confident politician/cult leader.</p>
<p><strong>Conclusion</strong><br />With the invention of the Pen, We gained so much but We lost the power of memorization. With AI, rapid development is imminent, But I feel the loss will be far too much.</p>
<p>We lost our muscles and survival instincts when we left the caves. Heck, Without a flint stone, It would take me ages to light a fire in camp. With mediocre code and misunderstood whitepapers, It seems the time for our brains to regress/halt has come.</p>
<p><strong>What Next?</strong><br />What Next? Nothing mate! Even with all this said, AI will not stop, Skynet is inevitable. Let me give you a taste of what I feel, Ask yourself a simple question, <strong>Who wrote this article?</strong></p>
]]></content:encoded></item><item><title><![CDATA[Boost your Git Squash-Rebase Workflow with these Commands! (auto-squash, auto-commit, auto-rebase, auto-push)]]></title><description><![CDATA[I recently joined a company, that follows squash-rebase flow here, and as my Git KT was going on, I figured I should build these commands before actually starting development, now that I have started development, these turned out to be quite handy!

...]]></description><link>https://blog.ra101.dev/git-auto-squash</link><guid isPermaLink="true">https://blog.ra101.dev/git-auto-squash</guid><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[GitLab]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Thu, 17 Aug 2023 14:55:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692284569550/90ef554d-2f54-4e0a-8573-bccb88908720.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently joined a company, that follows squash-rebase flow here, and as my Git KT was going on, I figured I should build these commands before actually starting development, now that I have started development, these turned out to be quite handy!</p>
<hr />
<h3 id="heading-what-is-git-squash-rebase-workflow">What is Git Squash-Rebase Workflow?</h3>
<p>Git Squash Rebase is a workflow in which:</p>
<ul>
<li><p>multiple commits are squashed into a single cohesive commit,</p>
</li>
<li><p>then rebased from the up-to-date main branch.</p>
</li>
</ul>
<p>This results in a cleaner commit history, grouping of changes, easier code reviews, and streamlined collaboration. <em>Of-course there are some drawbacks of this workflow, but that is beyond the scope of this post.</em></p>
<hr />
<h3 id="heading-git-squash-gsq">Git Squash (<code>gsq</code>):</h3>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">gsq</span></span>(){
    <span class="hljs-comment"># Usage:</span>
    <span class="hljs-comment">## gsq -b "base_branch_opt" -n "squash_count_opt" -m "msg" -d "desc" -D</span>
    <span class="hljs-comment">##</span>
    <span class="hljs-comment">##    -b: Base Branch Name (default: default origin branch)</span>
    <span class="hljs-comment">##    -n: Squash Count (default: all until base branch)</span>
    <span class="hljs-comment">##    -m: Commit Message, (default: latest commit message)</span>
    <span class="hljs-comment">##        - Uses Auto Commit Command, if present.</span>
    <span class="hljs-comment">##    -d: Commit Description, (default: null)</span>
    <span class="hljs-comment">##    -D: if passed, the description is populated with all the previous commit msg and desc until sqaush_count</span>

    <span class="hljs-comment"># Get Base Branch -&gt; Get Fork Point -&gt; Get Squashable Count -&gt; Squash!</span>

    <span class="hljs-comment">## Even though this command seems big, but the flow is pretty simple.</span>
    <span class="hljs-comment">## I use a very lite version of this code, there is alot of validation and</span>
    <span class="hljs-comment">## edges cases here, which is not particularly I care about in my personal use.</span>

    <span class="hljs-comment"># Declare Local Var</span>
    <span class="hljs-built_in">local</span> base_branch_opt; <span class="hljs-built_in">local</span> squash_count_opt; <span class="hljs-built_in">local</span> commit_msg_opt;
    <span class="hljs-built_in">local</span> commit_desc_opt; <span class="hljs-built_in">local</span> add_full_desc_opt=<span class="hljs-literal">false</span>;

    <span class="hljs-comment"># Get Optional Arguments!</span>

    <span class="hljs-comment">## Reset the getopts state</span>
    OPTIND=1
    <span class="hljs-comment">## Parse Through new opts.</span>
    <span class="hljs-keyword">while</span> <span class="hljs-built_in">getopts</span> b:n:m:d:D flag
    <span class="hljs-keyword">do</span>
        <span class="hljs-keyword">case</span> <span class="hljs-string">"<span class="hljs-variable">${flag}</span>"</span> <span class="hljs-keyword">in</span>
            b) base_branch_opt=<span class="hljs-variable">${OPTARG}</span>;;
            n) squash_count_opt=<span class="hljs-variable">${OPTARG}</span>;;
            m) commit_msg_opt=<span class="hljs-variable">${OPTARG}</span>;;
            d) commit_desc_opt=<span class="hljs-variable">${OPTARG}</span>;;
            D) add_full_desc_opt=<span class="hljs-literal">true</span>;;
        <span class="hljs-keyword">esac</span>
    <span class="hljs-keyword">done</span>

    <span class="hljs-comment"># Get Base Branch</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## Update base_branch_opt with default origin branch, if not passed!</span>
    <span class="hljs-built_in">local</span> current_branch=$(git rev-parse --abbrev-ref HEAD)
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$base_branch_opt</span> == <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
        base_branch_opt=$(git symbolic-ref refs/remotes/origin/HEAD | sed <span class="hljs-string">'s@^refs/remotes/origin/@@'</span>)
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment"># Get Fork Point Commit</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment"># Check if given base branch is actually an ancestor or not.</span>
    <span class="hljs-built_in">local</span> fork_point_commit=<span class="hljs-string">""</span>
    <span class="hljs-keyword">if</span> [[ $( git branch --merged HEAD 2&gt; /dev/null | sed  -e <span class="hljs-string">'s/* \(.*\)/ \1/'</span> -e  <span class="hljs-string">'s/^ *//g'</span> | grep -w <span class="hljs-string">"<span class="hljs-variable">$base_branch_opt</span>"</span> ) != <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
        <span class="hljs-comment">### Get the Last commit by `base_branch_opt`</span>
        fork_point_commit=$(git merge-base --fork-point <span class="hljs-string">"<span class="hljs-variable">$base_branch_opt</span>"</span>)
    <span class="hljs-keyword">else</span>
        <span class="hljs-comment">### Throw Error if Base Branch is not found as an ancestor.</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Invalid Base Branch! "</span> &amp;&amp; <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment"># Get Squashable Count</span>
    <span class="hljs-comment"># ----------------</span>
    <span class="hljs-comment">## Exit, if Squashable Count is 0!</span>
    <span class="hljs-comment">## We are okay with squashing 1 commit, the reason for that is, this allows us</span>
    <span class="hljs-comment">## to stage the changes and use `gsq` to commit those changes into squashed commit</span>


    <span class="hljs-comment">## squashable_count: Number of commits that can be to be squashed</span>
    <span class="hljs-built_in">local</span> current_commit=$(git rev-parse HEAD)
    <span class="hljs-built_in">local</span> squashable_count=$(git rev-list --count <span class="hljs-variable">$fork_point_commit</span>..<span class="hljs-variable">$current_commit</span>)

    <span class="hljs-comment">## Exit, if passed squash_count_opt is `0` or not a `number`!</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$squash_count_opt</span> != <span class="hljs-string">""</span> &amp;&amp; ( ! <span class="hljs-variable">$squash_count_opt</span> =~ ^[0-9]+$ || <span class="hljs-variable">$squash_count_opt</span> == 0 )]]; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Invalid Squash Count <span class="hljs-variable">$squash_count_opt</span>! "</span> &amp;&amp; <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">elif</span> [[ <span class="hljs-variable">$squash_count_opt</span> == <span class="hljs-string">""</span>  ]]; <span class="hljs-keyword">then</span>
      squash_count_opt=<span class="hljs-variable">$squashable_count</span>
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment">## Exit, if found `squashable_count` turns about to be `0` !</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$squashable_count</span> == <span class="hljs-string">"0"</span> ]]; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Nothing to Squash! "</span> &amp;&amp; <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment">## Squash Count Passed cannot be more than Squashable Count found!</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$squashable_count</span> &lt; <span class="hljs-variable">$squash_count_opts</span> ]]; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Cannot Squash more than <span class="hljs-variable">$squashable_count</span>! "</span> &amp;&amp; <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment"># Squash!: Get Commit Message and Description.</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## Get Commit Message, (Default: title from latest commit)</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$commit_msg_opt</span> != <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
      <span class="hljs-built_in">local</span> commit_message=<span class="hljs-variable">$commit_msg_opt</span>
    <span class="hljs-keyword">else</span>
      <span class="hljs-built_in">local</span> commit_message=$(git <span class="hljs-built_in">log</span> --format=<span class="hljs-string">"%s"</span> -n1)
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment">## Get Full Commit Description, (Default: raw body from last n commit)</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$add_full_desc_opt</span> == <span class="hljs-literal">true</span> ]]; <span class="hljs-keyword">then</span>
      <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$commit_desc_opt</span> != <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
        commit_desc_opt=<span class="hljs-string">"<span class="hljs-subst">$(echo $commit_desc_opt)</span> <span class="hljs-subst">$(git log --format='%B' -n$squash_count_opt)</span>"</span>
      <span class="hljs-keyword">else</span>
        commit_desc_opt=<span class="hljs-string">"<span class="hljs-subst">$(git log --format='%B' -n$squash_count_opt)</span>"</span>
      <span class="hljs-keyword">fi</span>
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment">## create commit_desc_if_there if commit_desc_opt is populated</span>
    <span class="hljs-built_in">local</span> commit_desc_if_there=<span class="hljs-string">""</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$commit_desc_opt</span> != <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
      commit_desc_if_there=$(<span class="hljs-built_in">echo</span> <span class="hljs-string">"-m '<span class="hljs-variable">$commit_desc_opt</span>'"</span>)
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment"># Squash!: Reset Commits Softly before commiting back.</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## Normally Squashing is done using rebase,</span>
    <span class="hljs-comment">## but I could not automate its interactive shell.</span>
    git reset --soft HEAD~<span class="hljs-variable">$squash_count_opt</span>

    <span class="hljs-comment"># Squash!: Commit to complete squashing!</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## Use Auto Commit Command if There, Else use Default `git commit`</span>
    <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$commit_msg_opt</span> == <span class="hljs-string">""</span> &amp;&amp; $(<span class="hljs-built_in">command</span> -v gac) ]]; <span class="hljs-keyword">then</span>
        gac <span class="hljs-variable">$commit_desc_if_there</span>
    <span class="hljs-keyword">else</span>
        git commit -m <span class="hljs-string">"<span class="hljs-variable">$commit_message</span>"</span> <span class="hljs-variable">$commit_desc_if_there</span>
    <span class="hljs-keyword">fi</span>
}
</code></pre>
<hr />
<h3 id="heading-git-auto-commit-gac">Git Auto Commit (<code>gac</code>):</h3>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">gac</span></span>() {
    <span class="hljs-comment">## The Idea is to create a commit message from branch name</span>
    <span class="hljs-comment">## For Example:</span>
    <span class="hljs-comment">##    if branch name is `feature/jira-123-this-is-issue-desc`</span>
    <span class="hljs-comment">##    then commit would be `[Enhancement JIRA-123] This Is Issue Desc`</span>

    <span class="hljs-comment"># Exit, if there is nothing to commit!</span>
    <span class="hljs-keyword">if</span> [[ $(git diff --staged) == <span class="hljs-string">""</span> ]]; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Nothing to Commit! "</span> &amp;&amp; <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">fi</span>


    <span class="hljs-comment"># Fetch Details</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## `feature/jira-123-this-is-issue-desc`, all in lower case</span>
    <span class="hljs-built_in">local</span> current_branch=$(git rev-parse --abbrev-ref HEAD | tr <span class="hljs-string">'[:upper:]'</span> <span class="hljs-string">'[:lower:]'</span>)

    <span class="hljs-comment">## `feature`</span>
    <span class="hljs-built_in">local</span> issue_type=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$current_branch</span> | cut -d <span class="hljs-string">'/'</span> -f 1)

    <span class="hljs-comment">## `jira-123`</span>
    <span class="hljs-built_in">local</span> issue_no=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$current_branch</span> | cut -d <span class="hljs-string">'/'</span> -f 2- | cut -d <span class="hljs-string">'-'</span> -f -2)

    <span class="hljs-comment">## `this-is-issue-desc`</span>
    <span class="hljs-built_in">local</span> issue_desc=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$current_branch</span> | cut -d <span class="hljs-string">'/'</span> -f 2- | cut -d <span class="hljs-string">'-'</span> -f 3- )


    <span class="hljs-comment"># Format Details</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## We will use this map to get issue_type out of branch name</span>
    <span class="hljs-built_in">declare</span> -A branch_map; branch_map[<span class="hljs-string">"feature"</span>]=<span class="hljs-string">"Enhancement"</span>;
    branch_map[<span class="hljs-string">"bugfix"</span>]=<span class="hljs-string">"Patch"</span>; branch_map[<span class="hljs-string">"version"</span>]=<span class="hljs-string">"Upgrade"</span>;

    <span class="hljs-comment">## `feature` -&gt; `Enhancement`; `random` -&gt; `Random`</span>
    issue_type=<span class="hljs-variable">${branch_map[$issue_type]-${issue_type^}</span>}

    <span class="hljs-comment">## `jira-123` -&gt; `JIRA-123`</span>
    issue_no=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$issue_no</span> | tr <span class="hljs-string">'[:lower:]'</span> <span class="hljs-string">'[:upper:]'</span>)

    <span class="hljs-comment">## `this-is-issue-desc` -&gt; `This Is Issue Desc`</span>
    issue_desc=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$issue_desc</span> | sed <span class="hljs-string">'s/-/ /g'</span> | awk <span class="hljs-string">'{for (i=1; i&lt;=NF; i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1'</span>)

    <span class="hljs-comment">## `[Enhancement JIRA-123] This Is Issue Desc`</span>
    <span class="hljs-built_in">local</span> commit_msg=<span class="hljs-string">"[<span class="hljs-variable">$issue_type</span> <span class="hljs-variable">$issue_no</span>] <span class="hljs-variable">$issue_desc</span>"</span>

    <span class="hljs-comment"># Commit!</span>
    <span class="hljs-comment"># ----------------</span>

    <span class="hljs-comment">## Along with this message, I have added $@, So that all the</span>
    <span class="hljs-comment">## flags and arguments of `git commit` can be passed in this command.</span>
    git commit -m <span class="hljs-string">"<span class="hljs-variable">$commit_msg</span>"</span> <span class="hljs-variable">$@</span>
}
</code></pre>
<hr />
<h3 id="heading-git-fetch-rebase-gfrb">Git Fetch Rebase (<code>gfrb</code>):</h3>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">gfrb</span></span>() {
    <span class="hljs-comment">## If $1 is not passed, then it will fetch the default branch</span>
    <span class="hljs-built_in">local</span> base_branch=<span class="hljs-variable">${1:-$(git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@')}</span>
    git fetch origin <span class="hljs-string">"<span class="hljs-variable">$base_branch</span>"</span>:<span class="hljs-string">"<span class="hljs-variable">$base_branch</span>"</span>

    <span class="hljs-comment">## Rebase requires stashing, but any file that has both</span>
    <span class="hljs-comment">## staged and unstaged changes will lose all its</span>
    <span class="hljs-comment">## unstaged changes! So uncomment at your own risk.</span>

    <span class="hljs-comment"># git stash --all</span>

    git rebase <span class="hljs-string">"<span class="hljs-variable">$base_branch</span>"</span>

    <span class="hljs-comment"># git stash pop</span>
}
</code></pre>
<hr />
<h3 id="heading-git-upstream-push-gup">Git Upstream Push (<code>gup</code>):</h3>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">gup</span></span>() {
    <span class="hljs-comment">## Although `--force` is frequently used in this workflow.</span>
    <span class="hljs-comment">## It still feels destructive to add here.</span>
    <span class="hljs-comment">## Instead I have added $@, So that all the `git push` </span>
    <span class="hljs-comment">## flags and arguments can be passed in this command.</span>
    <span class="hljs-built_in">local</span> current_branch=$(git rev-parse --abbrev-ref HEAD)
    git push --set-upstream origin <span class="hljs-string">"<span class="hljs-variable">$current_branch</span>"</span> <span class="hljs-variable">$@</span>
}
</code></pre>
<hr />
<p>Update your <code>~/.[ba|z]shrc</code> with these productive commands and save those few minutes. Happy Commiting!</p>
<p><strong>You also might like these:</strong></p>
<ul>
<li><p>Check out my gist (<a target="_blank" href="https://gist.github.com/ra101/70ea4389ba04bf6d5a172d9a3000e5f7">alias</a><a target="_blank" href="http://alias.sh">.sh</a>) for a big list of aliases for git, python, Django, and docker.</p>
</li>
<li><p>Made a meme into reality - <a target="_blank" href="https://blog.ra101.dev/new-bash-alias-git-out">New Bash Alias: Git Out</a></p>
</li>
<li><p>And Finally, a fun video - <a target="_blank" href="https://www.youtube.com/watch?v=z0-Rw7guZDY">Bash Script: Enjoy the Little Things!</a></p>
</li>
</ul>
<p><strong>PS: Feel free to share your productivity Hack!</strong></p>
]]></content:encoded></item><item><title><![CDATA[BlockChain as STL (C++): Data Structure, and Iterators]]></title><description><![CDATA[Aim:
To create an iterable blockchain, which could work with an extendable transaction class. Here the link GitHub repo!
Blockchain in Brief:

Blockchain is fundamentally a ledger maintaining records of transaction, This ledger is publicly distribute...]]></description><link>https://blog.ra101.dev/blockchain-cpp</link><guid isPermaLink="true">https://blog.ra101.dev/blockchain-cpp</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[C++]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[ShowHashnode]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Tue, 22 Feb 2022 17:34:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/T9rKvI3N0NM/upload/eb9a1833bd00d702ab29f4c910f7064b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-aim">Aim:</h3>
<p>To create an iterable blockchain, which could work with an extendable transaction class. Here the link <a target="_blank" href="https://github.com/ra101/Generic-BlockChain-container-cpp">GitHub</a> repo!</p>
<h3 id="heading-blockchain-in-brief">Blockchain in Brief:</h3>
<ul>
<li><p>Blockchain is fundamentally a ledger maintaining records of transaction, This ledger is publicly distributed.</p>
</li>
<li><p>Blockchain is a sort of linked-list of Blocks, A Block is a data-structure, that contains a set of transactions.</p>
</li>
<li><p>Whenever a transaction happens, transferring party adds a reward for the "Miner".</p>
</li>
<li><p>A "Miner" picks the set of transactions to be added in block till block-weight-limit (max allowed size of the block) is reached, then "Miner" does some heavy computation as proof of work and then sends the mined block in the world to add in each individual ledger.</p>
</li>
<li><p>These Transactions need not be monetary but could be anything that you want to make immutable.</p>
</li>
</ul>
<h3 id="heading-scope-of-this-project">Scope of this Project:</h3>
<ul>
<li><p>Will not be doing any server-side operations.</p>
</li>
<li><p>Will create a data-structure complete with custom error and iterators.</p>
</li>
<li><p>Miners reward will be sent out by the admin.</p>
</li>
<li><p>No block-weight-limit.</p>
</li>
<li><p>Our Own Custom Proof of Work.</p>
</li>
<li><p>Extendable/Inheritable Transaction Class</p>
</li>
</ul>
<h3 id="heading-plan-of-attack">Plan of Attack:</h3>
<ul>
<li><p>We are going to use <a target="_blank" href="https://ra101.hashnode.dev/rsa-cpp">RSA</a> for our encryption needs.</p>
</li>
<li><p>Extendable <code>base_transaction</code> class.</p>
</li>
<li><p>Create <code>block</code> class with <code>Transaction</code> and <code>HashFunction</code> templates.</p>
</li>
<li><p>Create a <code>blockchain</code> class with the same templates and custom iterators to make it iterable.</p>
</li>
</ul>
<h4 id="heading-setup">Setup</h4>
<p>Lets Setup the extra files!</p>
<h5 id="heading-rsa-library-will-be-used-for-signing-and-verification-of-transactions">RSA: Library will be used for signing and verification of transactions.</h5>
<blockquote>
<p>Create a <code>includes</code> folder and add files from <a target="_blank" href="https://github.com/ra101/RSA-cpp">Github</a></p>
</blockquote>
<h5 id="heading-notimplementedexception-the-exception-that-is-thrown-when-a-requested-method-or-operation-is-not-implemented"><code>not_implemented_exception</code>: The exception that is thrown when a requested method or operation is not implemented.</h5>
<pre><code class="lang-C++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">not_implemented_exception</span> :</span> <span class="hljs-keyword">public</span> logic_error
{
<span class="hljs-keyword">public</span>:
    not_implemented_exception(
        <span class="hljs-built_in">string</span> function = __builtin_FUNCTION()
    ) : logic_error(<span class="hljs-string">"`"</span> + function + <span class="hljs-string">"` not implemented!"</span>){};
};
</code></pre>
<h4 id="heading-basetransaction"><code>base_transaction&lt;EncryptionAlgo&gt;</code></h4>
<p>Here are the required things:</p>
<ul>
<li><p>Parametric Constructor with <code>from_addr</code>, <code>to_addr</code>, <code>transfer_amount</code></p>
</li>
<li><p>Hash Generator function (<code>generate_hash_input</code>)</p>
</li>
<li><p>Override <code>string</code> Operator (for string type casting)</p>
</li>
<li><p>Override <code>&lt;&lt;</code> Operator (for <code>cout</code>)</p>
</li>
<li><p>Override <code>&lt;</code> Operator (for comparison)</p>
</li>
<li><p>Function to get balance based on address (<code>get_balance(addr)</code>)</p>
</li>
<li><p>Function to sign transaction (<code>sign_transaction(key_pair)</code>)</p>
</li>
<li><p>Function to validate transaction (<code>is_transaction_valid(verifying_func)</code>)</p>
</li>
</ul>
<p>Every Function logic will be same, which is to throw <code>not_implemented_exception</code>, for example:</p>
<pre><code class="lang-C++"><span class="hljs-function"><span class="hljs-keyword">operator</span> <span class="hljs-title">string</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span> </span>{<span class="hljs-keyword">throw</span> not_implemented_exception();}
</code></pre>
<h4 id="heading-customtransaction-public-basetransaction"><code>custom_transaction : public base_transaction&lt;EncryptionAlgo&gt;</code></h4>
<p>Private Members:</p>
<ul>
<li><p><code>from_address</code> (Yours <code>public_key</code>)</p>
</li>
<li><p><code>to_address</code> (Others <code>public_key</code>)</p>
</li>
<li><p><code>transfer_amount</code></p>
</li>
<li><p><code>timestamp</code></p>
</li>
<li><p><code>signature</code> (Initially <code>0</code>, will be updated in <code>sign_transaction</code>)</p>
</li>
</ul>
<p>Public Members:</p>
<ul>
<li>Parametric Constructor with <code>from_addr</code>, <code>to_addr</code>, <code>transfer_amount</code></li>
</ul>
<p>custom_transaction(from_adrr, to_addr, amount){ from_address = from_addr; to_address = to_addr; transfer_amount = amount; timestamp = chrono::steady_clock::now(); signature = 0; }</p>
<pre><code class="lang-plaintext">
- Hash Generator function (`generate_hash_input`)

&gt; ```python
# Concatenation of all stringified private variables (except Signature)
# to_string(...) in C++
return (str(from_addr) + str(to_addr) + str(amount) + str(timestamp))
</code></pre>
<ul>
<li>Override <code>string</code> Operator (for string typecasting)</li>
</ul>
<p>operator string() const { string from_address_str = "\nfrom_address: " + to_string(from_address); string to_address_str = "\nto_address: " + to_string(to_address); string transfer_amount_str = "\ntransfer_amount: " + to_string(transfer_amount); string signature_str = "\nsignature: " + to_string(signature); return from_address_str + to_address_str + transfer_amount_str + signature_str; }</p>
<pre><code class="lang-plaintext">
- Override `&lt;&lt;` Operator (for `cout`)

&gt; ```C++
friend ostream &amp;operator&lt;&lt;(ostream &amp;out, custom_transaction const &amp;temp)
{
  // Using above string operator
  return out &lt;&lt; string(temp);
}
</code></pre>
<ul>
<li>Override <code>&lt;</code> Operator (for comparison)</li>
</ul>
<p>bool operator&lt;(const custom_transaction &amp;other) const { return generate_hash_input() &lt; other.generate_hash_input(); }</p>
<pre><code class="lang-plaintext">
- Function to get balance based on the address (`get_balance(addr)`)

&gt; ```C++
float get_balance(addr) const
{
  if (addr == to_address)
    return transfer_amount;
  if (addr == from_address)
    return -transfer_amount;
  return 0;
}
</code></pre>
<ul>
<li>Function to sign transaction (<code>sign_transaction(key_pair)</code>)</li>
</ul>
<blockquote>
<p>Here are some Pointers regarding signing</p>
<ul>
<li>A Transaction is signed by the party making transaction therefore our <code>from_address</code> should match <code>public_key</code> in <code>key_pair</code>. Let us create an Error Regarding that:</li>
</ul>
</blockquote>
<p>class public_key_mismatch : public invalid_argument { public: public_key_mismatch( string addr, std::string pk) : invalid_argument("from_addr: '" + addr + "' do not match public_key: '" + pk + "'"){}; };</p>
<pre><code class="lang-plaintext">&gt; - A Transaction is can be signed once, Let us create a Exception Regarding that:
&gt; ```C++
class resign_transaction_exception : public logic_error
{
public:
    resign_transaction_exception(string transaction) : logic_error("Resigning Transaction!" + transaction){};
};
</code></pre>
<blockquote>
<ul>
<li>Signing of Transaction refers Signing the stringified Transaction class i.e. output of <code>generate_hash_input()</code></li>
</ul>
</blockquote>
<p>template bool sign_transaction(EncryptionAlgo key_pair) { if (from_address != key_pair.get_public_key()) throw public_key_mismatch(to_string(from_address), to_string(key_pair.get_public_key())); if (signature != 0) // already signed throw resign_transaction_exception(*this); signature = key_pair.sign(generate_hash_input()); return true; }</p>
<pre><code class="lang-plaintext">

- Function to validate transaction (`is_transaction_valid(verifying_func)`)

&gt; ```C++
bool is_transaction_valid(bool (*verfication_function)(string, size_t, address)) const
{
  // reward, since reward is given by admin, there is no key pair
  if (from_address == 0)
    return true;
  return verfication_function(generate_hash_input(), signature, from_address);
}
</code></pre>
<h4 id="heading-block"><code>block &lt;Transaction, HashFunctionClass&gt;</code></h4>
<p>NOTES:</p>
<ul>
<li><p>A block typically contains the following:</p>
</li>
<li><p>ID</p>
</li>
<li><p>Previous Hash</p>
</li>
<li><p>timestamp</p>
</li>
<li><p><code>nonce</code> ("number used once") a 32-bit, data computed in proof-of-work</p>
</li>
<li><p>A set of Transactions (Merkel Tree)</p>
</li>
<li><p>Hash (stringification of all of the above)</p>
</li>
<li><p><code>hash_function</code> is an instance of template class used for all hashing related needs (<code>std::hash</code> used in <code>main.cpp</code>)</p>
</li>
<li><p>Proof of Work:</p>
</li>
<li><p>Calculating Hash in such a way that it becomes computationally intensive. A way to make it happen is:</p>
</li>
</ul>
<h1 id="heading-here-nonce-is-found-via-brute-force">Here <code>nonce</code> is found via brute force</h1>
<h1 id="heading-until-hashpatternis-matched">until HASH_PATTERNis matched.</h1>
<p>while(1): hash_input = str(...) + str(nonce) if re.match(hash_function(hash_input), HASH_PATTERN): return nonce nonce += 1</p>
<pre><code class="lang-plaintext">
 - In **BitCoin**:
  - hash_function: `sha256`
  - HASH_PATTERN: Starting with `n` zeros, higher the `n`, harder to compute.

 - In `namespace::ra` :
  - hash_function: Template (`std::hash&lt;string&gt;` for reference)
  - HASH_PATTERN: hash length must be `15/n`, lesser the n, harder to compute.





#### `block_chain &lt;Transaction, HashFunctionClass&gt;`

Well as the name states it is a chain of blocks, So Naturally, It will contain the same Template Arguments as `Block`

Private Members:
- `list&lt;BlockType&gt; chain` (A list of blocks)
- `list&lt;Trasaction&gt; pending_transaction` (Temperaroy Buffer before mining (_create a block and adding it to list_))
- `difficulty` (to be passed in `block` class)
- `minning_reward` (If exists, will add a new transaction from admin before mining block)
- `verfication_function` (to verify block or transaction itself)

Public Members:
- Iterator Class (To make iteration easy)

&gt; - Private:
&gt;  - `std::_List_iterator&lt;block_type&gt;` block_ptr, 
&gt; - Public:
&gt;  - Override `==`, `!=`, `++`, `&amp;++`, `--`, `&amp;--`, for example:

&gt;&gt;&gt; ```C++
iterator operator--(int)
{
    iterator _temp = *this;
    m_block_ptr--;
    return _temp;
}
</code></pre>
<ul>
<li>Override the following to work with iterator class</li>
</ul>
<p>const iterator begin() { return chain.begin(); } const iterator end() { return chain.end(); } block_type &amp;back() { return chain.back(); } block_type &amp;front() { return chain.front(); } int size() { return chain.size(); }</p>
<pre><code class="lang-plaintext">

- `block_chain(diffuculty, verfication_function, minning_reward)` Constructor:
 - Update all the private variable by this constructor
 - Add A Genesis Block to chain! 


- get_balance(): 
 - `float balance = 0`
 - Iterator over the `block_chai`n from `begin()` to `end()` using iterator class and add it to `balance`
 -  return `balance`


- `add_transaction(temp)`
 - check `temp` using `is_transaction_valid` by passing in `verfication_function`
 - add to `pending_transaction` else Throw Error


- `mine_pending_transactions(minning_reward_address)`
 - if `minning_reward` exsits, add a reward `transaction` to `minning_reward_address`, else continue
 - create a block with `pending_transaction`, and push it to chain.
 - clear `pending_transaction`.

- `is_chain_valid()`
 - Iterator over the `chain`, check the validity of current block using `is_block_valid` by passing in `verfication_function`
 - check if `previous_hash` of current block matches `hash` of the previous block

All the code can be found at the below link:
https://github.com/ra101/Generic-BlockChain-container-cpp
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Implementing RSA Cryptography (C++)]]></title><description><![CDATA[Aim:
To create a working RSA code, Using namespace ra::random_prime_engine, Here the link GitHub repo!
What is RSA?
The Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm. Asymmetric Encryption is when a box(data) can be locked by one ...]]></description><link>https://blog.ra101.dev/rsa-cpp</link><guid isPermaLink="true">https://blog.ra101.dev/rsa-cpp</guid><category><![CDATA[C++]]></category><category><![CDATA[Cryptography]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[ShowHashnode]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Fri, 28 Jan 2022 14:10:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FnA5pAzqhMM/upload/a29d85147226ce679bbef4ac034006c2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-aim">Aim:</h3>
<p>To create a working RSA code, Using <a target="_blank" href="https://ra101.hashnode.dev/random-prime-generator"><code>namespace ra::random_prime_engine</code></a>, Here the link <a target="_blank" href="https://github.com/ra101/RSA-cpp">GitHub</a> repo!</p>
<h3 id="heading-what-is-rsa">What is RSA?</h3>
<p>The Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm. Asymmetric Encryption is when a box(data) can be locked by one key and unlocked by other. locking key cannot unlock the box and vice-versa. The locking key is the public key and the unlocking key is the private key, Public key is called so because we publicly distribute it, so anyone/everyone would send the user an encrypted msg, and the user can unlock it in private with the private key.
By keeping private to the user-self, no hacker can get a method of unlocking it.</p>
<h4 id="heading-how-rsa-works">How RSA Works?</h4>
<p>https://ra101.hashnode.dev/rsa-encryption-algorithm</p>
<h3 id="heading-code">Code:</h3>
<ul>
<li>Private Members:<ul>
<li><code>private_key</code></li>
<li><code>public_key</code></li>
<li><code>create_key(long seed)</code></li>
</ul>
</li>
</ul>
<ul>
<li>Public Members:<ul>
<li><code>Constructor</code> &amp; <code>Constructor(seed)</code></li>
<li><code>std::size_t decrypt(std::size_t);</code></li>
<li><code>std::size_t decrypt_with_padding(std::string);</code></li>
<li><code>Key Getters</code></li>
<li><code>std::size_t sign(Message message)</code></li>
</ul>
</li>
</ul>
<ul>
<li>Other Function within <code>namespace</code> but Outside <code>class</code> <em>(All the functions utilizing public key)</em>:<ul>
<li><code>std::size_t encrypt(std::size_t digest, public_key);</code></li>
<li><code>std::string encrypt_with_padding(std::size_t digest, public_key);</code></li>
<li><code>bool verify(Message message, size_t digest, public_key)</code></li>
<li><code>string padding(string)</code></li>
</ul>
</li>
</ul>
<h4 id="heading-constructors">Constructors:</h4>
<p>The seed in the constructor is used in <code>random prime engine</code> and the logic of the seed argument is as follow,</p>
<pre><code class="lang-python"><span class="hljs-comment"># pseudo code implemented in python</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">constructor</span>(<span class="hljs-params">seed=None</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> seed:
        seed = timestamp()
    <span class="hljs-keyword">else</span>:
        seed = hash(seed)
   <span class="hljs-keyword">return</span> create_key(seed)
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">// Usage</span>

ra::rsa_key_pair k1, k2(<span class="hljs-string">"127.0.0.1"</span>);
</code></pre>
<h4 id="heading-createkeyseed-function"><code>create_key(seed)</code> function,</h4>
<p>I will not get into the mathematics of it all, but in the end, using 2 primary numbers we get</p>
<ul>
<li>public key: (n, e)</li>
<li>private key: (n, d)</li>
</ul>
<p>(n, e, d) all are integers.</p>
<p>To concatenate these two numbers (n, e/d) let us define a big number <code>BIG_NO</code>, such that </p>
<ul>
<li>n = key / BIG_NO</li>
<li>e = public_key % BIG_NO</li>
<li>d = private_key % BIG_NO</li>
</ul>
<pre><code class="lang-C++"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> BIG_NO 100000000000</span>

public_key = n * BIG_NO + e;
private_key = n * BIG_NO + d;
</code></pre>
<h4 id="heading-encryptdigest-key-function"><code>encrypt(digest, key)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> (digest ** e) % n
</code></pre>
<h4 id="heading-decryptencrypteddata-function"><code>decrypt(encrypted_data)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> (encrypted_data ** d) % n
</code></pre>
<h4 id="heading-paddingstring-str-function"><code>padding(string str)</code> function,</h4>
<pre><code class="lang-C++"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> PAD_SIZE 10</span>

<span class="hljs-comment">// 12345 -&gt; 0000012345</span>
<span class="hljs-keyword">while</span> (str.length() &lt; PAD_SIZE)
{
    str = <span class="hljs-string">'0'</span> + str; <span class="hljs-comment">// add 0 in front of no.</span>
}
<span class="hljs-keyword">return</span> str;
</code></pre>
<h4 id="heading-encryptwithpaddingdigest-key-function"><code>encrypt_with_padding(digest, key)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-comment"># encrypt each digit</span>
<span class="hljs-keyword">for</span> each_digit <span class="hljs-keyword">in</span> digest:
    output = padding(encrypt(each_digit)) + output
<span class="hljs-keyword">return</span> output
</code></pre>
<h4 id="heading-decryptwithpaddingencrypteddata-function"><code>decrypt_with_padding(encrypted_data)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-comment"># cut the input string in chunks of length PAD_SIZE</span>
<span class="hljs-comment"># decrypt each chunk to digit and then form a output</span>
<span class="hljs-keyword">for</span> i_chunk <span class="hljs-keyword">in</span> len(encrypted_data)/PAD_SIZE:
    i = i_chunk * PAD_SIZE
    digit = decrypt(int(encrypted_data[i: i + PAD_SIZE]))
    output = digit + output * <span class="hljs-number">10</span>
<span class="hljs-keyword">return</span> output
</code></pre>
<h4 id="heading-signmessage-message-function"><code>sign(Message message)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> decrypt(hash(message))
</code></pre>
<h4 id="heading-verifymessage-message-digest-otherspublickey-function"><code>verify(Message message, digest, others_public_key)</code> function,</h4>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> ( hash(message) == encrypt(digest, others_public_key) )
</code></pre>
<p>All the code can be found at the below link: https://github.com/ra101/RSA-cpp</p>
]]></content:encoded></item><item><title><![CDATA[Mathematics of RSA Encryption Algorithm]]></title><description><![CDATA[What is RSA?
The Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm. Asymmetric Encryption is when a box(data) can be locked by one key and unlocked by other. locking key cannot unlock the box and vice-versa. The locking key is the pub...]]></description><link>https://blog.ra101.dev/rsa-encryption-algorithm</link><guid isPermaLink="true">https://blog.ra101.dev/rsa-encryption-algorithm</guid><category><![CDATA[encryption]]></category><category><![CDATA[Cryptography]]></category><category><![CDATA[Mathematics]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Thu, 13 Jan 2022 13:46:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/YriuRFYUP0I/upload/009b857b851c71c709e0067ed35b05ca.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-rsa">What is RSA?</h3>
<p>The Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm. Asymmetric Encryption is when a box(data) can be locked by one key and unlocked by other. locking key cannot unlock the box and vice-versa. The locking key is the public key and the unlocking key is the private key, Public key is called so, because it is publicly distributed, so anyone/everyone would send the user an encrypted msg, and the user can unlock it in private with the private key.
By keeping private to the user-self, no hacker can get a method of unlocking it.</p>
<hr />
<h3 id="heading-how-asymmetric-encryption-is-achieved">How Asymmetric Encryption is achieved?</h3>
<p>We need a mathematical function such that</p>
<blockquote>
<center> <code>f</code>: public key function , <code>g</code>: private key function
<br />
<code>f</code><sup><code>-1</code></sup><code>(f(msg)) != msg</code>
<br />
<code>g(g</code><sup><code>-1</code></sup><code>(msg)) != msg</code>
<br />
<code>g(f(msg)) == msg</code></center>

</blockquote>
<hr />
<h3 id="heading-signing-document-via-asymmetric-encryption">Signing Document via Asymmetric Encryption:</h3>
<p>Digital Signature is the by-product of Asymmetric Encryption, In most asymmetric encryption algorithms (including RSA), public and private are just names, one can simply interchange them for locking and unlocking. Here is how to sign a document:</p>
<p><strong>How to sign:</strong></p>
<ul>
<li>Step 1: Calculate hash of the document using an unbreakable and popular hashing algorithm (for eg. SHA-256)</li>
<li>Step 2: Make <code>digest</code> by performing the decryption function with the private key on that hash.</li>
<li>Step 3: Send the document, digest, and hashing algorithm to the world.</li>
</ul>
<p><strong>How to Verify:</strong></p>
<ul>
<li>Step 1: Calculate the hash of the document using the provided hashing algorithm, let's call it the "calculated hash".</li>
<li>Step 2: Get the hash by performing the encryption function with the user's public key on that digest,  let's call it the "given hash".</li>
<li>Step 3: If "calculated hash" matches with the "given hash" then the document is authentic else not.</li>
</ul>
<hr />
<h3 id="heading-mathematics-of-rsa">Mathematics of RSA:</h3>
<p>for <code>g</code> and <code>f</code> should be such that <code>g</code> must relatively harder to perform so that it could not be cracked by brute force.</p>
<p>First, let's get this straight. Every string data can be represented as numbers or chunks of numbers, which can happen via ASCII or change it to binary then to decimal. So mathematical operation can be used on any and every data.</p>
<p>Consider <code>m</code> as the message. say m is 10, now we have to find 2 functions, one that will change it some else and the other that can change back!</p>
<blockquote>
<p>Multiplication/Division:</p>
<blockquote>
<p><center>let <code>f(key, m) = key * m</code></center>
so now we have to distribute <code>f</code> and <code>key</code> but same key can be used to change it back!</p>
</blockquote>
<p>Addition/Subtraction:</p>
<blockquote>
<p><center>let <code>f(key, m) = key + m</code></center>
so now we have to distribute <code>f</code> and <code>key</code> but same key can be used to change it back!</p>
</blockquote>
<p>Trigonometry:</p>
<blockquote>
<p><center> let <code>f(..., m) = sin(... m)</code> </center>
Here the problem is the decimal nature of output, can have different result at different machines!</p>
</blockquote>
</blockquote>
<p><br /></p>
<blockquote>
<p>Modulus:
For those who are new to modulus function, it is the reminder of integer division.</p>
<blockquote>
<p><center> <code>x mod y</code> =&gt; <code>ky - x</code> where <code>ky</code> &gt; <code>x</code> </center>
for example: <code>7/5 = 1</code> and <code>2 = 7 mod 5</code></p>
</blockquote>
<p>Here is the catch, for</p>
<blockquote>
<p><center><code>2 = m mod 5</code>
<code>m</code> can be <code>2, 7, 12... 5*(x) + 2</code></center>
So a hacker with <code>2</code> (encrypted msg) and <code>5</code> cannot decode the <code>m</code>, but so can't we.</p>
</blockquote>
<p>Let us try one more trick</p>
<blockquote>
<p><center> <code>3</code><sup><code>m</code></sup><code>mod 5 = x</code><br />
for if <code>m</code> is <code>0, 1, 2, 3, 4 ...</code> x is <code>1, 3, 4, 2, 1 ...</code> respectively, <code>m</code> is uniformly distributed in 1 to 4.</center>
So a hacker with <code>x</code> (encrypted msg), <code>5</code> and <code>3</code> cannot decode the <code>m</code>, but still so can't we. Another major point to be noted is, if <code>3 &lt; 5</code> exists, then <code>x == 3</code> for some <code>m</code> and <code>x &lt; 5</code> exists always.</p>
</blockquote>
<p>Now Let us merge both tricks.</p>
<blockquote>
<p><center> <code>m</code><sup><code>e</code></sup><code>mod n = x</code>, <code>m &lt; n</code>    --&gt; eq 1<br />
<code>m</code>: message, <code>e</code>, <code>n</code>: some constants, <code>x</code>: encrypted message</center>
Let there be another equation</p>
<p><center> <code>x</code><sup><code>d</code></sup><code>mod n = m</code>    --&gt; eq 2<br />
<code>x</code>: encrypted message, <code>d</code>, <code>n</code>: some constants, <code>m</code>: message</center><br />
Let us substitute <code>x</code> in <code>eq 2</code> with <code>eq 1</code><br /></p>
<p><center> <code>(m</code><sup><code>d</code></sup><code>mod n)</code><sup><code>e</code></sup><code>mod n = m</code><br />
<code>m</code><sup><code>e * d</code></sup><code>mod n = m</code><br />
<code>m</code>: message, <code>e</code>, <code>d</code>, <code>n</code>: some constants, <code>x</code>: encrypted message</center>
in other words: <code>e</code> -&gt; <code>public_key</code> and <code>d</code> -&gt; <code>private_key</code>
All we need is do is define those constants and we are good to go! </p>
</blockquote>
<p>Now Lets take a dive into history,</p>
<blockquote>
<p>Introducing the <code>Totient</code> function aka Euler's phi function</p>
<p><center> <code>phi(n) = m</code>, <code>m</code> is the <b>count</b> of integers b/w <code>[1, n]</code>, which are coprime(relatively prime) to <code>n</code></center><br />
for example, <code>phi(8) = 2</code> as, <code>gcd(6, n) == 1</code> holds true only for <code>1</code> and <code>5</code>.</p>
<ul>
<li>Interestingly enough, <code>phi(prime)</code> is always <code>prime - 1</code>, as all the numbers before prime gave their <code>gcd</code> as <code>1</code>, given the definition of prime is exactly that.</li>
<li>Another Observation is <code>phi(p1 * p2) = phi(p1) * phi(p2)</code></li>
</ul>
</blockquote>
<p>Let's cook with the ingredients we have.</p>
<blockquote>
<ul>
<li><code>phi(n) = Set of all the co-primes</code></li>
<li><code>3</code><sup><code>e</code></sup><code>mod 5 = x</code>,<br /> for if <code>e</code> is <code>0, 1, 2, 3, 4 ...</code> x is <code>1, 3, 4, 2, 1 ...</code> respectively, <code>e</code> is <strong>uniformly distributed</strong> in 1 to 4.</li>
<li>Let there be <code>a</code><sup><code>k</code></sup>, such that <code>a</code><sup><code>k</code></sup><code>= 1 mod n</code></li>
<li>Since, is <code>k</code> one of the uniformly distributed power, it must be within <code>phi(n)</code>, therefore <code>phi(n) = kc</code>, there <code>c</code> is some constant.</li>
<li>Now if raise both side with power for <code>c</code></li>
<li>It becomes: <code>a</code><sup><code>kc</code></sup><code>= a</code><sup><code>phi(n)</code></sup><code>= 1 mod n</code>
This is <code>Fermat–Euler Theorem</code></li>
</ul>
</blockquote>
<p>Merge both the discoveries:</p>
<blockquote>
<center> <code>a * a</code><sup><code>phi(n)</code></sup><code>mod n = a</code><sup><code>ed</code></sup><code>mod n</code> <br />
<code>a * a</code><sup><code>phi(n) * c</code></sup><code>= a</code><sup><code>ed</code></sup><code>mod n</code><br />
<code>(phi(n) * c) + 1 = e * d</code></center><br />
if <code>n</code> is product of big prime number then phi(n) easy to calculate and <code>n</code> itself hard to find (prime factorization would take a lot of time)
<center> <code>d = (c * phi(n) + 1) / e</code><br />
where <code>c</code> is calculated such that <code>d</code> becomes an integer
<code>(n, e)</code> : public key, <code>(n, d)</code>: private key</center>  

</blockquote>
</blockquote>
<hr />
<h3 id="heading-bibliography-resources">Bibliography / Resources:</h3>
<p><strong>RSA Brief:</strong> https://www.youtube.com/watch?v=wXB-V_Keiu8</p>
<p><strong>Khan Academy:</strong> https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/v/intro-to-rsa-encryption</p>
<p><strong>Proof of Fermat–Euler Theorem:</strong> https://www.youtube.com/watch?v=5pswKNgVZSg</p>
<p><strong>RSA SIgning:</strong> https://www.cs.cornell.edu/courses/cs5430/2015sp/notes/rsa_sign_vs_dec.php</p>
]]></content:encoded></item><item><title><![CDATA[Random Prime Number Generator (C++)]]></title><description><![CDATA[Aim:
To create a random number engine that generates prime number on the go! Here the link GitHub repo
Plan of Attack:

Since finding prime number in constant time is impossible by the math at the moment, So We are going to use a database-based appro...]]></description><link>https://blog.ra101.dev/random-prime-generator</link><guid isPermaLink="true">https://blog.ra101.dev/random-prime-generator</guid><category><![CDATA[C++]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[ShowHashnode]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Mon, 10 Jan 2022 10:07:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/a5845259dc02d788f47a821fb6eaa09f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-aim">Aim:</h3>
<p>To create a random number engine that generates prime number on the go! Here the link <a target="_blank" href="https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp">GitHub</a> repo</p>
<h3 id="heading-plan-of-attack">Plan of Attack:</h3>
<ul>
<li>Since finding prime number in constant time is impossible by the math at the moment, So We are going to use a database-based approach. Lets store all the prime number in <code>primeDB</code> file</li>
<li>Since <code>C++</code> already have <a target="_blank" href="https://en.cppreference.com/w/cpp/numeric/random">random engines</a>, Let us create a wrapper around that using <a target="_blank" href="https://en.cppreference.com/w/cpp/language/templates">templates</a></li>
</ul>
<h3 id="heading-objective">Objective:</h3>
<ul>
<li><a target="_blank" href="https://en.cppreference.com/w/cpp/container">Container</a> that takes in engine class and override all the engine functions, also takes in filepath for database</li>
<li>Functions to override<ul>
<li><code>()</code> -&gt; returns random prime number</li>
<li><code>min()</code> -&gt; returns min prime number</li>
<li><code>max()</code> -&gt; returns max prime number</li>
<li><code>&lt;&lt;</code> -&gt; save the state to <code>std::stringstream</code></li>
<li><code>&gt;&gt;</code> -&gt; restores the state from <code>std::stringstream</code></li>
</ul>
</li>
</ul>
<h3 id="heading-code">Code:</h3>
<ul>
<li>Private Members:<ul>
<li><code>template &lt;typename Engine&gt; Engine eng;</code></li>
<li><code>int min_prime;</code></li>
<li><code>int max_prime;</code></li>
<li><code>char const *db_filepath;</code></li>
</ul>
</li>
</ul>
<ul>
<li>Public Members:<ul>
<li><code>Constructor</code></li>
<li><code>int operator()();</code></li>
<li><code>friend stringstream &amp;operator&lt;&lt;</code></li>
<li><code>friend stringstream &amp;operator&gt;&gt;</code></li>
</ul>
</li>
</ul>
<h4 id="heading-constructor-takes-in-seed-and-filepath">Constructor: takes in <code>seed</code> and <code>filepath</code></h4>
<pre><code class="lang-C++"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DB_FILEPATH <span class="hljs-meta-string">"primeDB"</span></span>

<span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> Engine&gt;
random_prime_engine&lt;Engine&gt;::random_prime_engine(<span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">long</span> rand_seed, <span class="hljs-keyword">char</span> <span class="hljs-keyword">const</span> *db_filepath=DB_FILEPATH)
{
    <span class="hljs-comment">// Get DB path</span>
    <span class="hljs-keyword">this</span>-&gt;db_filepath = db_filepath;
    eng.seed(rand_seed);
}
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">// Usage</span>

<span class="hljs-function">ra::random_prime_engine&lt;<span class="hljs-built_in">std</span>::default_random_engine&gt; <span class="hljs-title">rpe_2</span><span class="hljs-params">(rand_seed)</span></span>;
</code></pre>
<h4 id="heading-operator"><code>()</code> operator,</h4>
<pre><code class="lang-C++"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DB_SIZE 10000</span>

<span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> Engine&gt;
<span class="hljs-keyword">int</span> random_prime_engine&lt;Engine&gt;::<span class="hljs-keyword">operator</span>()()
{
    <span class="hljs-keyword">int</span> idx = eng() % DB_SIZE; <span class="hljs-comment">// to get a index within file</span>
    <span class="hljs-keyword">int</span> rand_prime;

    <span class="hljs-comment">// Open the file</span>
    <span class="hljs-built_in">std</span>::ifstream file;
    file.open(db_filepath);

    <span class="hljs-comment">// update rand_prime till it gets the value at index</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= idx; i++)
        file &gt;&gt; rand_prime;

    file.close();
    <span class="hljs-keyword">return</span> (rand_prime);
}
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">// Usage</span>

<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; rpe()
</code></pre>
<h4 id="heading-min-and-max">min and max</h4>
<pre><code class="lang-python"><span class="hljs-comment"># pseudo code</span>
<span class="hljs-comment"># initialize min/max with 0, for lazy initialization</span>

{
    <span class="hljs-comment"># return min or max if once found</span>
    <span class="hljs-keyword">if</span> bool(min/max):
        <span class="hljs-keyword">return</span> min/max

    min = file.first_line
    max = file.last_line

    <span class="hljs-keyword">return</span> min/max
}
</code></pre>
<h4 id="heading-andgtandgt-and-andlt"><code>&gt;&gt;</code> and <code>&lt;&lt;</code></h4>
<pre><code class="lang-C++"><span class="hljs-comment">// Friend Functions</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> stringstream SS</span>
function SS &amp;<span class="hljs-keyword">operator</span>&lt;&gt;(SS&amp;in/out, rpe){
    in/out &gt;&gt; rpe.eng;
    <span class="hljs-keyword">return</span> in/out
}
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">// Usage</span>

<span class="hljs-built_in">std</span>::<span class="hljs-built_in">stringstream</span> state;
state &lt;&lt; rpe; <span class="hljs-comment">//save current state</span>
state &gt;&gt; rpe; <span class="hljs-comment">//restore old state</span>
</code></pre>
<p>All the code can be found at the below link:
https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp</p>
]]></content:encoded></item><item><title><![CDATA[Intro to Emoji URLs]]></title><description><![CDATA[I was looking for catchy domain names, And I came across emoji domains like 📙.ws or i❤️.ws

Well, I knew what my task of day is going to be. Below is the report of my 3 hour investigation into Emoji Domains.

How are they possible?
To create standar...]]></description><link>https://blog.ra101.dev/intro-to-emoji-urls</link><guid isPermaLink="true">https://blog.ra101.dev/intro-to-emoji-urls</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Fri, 05 Nov 2021 09:06:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636289033995/GOmieQuhQ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I was looking for catchy domain names, And I came across emoji domains like <a target="_blank" href="http://📙.ws/">📙.ws</a> or <a target="_blank" href="http://i❤️.ws/">i❤️.ws
</a></p>
<p>Well, I knew what my task of day is going to be. Below is the report of my 3 hour investigation into Emoji Domains.
<br /></p>
<h3 id="heading-how-are-they-possible">How are they possible?</h3>
<p>To create standardization in Internet hostnames every domain name is encoded into punycode, a LDH (letters, digits, and hyphens) subset of ASCII, by browsers before URL encoding it. pseudo code for the flow can written as:</p>
<pre><code>final_url <span class="hljs-operator">=</span> url.encode(
    punycode.encode(domain.<span class="hljs-built_in">name</span>) <span class="hljs-operator">+</span> <span class="hljs-string">'/rest of the path'</span>
)
</code></pre><p>Now, by only using LDH, other ASCII char are converted into <code>xn--</code> form, some examples are:</p>
<ul>
<li><code>ü</code> -&gt; <code>xn--tda</code></li>
<li><code>人</code> -&gt; <code>xn--gmq</code></li>
<li><code>😀</code> -&gt; <code>xn--e28h</code></li>
</ul>
<p>links: <a target="_blank" href="punycoder.com">punycoder.com</a> | <a target="_blank" href="urlenc.com">urlenc.com</a>
<br /></p>
<h3 id="heading-why-are-they-so-rare">Why are they so rare?</h3>
<p>With the restriction of LDH many hosting services also add the rule that <code>-</code> must be surrounded by characters to decrease changes of scamming or exploits therefore making <code>--</code> illegal. </p>
<p>Click <a target="_blank" href="https://www.20i.com/support/domain-names/domain-name-restrictions">Here</a> to know more.
<br /></p>
<p><strong>Loop-Hole: According to <a target="_blank" href="https://en.wikipedia.org/wiki/Emoji_domain#Availability_and_registration">wikipedia</a>, <code>As of April 2021, there are eleven top-level domains for which registration is possible: .uz, .cf, .ga, .gq, .ml, .tk, .st, .fm, .to, .kz and .ws</code></strong>
<br /></p>
<h3 id="heading-lets-get-one">Lets get one!</h3>
<p><em>I noticed <code>.tk</code>, and I remembered long ago they were giving redirector domain names for free that too without signup. I checked back, sadly that was not the case anymore, Although the fees was not that much, But I am not willing to pay for a detour in my evening.</em></p>
<p><em>Okay if we can't have domain name, lets get a subdomain, 
I already have a <a target="_blank" href="infinityfree.net">InfinityFree</a> account, So lets try there, but it looked at <code>--</code> and said <code>no latin letters</code>, So, I looked around and found some websites but I had to input my card info, so i backed out.</em></p>
<p><strong>Finally, <a target="_blank" href="https://profreehost.com">ProFreeHost</a> was my saviour, I quickly setup an account, found how to redirect the url</strong>, only thing left was to think of a domain name, After ton of soul searching, there it was on my youtube feed, <code>Lightyear | Teaser Trailer</code>. <strong>So I went to infinity and beyond and created my website:
<a target="_blank" href="http://2️⃣♾️➕🚀.unaux.com/">2️⃣♾️➕🚀.unaux.com</a></strong>
<br /></p>
<p>If you make/made your own Emoji Website, comment below and share with us as well.</p>
]]></content:encoded></item><item><title><![CDATA[Python: Reimaging Constants]]></title><description><![CDATA[A different implementation of constant for python
I couldn't find a good implementation of constants, so created my own! Let's get started!
Do checkout the complete code at https://gist.github.com/ra101/aa27ff6e437f74ca56027a8c6b166882
How it Should ...]]></description><link>https://blog.ra101.dev/python-reimaging-constants</link><guid isPermaLink="true">https://blog.ra101.dev/python-reimaging-constants</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Sat, 02 Oct 2021 18:58:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xrVDYZRGdw4/upload/d0f810c0a136cdcd3d4b80a2e8f3a499.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A different implementation of constant for python</p>
<p>I couldn't find a good implementation of constants, so created my own! Let's get started!</p>
<p>Do checkout the complete code at https://gist.github.com/ra101/aa27ff6e437f74ca56027a8c6b166882</p>
<p>How it Should work</p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Links</span>(<span class="hljs-params">ConstantClass</span>):</span>
        GITHUB = <span class="hljs-string">"https://github.com/ra101"</span>
        WEB = <span class="hljs-string">"https://ra101.github.io/"</span>
        LINKS = <span class="hljs-string">"dev.ra.101@protonmail.com"</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">ConstantClass</span>):</span>
        NAME = <span class="hljs-string">"〈 RA 〉"</span>
        WEB = Links.WEB
        LINKS = Links
</code></pre>
<p>Now <code>Links.GITHUB</code> should return <code>https://github.com/ra101</code> and <code>Link.GITHUB = 'new_value'</code> or <code>Links.NEW_CONTANTS = NEW_VALUE</code> both should return None, without assigning or creating new field</p>
<h1 id="heading-here-is-how-i-made-it">Here is How I made it!</h1>
<ol>
<li>We need to mock all setter in a meta class, which will be used by main class.</li>
</ol>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConstantMeta</span>(<span class="hljs-params">type</span>):</span>
    <span class="hljs-string">"""
    Meta Class for Constant, How Constant class would behave
    """</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__setattribute__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        <span class="hljs-comment"># Override set method to make it immutable</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__setattr__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        <span class="hljs-comment"># Override set method to make it immutable</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__setitem__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        <span class="hljs-comment"># Override set method to make it immutable</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__set__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        <span class="hljs-comment"># Override set method to make it immutable</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<p>1.5) Lets add a external setter</p>
<pre><code class="lang-python">    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__force_set__</span>(<span class="hljs-params">self, name, value</span>):</span>
        <span class="hljs-comment"># A external set method to make sure we can update value in __new__</span>
        <span class="hljs-keyword">return</span> super().__setattr__(name, value)
</code></pre>
<ol>
<li>Override <code>__new__</code> to make the actual class</li>
</ol>
<pre><code class="lang-python">    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span>(<span class="hljs-params">cls, clsname, bases, clsdict</span>):</span>
        <span class="hljs-string">"""
        adding __keys__, __values__ fields
        and keys(), values() methods
        """</span>
        obj = super().__new__(cls, clsname, bases, clsdict)
        obj.__force_set__(<span class="hljs-string">"__values__"</span>, [])
        obj.__force_set__(<span class="hljs-string">"__keys__"</span>, [])
        <span class="hljs-keyword">for</span> key, val <span class="hljs-keyword">in</span> vars(obj).items():
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> key.startswith(<span class="hljs-string">"__"</span>):
                obj.__values__.append(val)
                obj.__keys__.append(key)
        obj.__force_set__(<span class="hljs-string">"keys"</span>, <span class="hljs-keyword">lambda</span>: obj.__keys__)
        obj.__force_set__(<span class="hljs-string">"values"</span>, <span class="hljs-keyword">lambda</span>: obj.__values__)
        <span class="hljs-keyword">return</span> obj
</code></pre>
<p>2.5) Add below methods for polishing the class</p>
<pre><code class="lang-python">
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span>(<span class="hljs-params">cls, key</span>):</span>
        <span class="hljs-comment"># adding __getitem__ to make objects "subscriptable"</span>
        <span class="hljs-keyword">return</span> getattr(cls, key)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span>(<span class="hljs-params">cls</span>):</span>
        <span class="hljs-comment"># In case of for loops</span>
        <span class="hljs-keyword">return</span> zip(cls.__keys__, cls.__values__)
</code></pre>
<ol>
<li>Finally Lets create the class!</li>
</ol>
<pre><code class="lang-python">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConstantClass</span>(<span class="hljs-params">metaclass=ConstantMeta</span>):</span>
    <span class="hljs-string">"""
    Now this class can be inherited whenever required to make constants
    """</span>

    <span class="hljs-keyword">pass</span>
</code></pre>
<p>Finally! We are Done! We Created a almost immutable class that could be used as constants</p>
<h2 id="heading-examples">Examples</h2>
<p><strong>Input:</strong></p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Links</span>(<span class="hljs-params">ConstantClass</span>):</span>
        GITHUB = <span class="hljs-string">"https://github.com/ra101"</span>
        WEB = <span class="hljs-string">"https://ra101.github.io/"</span>
        LINKS = <span class="hljs-string">"dev.ra.101@protonmail.com"</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">ConstantClass</span>):</span>
        NAME = <span class="hljs-string">"〈 RA 〉"</span>
        WEB = Links.WEB
        LINKS = Links

    Links.WEB = <span class="hljs-string">'any_new_value'</span>

    print(<span class="hljs-string">f"\nLinks.WEB: <span class="hljs-subst">{Links.WEB}</span>"</span>)
    print(<span class="hljs-string">f"\nAuthor.values(): <span class="hljs-subst">{Author.values()}</span>"</span>)
    print(<span class="hljs-string">f"\ndict(Author): <span class="hljs-subst">{dict(Author)}</span>"</span>)
    print(<span class="hljs-string">"\nfor key in Author.LINKS.keys()"</span>)
    <span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> Author.LINKS.keys():
        print(<span class="hljs-string">f'getattr(Author.LINKS, "<span class="hljs-subst">{key}</span>"): <span class="hljs-subst">{getattr(Author.LINKS, key)}</span>'</span>)
</code></pre>
<p>Author.values(): ['〈 RA 〉', 'https://ra101.github.io/', &lt;<strong>main</strong>.ConstantClass object at 0x00000293A94768E0&gt;]</p>
<p>dict(Author): {'NAME': '〈 RA 〉', 'WEB': 'https://ra101.github.io/', 'LINKS': &lt;<strong>main</strong>.ConstantClass object at 0x00000293A94768E0&gt;}</p>
<p>for key in Author.LINKS.keys() getattr(Author.LINKS, "GITHUB"): https://github.com/ra101 getattr(Author.LINKS, "WEB"): https://ra101.github.io/ getattr(Author.LINKS, "EMAIL"): dev.ra.101@protonmail.com</p>
<pre><code class="lang-plaintext">
Do checkout the complete code at https://gist.github.com/ra101/aa27ff6e437f74ca56027a8c6b166882
</code></pre>
]]></content:encoded></item><item><title><![CDATA[MasquerBot: A Telegram Bot for true paranoids.]]></title><description><![CDATA[https://www.youtube.com/watch?v=yH3SVmCZD7Q
https://t.me/MasquerBot
I watched Snowden in 2016. It was the year, I became paranoid. 👻
Introducing 𝗠𝗮𝘀𝗾𝘂𝗲𝗿𝗕𝗼𝘁! It is a telegram_bot that can hide any given text message inside any given image, ...]]></description><link>https://blog.ra101.dev/masquerbot-a-telegram-bot-for-true-paranoids</link><guid isPermaLink="true">https://blog.ra101.dev/masquerbot-a-telegram-bot-for-true-paranoids</guid><category><![CDATA[Python]]></category><category><![CDATA[bot]]></category><category><![CDATA[Cryptography]]></category><category><![CDATA[ShowHashnode]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Thu, 12 Aug 2021 20:33:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636289043908/OD01idldc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=yH3SVmCZD7Q">https://www.youtube.com/watch?v=yH3SVmCZD7Q</a></div>
<h3 id="httpstmemasquerbot">https://t.me/MasquerBot</h3>
<p>I watched Snowden in 2016. It was the year, I became paranoid. 👻</p>
<p>Introducing 𝗠𝗮𝘀𝗾𝘂𝗲𝗿𝗕𝗼𝘁! It is a telegram_bot that can hide any given text message inside any given image, by manipulating the very pixels of that image (steganography)</p>
<p>• URL changes every 6 hrs, with 130 char long, therefore making it impossible to trace by anyone other than Telegram.</p>
<p>𝘍𝘢𝘳 𝘣𝘦𝘵𝘵𝘦𝘳 𝘥𝘰𝘤𝘶𝘮𝘦𝘯𝘵𝘢𝘵𝘪𝘰𝘯 𝘪𝘴 𝘰𝘯 𝘨𝘪𝘵𝘩𝘶𝘣, 𝘭𝘪𝘯𝘬𝘴 𝘢𝘵 𝘵𝘩𝘦 𝘦𝘯𝘥.</p>
<p>📈 𝗪𝗼𝗿𝗸𝗳𝗹𝗼𝘄:</p>
<p>• It works by creating an ECDSA encryption 🔑🗝key pair, returns you the 🔑public key, to distribute.</p>
<p>• To encrypt, one will have to send your 🔑key along with ✉text and 🖼image.</p>
<p>• The bot will encrypt the text and hide it then it will return the 🖼 encode-image.</p>
<p>• You as a recipient will send the encoded-image to the bot. and it will take your 🗝private key from the 📒database and will send you the hidden ✉text.</p>
<p>PS: Icon is not just eye-candy for otakus. try "/icon" command, within the bot. I bet you will love it. 😉</p>
<p>⚡𝗟𝗶𝗻𝗸𝘀:
Github: https://github.com/ra101/MasquerBot
LBRY: https://lbry.tv/@ra101/MasquerBot</p>
]]></content:encoded></item><item><title><![CDATA[Solve: There is no Brightness button on my new keyboard ヽ(°〇°)ﾉ]]></title><description><![CDATA[As the title says, I bought a new keyboard for my laptop, unfamiliar with world of keyboards, I went with the safest option, approved by many, the Logitech G213 Prodigy. 
Much to my suprise, I was not able to control brightness with this new keyboard...]]></description><link>https://blog.ra101.dev/solve-there-is-no-brightness-button-on-my-new-keyboard</link><guid isPermaLink="true">https://blog.ra101.dev/solve-there-is-no-brightness-button-on-my-new-keyboard</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Sun, 06 Jun 2021 11:43:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636289054681/6ZH54H6cw.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As the title says, I bought a new keyboard for my laptop, unfamiliar with world of keyboards, I went with the safest option, approved by many, the Logitech G213 Prodigy. </p>
<p>Much to my suprise, I was not able to control brightness with this new keyboard.</p>
<ul>
<li>No function keys were mapped to brightness settings</li>
<li>There was no specific keys for that</li>
<li>Even G Hub software had no System Action for brightness</li>
</ul>
<p>So, the dev inside me said, lets tackle it with software!
<br />
By the help of stack-overflow and powershell docs, I wrote a simple powershell script, to adjust my brightness...
{% gist https://gist.github.com/ra101/c2060ade52280b4fcbe3291331caf1e0 %}</p>
<pre><code class="lang-powershell">.\brightness.ps1 &lt;# No agrs will increase brightness (+10) #&gt;
</code></pre>
<pre><code class="lang-powershell">.\brightness.ps1 desc &lt;# desc as arg will decrease brightness (-10) #&gt;
</code></pre>
<p><br />
Now I compiled this file to <code>.exe</code>, to replicate that,</p>
<ul>
<li><p>First Install ps2exe module in powershell (as admin)</p>
<pre><code class="lang-powershell">Install-Module ps2exe
</code></pre>
</li>
<li><p>Simply use this module to convert ps1 to exe</p>
<pre><code><span class="hljs-selector-tag">Invoke-ps2exe</span> .\<span class="hljs-selector-tag">brightness</span><span class="hljs-selector-class">.ps1</span> .\<span class="hljs-selector-tag">brightness</span><span class="hljs-selector-class">.exe</span> <span class="hljs-selector-tag">-noConsole</span>
</code></pre></li>
</ul>
<p><br />
First I thought of using AutoHotKey, but i couldn't utilise any function key there. So, settled with G-Hub instead</p>
<p>Now, head over to G-Hub add this file as application, <strong>twice</strong> , one for +10 and other for -10, remember to add <code>desc</code> there and then change whatever Function keys you want map to brightness.</p>
<p>FYI: I used F6 key to change to G-shift mode. and F7 to increase brightness and F8 to decrease brightness in G-shift mode. No updation made in default mode.</p>
<p><br />
Please comment, for any suggestion regarding this keyboard, or any wonderful hack you have in mind.</p>
]]></content:encoded></item><item><title><![CDATA[New Bash Alias: Git Out]]></title><description><![CDATA[Up until now, we only had git commit and git push. But what about git out? If you know what it feels like to be left out, you should empathize with this command. Even though it is a part of this legendary trio, it is never actually used.
But not toda...]]></description><link>https://blog.ra101.dev/new-bash-alias-git-out</link><guid isPermaLink="true">https://blog.ra101.dev/new-bash-alias-git-out</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Tue, 20 Apr 2021 16:59:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636289060415/v4rWENuNt.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Up until now, we only had <code>git commit</code> and <code>git push</code>. But what about <code>git out</code>? If you know what it feels like to be left out, you should empathize with this command. Even though it is a part of this legendary trio, it is never actually used.</p>
<p>But not today, Not anymore!
Let's right the wrongs of this society!
So, if you are with me!</p>
<p>Open Your <code>.bashrc</code> File!</p>
<pre><code class="lang-Bash">nano ~/.bashrc
</code></pre>
<p><br /></p>
<p>Add This Line! &amp; Save it! (ctrl+x, y, return)</p>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">git</span></span>() { <span class="hljs-keyword">if</span> [[ <span class="hljs-variable">$@</span> == <span class="hljs-string">"out"</span> ]]; <span class="hljs-keyword">then</span> <span class="hljs-built_in">command</span> <span class="hljs-string">"exit"</span>; <span class="hljs-keyword">else</span> <span class="hljs-built_in">command</span> git <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>; <span class="hljs-keyword">fi</span>; }
</code></pre>
<p><br /></p>
<p>And Finally! Source it!</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> ~/.bashrc
</code></pre>
<p>Good job! Be Proud! Because of you, there is one less lonely command!</p>
<p>PS: Feel free to share any meme command out there.</p>
]]></content:encoded></item><item><title><![CDATA[How to Write a C++ Library]]></title><description><![CDATA[Prerequisite: One must be familiar with coding in C++. 
I coded my first C++ libraries 5 years back, I had just started college, and wanted to do something solid!, One fine evening, I was looking back at that code, It was so, poorly written, So I sta...]]></description><link>https://blog.ra101.dev/write-library-cpp</link><guid isPermaLink="true">https://blog.ra101.dev/write-library-cpp</guid><category><![CDATA[C++]]></category><category><![CDATA[C]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[library]]></category><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Mon, 22 Feb 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Y_LgXwQEx2c/upload/39b4a85cc66d179be095468fb5675474.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Prerequisite: One must be familiar with coding in <code>C++</code>. </p>
<p>I coded my first <code>C++</code> libraries 5 years back, I had just started college, and wanted to do something solid!, One fine evening, I was looking back at that code, It was so, poorly written, So I started fixing it. I googled <code>C++</code> Convention, After many search results, I found out there are no good resources out there. So I took upon myself, To Write One!</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Library</td><td>Article</td><td>Repo</td></tr>
</thead>
<tbody>
<tr>
<td>Random Prime No. Genrator</td><td><a target="_blank" href="https://ra101.hashnode.dev/random-prime-generator">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp/">GitHub</a></td></tr>
<tr>
<td>RSA Cryptography</td><td><a target="_blank" href="https://ra101.hashnode.dev/rsa-cpp">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/RSA-cpp/">GitHub</a></td></tr>
<tr>
<td>BlockChain</td><td><a target="_blank" href="https://ra101.hashnode.dev/blockchain-cpp">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/Generic-BlockChain-container-cpp/">GitHub</a></td></tr>
</tbody>
</table>
</div><p>These are coding practices one may follow to write readable good code.</p>
<h3 id="heading-file-types">File Types:</h3>
<p>Any programing file, in the end, is nothing but a text file with a fancy extension. In the Book of Genesis, the mentioned naming style is:</p>
<ul>
<li><code>.c</code> for <code>C</code></li>
<li><code>.cpp</code> for <code>C++</code></li>
<li><code>.h</code> for headers (independent of <code>C</code> or <code>C++</code>)</li>
</ul>
<p>But due to the opensource nature of GNU, A bunch of different assembler and compilers were made which came with their own extensions variations, such as, <code>.cc</code>, <code>.C</code>, <code>.cxx</code>, <code>.c++</code> and <code>.hh</code>, <code>.H</code>, <code>.hxx</code>, <code>.hpp</code>, <code>.h++</code>.</p>
<p>TBH, Just chose one set of extensions, after all, even <code>.txt</code> can be compiled.</p>
<p>I use, (Since Most IDE recognize them):</p>
<ul>
<li><code>.c</code> for <code>C</code></li>
<li><code>.cpp</code> for <code>C++</code></li>
<li><code>.h</code> for <code>C</code> headers</li>
<li><code>.hpp</code> for <code>C++</code> headers</li>
</ul>
<h3 id="heading-makefile"><code>makefile</code>:</h3>
<p>A <code>makefile</code> is a special file, containing shell commands, that you create and name <code>makefile</code> (no extensions)</p>
<p>It is executed using the <code>make</code> command. My Typical makefile looks like this: </p>
<pre><code class="lang-bash"><span class="hljs-comment"># Variables</span>
CXX=g++
CXXFLAGS=-std=c++11 -w

<span class="hljs-comment"># &lt;command&gt; : &lt;dependencies&gt;</span>

<span class="hljs-comment"># would have worked with main.cpp as well, added rest of</span>
<span class="hljs-comment"># dependencies to add a check before compiler returns an error.</span>
build: main.cpp local_header.hpp includes/external_lib.hpp 
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\nmain.cpp: Building..."</span>
    $(CXX) $(CXXFLAGS) -o main.out main.cpp

run: main.out
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\nmain.cpp: Executing..."</span>
    ./main.out

clean: main.out
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\nmain.cpp: Cleaning..."</span>
    rm main.out

<span class="hljs-comment"># test command is for show, I have probably never used it 😅😂 </span>
<span class="hljs-built_in">test</span>: test.cpp
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\ntest.cpp: Building..."</span>
    $(CXX) $(CXXFLAGS) -o test.out test.cpp
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\ntest.cpp: Executing..."</span>
    ./test.out
    @<span class="hljs-built_in">echo</span> <span class="hljs-string">"\n\ntest.cpp: Cleaning..."</span>
    rm ./test.out

all: build run clean
</code></pre>
<pre><code class="lang-bash">$ <span class="hljs-comment"># To build, run and clean the main.cpp</span>
$ make all
</code></pre>
<p>One can use something like <a target="_blank" href="https://www.gnu.org/software/automake/">GNU Automake</a> or <a target="_blank" href="https://cmake.org/">CMake</a> instead of hand-written makefiles. These tools may add the overhead of other files, but these files are informative files. Use these tools, if they benefit your project.</p>
<p>NOTE: use <code>-MMD</code> flag to get a <code>.d</code> file, containing all dependencies.</p>
<h3 id="heading-preprocessors">PreProcessors:</h3>
<p>The preprocessors are the directives, which instruct the compiler to preprocess the information before starting compilation. All preprocessors start with <code>#</code>, For example: <code>#include&lt;iosteam&gt;</code></p>
<p>These are the coding practices, I use:</p>
<ul>
<li><p>Double Quotes (<code>"..."</code>) for including local headers, This rule increases readability of Code</p>
</li>
<li><p>3 Levels of includes (I picked this habit while working in python) with linespace between them.</p>
<ul>
<li>First, for core <code>g++</code> system files.</li>
<li>Second, for externally added libraries.</li>
<li>Third, for locally created files.</li>
</ul>
</li>
</ul>
<p>As mentioned <a target="_blank" href="https://stackoverflow.com/questions/2762568/c-c-include-header-file-order">here</a> one should include local headers first — <em>then</em> system headers. The reason is to guarantee that all local headers are self-sufficient</p>
<p>"self-sufficient" means, local headers are not depending on System or External libraries.
This although is a good way of checking, I believe this "check" is not something headers/compilers should do, well at least not at the file level.
In an ideal world, Each header would have its own test files to resolve this, until then, going against the natural order might not be that bad.</p>
<ul>
<li><p><code>#pragma one</code> for <strong>header files</strong></p>
<ul>
<li>What <code>#include</code> does is that it adds the mentioned file at the top of the code (you can check it by using <code>--save-temp</code> flag during compiling) So, If a header file is called again somewhere else, The Whole Code will be compiled again. Since Header files don't typically initiate a variable. It is Advised to compile it once for performance enhancement.</li>
<li>One can use <code>#indef ... #include ... #endif</code>, but it is tedious, so<code>#pragma once</code> reduces possibilities for bugs due to manual mishandling.</li>
</ul>
</li>
<li><p>DO NOT USE <code>using namespace ...</code> in <strong>header file</strong></p>
<ul>
<li>It may lead to a re-declaration error.</li>
<li>It may populate the header file with its function</li>
</ul>
</li>
</ul>
<p>SO, According to the above rules, A good <strong>header</strong> would be.</p>
<pre><code class="lang-C++"><span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once <span class="hljs-comment">// 2 line-space afterwards</span></span>


<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;system_file_1&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;system_file_2&gt; // 1 line-space afterwards</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;external_lib1_1&gt; // 1 line-space afterwards</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;external_lib2_2&gt; // club external libs together</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;external_lib2_3&gt; // 1 line-space afterwards</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"local_file"</span> <span class="hljs-comment">// 2 line-space afterwards</span></span>


<span class="hljs-comment">// using namespace ... DO NOT USE IN HEADERS</span>

<span class="hljs-keyword">namespace</span> ra {
...
}
</code></pre>
<h3 id="heading-nomenclature">Nomenclature:</h3>
<h4 id="heading-file-or-namespace-or-class-or-function">File | <code>namespace</code> | <code>Class</code> | <code>function</code>:</h4>
<ul>
<li>Nothing is fixed, one may use <code>camelCase</code>, <code>PascalCase</code> or
<code>snake_case</code>.</li>
<li>I personally find <code>snake_case</code> to be more readable.</li>
</ul>
<h4 id="heading-template-parameter"><code>Template</code> Parameter:</h4>
<ul>
<li>same as above, no rules.</li>
<li>I prefer <code>PascalCase</code> here.</li>
</ul>
<h4 id="heading-constants-or-macros">Constants | Macros:</h4>
<ul>
<li><code>UPPER_SNAKE_CASE</code> is preferred everywhere.</li>
</ul>
<h4 id="heading-variables">Variables:</h4>
<ul>
<li>Before IDE(s) were a thing, People just couldn't hover over variables to get info. So some old libraries use the following conventions:<ul>
<li><code>m_&lt;any case&gt;</code> for private members</li>
<li><code>t_&lt;any case&gt;</code> for function parameters</li>
</ul>
</li>
<li>I personally, discard this rule.</li>
</ul>
<h4 id="heading-taboo-of-naming">Taboo of Naming:</h4>
<p>Check this <a target="_blank" href="https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier">link</a></p>
<h3 id="heading-comments">Comments:</h3>
<p>C++ allows for 2 types of comments:</p>
<pre><code class="lang-C++"><span class="hljs-comment">// This is single line Comment</span>
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">/*
...
This is Multi-Line Comment
...
*/</span>
</code></pre>
<p>Generally speaking, single-line comments provide more control over the appearance and are <em>considered</em> better.</p>
<p>As a python developer, I wholeheartedly disagree, This is how I prefer my code!</p>
<pre><code class="lang-C++">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">custom_class</span> {</span>
    <span class="hljs-comment">/*
        A definition of what does this class represent
        - Preferred Usage:
            ...
    */</span>
    <span class="hljs-keyword">private</span>:
        <span class="hljs-comment">// How this variable affects / Where this may be used</span>
        <span class="hljs-keyword">float</span> variable {<span class="hljs-number">3.14</span>};

        <span class="hljs-comment">// What does this function do</span>
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">function</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">custom_class::function</span><span class="hljs-params">()</span></span>{
    <span class="hljs-comment">/*
        A definition of what does this function do
        - Input: ...
        - Output: ...
    */</span>
}
</code></pre>
<h3 id="heading-custom-exceptions">Custom Exceptions:</h3>
<p>Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard programming language. These are most helpful in Debugging when code is unable to compile.</p>
<p>Below is My Favorite Exception:</p>
<pre><code class="lang-C++"><span class="hljs-comment">// Code</span>

<span class="hljs-keyword">namespace</span> ra
{
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">external_exception</span> :</span> <span class="hljs-keyword">public</span> <span class="hljs-built_in">std</span>::logic_error
    {
    <span class="hljs-keyword">public</span>:
        external_exception(
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> function = __builtin_FUNCTION()
        ) : <span class="hljs-built_in">std</span>::logic_error(<span class="hljs-string">"`"</span> + function + <span class="hljs-string">"` called for external exception!"</span>){};
    };
}
</code></pre>
<pre><code class="lang-C++"><span class="hljs-comment">// Usage</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">main</span> <span class="hljs-params">()</span></span>{ <span class="hljs-keyword">throw</span> ra::external_exception(); }
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># Output</span>

terminate called after throwing an instance of <span class="hljs-string">'ra::external_exception'</span>
  what():  `main` called <span class="hljs-keyword">for</span> external exception!
</code></pre>
<p>Let me explain, In argument of constructor of exception it says:</p>
<pre><code class="lang-C++"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> function = __builtin_FUNCTION()
</code></pre>
<p><code>__builtin_FUNCTION()</code> return the source location, when called.</p>
<p>Since called in Argument, whenever it is initiated that is the source location, Essentially Making it a traceable Exception</p>
<p>Here We have inherited from <code>logic_error</code>, but other exceptions/errors could be found <a target="_blank" href="https://en.cppreference.com/w/cpp/header/stdexcept">here</a></p>
<p>NOTE: In C++ Exceptions and Errors are the same, but in theory, Exceptions are something that could be handled, whereas errors should not be as they break the system.</p>
<h3 id="heading-modularity">Modularity</h3>
<p>A Modular design is shown to improve the design process by allowing better re-usability, relatively low maintenance, workload handling, and easier debugging processes. Modularity in <code>C++</code> can be achieved by the following </p>
<h4 id="heading-template">Template</h4>
<p>As defined (here)[https://www.javatpoint.com/cpp-templates]:  A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types</p>
<p>Templates can be represented in two ways:</p>
<ul>
<li><a target="_blank" href="https://en.cppreference.com/w/cpp/language/function_template">Function templates</a></li>
</ul>
<pre><code class="lang-C++"><span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> TemplateKlass&gt;
<span class="hljs-function">TemplateKlass <span class="hljs-title">get_maximum</span><span class="hljs-params">(TemplateKlass x, TemplateKlass y)</span></span>{
   <span class="hljs-keyword">return</span> (x &gt; y)? x: y;
}
</code></pre>
<ul>
<li><a target="_blank" href="https://en.cppreference.com/w/cpp/language/templates">Class templates</a><pre><code class="lang-C++"><span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> TemplateKlass&gt;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">custom_class</span> {</span>
<span class="hljs-keyword">private</span>:
 TemplateKlass x, y;
<span class="hljs-keyword">public</span>:
 custom_class(TemplateKlass, TemplateKlass);
};
</code></pre>
</li>
</ul>
<p>I am will not into details, As there are far better resources</p>
<h4 id="heading-function-as-argument">Function as Argument:</h4>
<p>We can pass a function in the argument of another function, Well Actually A function pointer is passed to be exact. This comes in handy in the situation, where you have multiple services for the same request, for example, <strong>Hashing</strong>, you can use so many third-party algorithms for hashing.</p>
<pre><code class="lang-C++"><span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">verify_hash</span><span class="hljs-params">(<span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> (*hash_func)(<span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span>))</span></span>{
    <span class="hljs-comment">/*
        This will take in any function with
        input and output as a string 
    */</span>
    <span class="hljs-keyword">return</span> hashed_output == hash_func(input)
}
</code></pre>
<h4 id="heading-inheritance">Inheritance</h4>
<p>I picked up this in my <code>Unity3D</code> days, In <code>Unity3D</code> Almost everything is inherited and then used.</p>
<p>The plan is simple, Create a class with a bunch of public members all throwing error.</p>
<p>And Then Everyone would have to Inherit that class and override it.</p>
<p>For Example</p>
<pre><code class="lang-C++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">base_class</span>{</span>
    <span class="hljs-comment">/*
        Everyone will inherit from this class
    */</span>
<span class="hljs-keyword">public</span>:
    base_class(){}
    base_class(<span class="hljs-keyword">float</span>) {<span class="hljs-keyword">throw</span> not_implemented_exception();}

    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">operator</span> <span class="hljs-title">string</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span> </span>= <span class="hljs-number">0</span>;

    <span class="hljs-keyword">bool</span> <span class="hljs-keyword">operator</span>&lt;(<span class="hljs-keyword">const</span> base_class &amp;other) <span class="hljs-keyword">const</span> { <span class="hljs-keyword">throw</span> not_implemented_exception(); }

    <span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> TemplateKlass&gt;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">some_func</span><span class="hljs-params">(TemplateKlass temp)</span> </span>{<span class="hljs-keyword">throw</span> not_implemented_exception();}
}
</code></pre>
<pre><code class="lang-C++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">extended_class</span> :</span> <span class="hljs-keyword">public</span> base_class{
    <span class="hljs-comment">/*
        This is how Inheritance would work
    */</span>
<span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">float</span> m_temp;
<span class="hljs-keyword">public</span>:
    extended_class(){}
    extended_class(<span class="hljs-keyword">float</span> t_temp) : m_temp(t_temp)

    <span class="hljs-function"><span class="hljs-keyword">operator</span> <span class="hljs-title">std::string</span><span class="hljs-params">()</span> </span>{<span class="hljs-keyword">return</span> to_string(t_temp);}

    <span class="hljs-keyword">bool</span> <span class="hljs-keyword">operator</span>&lt;(<span class="hljs-keyword">const</span> extended_class &amp;other) <span class="hljs-keyword">const</span> { m_temp &lt; other.m_temp }

    <span class="hljs-keyword">template</span> &lt;<span class="hljs-keyword">typename</span> TemplateKlass&gt;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">some_func</span><span class="hljs-params">(TemplateKlass temp)</span> </span>{...}
}
</code></pre>
<h3 id="heading-bonus-icon-pack">Bonus: Icon Pack!</h3>
<p>Yeah... I created my own icons too...</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>GNU Extension</td><td>Preview</td><td>Download</td></tr>
</thead>
<tbody>
<tr>
<td>.c</td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/c.png">c.png</a></td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/c.ico">c.ico</a></td></tr>
<tr>
<td>.cpp</td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/cpp.png">cpp.png</a></td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/cpp.ico">cpp.ico</a></td></tr>
<tr>
<td>.cs</td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/cs.png">cs.png</a></td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/cs.ico">cs.ico</a></td></tr>
<tr>
<td>.h / .hpp</td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/h.png">h.png</a></td><td><a target="_blank" href="https://ra101.github.io/namespace-ra/assets/h.ico">h.ico</a></td></tr>
</tbody>
</table>
</div><hr />
<div class="hn-table">
<table>
<thead>
<tr>
<td>Library</td><td>Article</td><td>Repo</td></tr>
</thead>
<tbody>
<tr>
<td>Random Prime No. Genrator</td><td><a target="_blank" href="https://ra101.hashnode.dev/random-prime-generator">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp/">GitHub</a></td></tr>
<tr>
<td>RSA Cryptography</td><td><a target="_blank" href="https://ra101.hashnode.dev/rsa-cpp">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/RSA-cpp/">GitHub</a></td></tr>
<tr>
<td>BlockChain</td><td><a target="_blank" href="https://ra101.hashnode.dev/blockchain-cpp">HashNode</a></td><td><a target="_blank" href="https://github.com/ra101/Generic-BlockChain-container-cpp/">GitHub</a></td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[Quine(s) in JavaScript]]></title><description><![CDATA[Quine) is a program that takes no input but outputs a copy of its own code. Unlike other languages writing a quine in JavaScript/NodeJS is quite easy.


Here we go!
function quine() { console.log(quine.toString()) }

The key here is that any function...]]></description><link>https://blog.ra101.dev/quines-in-javascript-1</link><guid isPermaLink="true">https://blog.ra101.dev/quines-in-javascript-1</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Fri, 12 Feb 2021 19:51:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636289067430/s3htDtVNG.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://en.wikipedia.org/wiki/Quine_(computing">Quine</a>) is a program that takes no input but outputs a copy of its own code. Unlike other languages writing a quine in JavaScript/NodeJS is quite easy.</p>
<p><br />
<br /></p>
<p><strong>Here we go!</strong></p>
<pre><code class="lang-Javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">quine</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(quine.toString()) }
</code></pre>
<p>The key here is that any function in JavaScript can be converted into a string and can be printed. Also, <code>console.log</code> is not the only option, <code>alert</code> can be used too. Although it will not work in a node terminal.</p>
<p><strong>Above is a function that prints its source code but it is not a file that can be executed.</strong> So let's add a Call statement,</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">quine</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(quine.toString()+<span class="hljs-string">" quine();"</span>) } quine();
</code></pre>
<p>Note that we needed to add something extra in the log statement to achieve our goal. And <code>;</code> was probably not needed.</p>
<p><br /></p>
<p>Let's make it a little elegant, We know that JavaScript can make a function run as soon as it is defined, By using an IIFE (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">Immediately Invoked Function Expression</a>).</p>
<pre><code class="lang-javascript">( <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">quine</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"( "</span> + quine.toString() + <span class="hljs-string">" )()"</span>) } )()
</code></pre>
<p>Note that we manipulated the log statement as required.</p>
<p>For some more Quines in NodeJS: https://catonmat.net/quine-in-node</p>
<p><br /></p>
<p><strong>Now let's take <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow-Operator</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting">Format-Strings</a> into this equation and It becomes almost eye-blindingly beautiful!</strong></p>
<pre><code class="lang-Javascript">($=<span class="hljs-function"><span class="hljs-params">_</span>=&gt;</span><span class="hljs-string">`($=<span class="hljs-subst">${$}</span>)()`</span>)()
</code></pre>
<p>To Understand let's remove IIFE and extra parentheses in the format-string. And also, add some spacing.</p>
<pre><code class="lang-Javascript">$    =    <span class="hljs-function"><span class="hljs-params">_</span>    =&gt;</span>    <span class="hljs-string">`$=<span class="hljs-subst">${$}</span>`</span>
</code></pre>
<p>So, the first <code>$</code> is a variable that contains an arrow function.
<code>_</code> is a random parameter for the arrow function which remains unused.
After the arrow, this is our format-string which can be divided into 2 parts, the String, "$=", and the Variable which is first <code>$</code> itself. </p>
<p><br /></p>
<p><strong>Lastly, A Quine needs to be executable but it doesn't mean that programs resulting in errors can't be a Quine. Here is an example</strong></p>
<pre><code class="lang-Javascript"><span class="hljs-keyword">throw</span> <span class="hljs-number">0</span>
^
<span class="hljs-number">0</span>
</code></pre>
<p>Link: https://github.com/nmrugg/quine</p>
<p>This program when executed as a .js file with the help of NodeJS outputs its own source code. </p>
<p>How this works is, NodeJS returns an error at the first line, the rest of the code is how the error looks like.</p>
<p>If you make your own JS Quine or you want to share Quine in other programming languages, then please do write in the comment section.</p>
]]></content:encoded></item><item><title><![CDATA[Half-Day Builds!]]></title><description><![CDATA[Hi 🖐,
This post is about the half-day builds! These projects will never be featured anywhere, So why not create a combined thread for them.
Draw Graphs in C++
I was looking for a graphics.h project, One day my friend asked me "Did you ever come acro...]]></description><link>https://blog.ra101.dev/half-day-builds</link><guid isPermaLink="true">https://blog.ra101.dev/half-day-builds</guid><dc:creator><![CDATA[Parth Agarwal]]></dc:creator><pubDate>Tue, 27 Oct 2020 07:41:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/vpOeXr5wmR4/upload/b230b523b2514e1ecc4a2f4eb3d37015.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi 🖐,
This post is about the half-day builds! These projects will never be featured anywhere, So why not create a combined thread for them.</p>
<p><br /><strong>Draw Graphs in C++</strong>
I was looking for a graphics.h project, One day my friend asked me "Did you ever come across any code which Draws the given input graph?", I replied... wait-for-it!
Link: https://github.com/ra101/graphical-representation-of-graphs-in-cpp</p>
<p><br /><strong>Pinger</strong> (Python)
One of my deployed college project got shut down. This Script executes at startup, starts a headless browser, and open the various sites declared within. All in the background.
Link:https://github.com/ra101/pinger</p>
<p><br /><strong>lbry VLC Extension</strong> (Lua)
I was looking for a dark theme for VLC and I found out that people can create extensions that can be attached to the final build binary! This extension enables us to network streams free lbry.tv videos.
Link: https://github.com/ra101/lbry.tv-VLC-Playlist-Parser</p>
<p><br /><strong>Text to Morse Code</strong> (Dart)
A Flutter Trial App, It changes Text to Morse Code and then allows to vibrate the phone or to flicker torch accordingly.
Link: https://github.com/ra101/txt_mrs_vib</p>
<p><br /><strong>DuckDuckGo Chrome-Ext</strong> (JavaScript)
A Chrome-Extension that adds a button to open the current search with DuckDuckGo. You can also attach a Key-Binding to use it.
Link: https://github.com/ra101/DuckDuckGo-Chrome-Ext</p>
]]></content:encoded></item></channel></rss>