<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>bla bla weblog</title>
    <link>https://ayushsingh.dev/blog</link>
    <description>Writing by Ayush Kumar Singh on data platforms, infrastructure, and whatever else is on my mind.</description>
    <language>en</language>
    <lastBuildDate>Wed, 19 Nov 2025 00:00:00 GMT</lastBuildDate>
    <atom:link href="https://ayushsingh.dev/feed.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Find lost data in Git</title>
      <link>https://ayushsingh.dev/blog/find-lost-data-in-git</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/find-lost-data-in-git</guid>
      <pubDate>Wed, 19 Nov 2025 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>A script to find lost Git commits, stashes, or other changes</description>
      <content:encoded><![CDATA[<p>This script helped me find lost stashes that contained a lot of important changes, so I wanted to share it here for others who might find themselves in a similar situation.</p>
<p><strong>Important</strong>: Git&#39;s garbage collection eventually deletes unreachable commits (typically after 30 days), so run this script as soon as you realize something is missing.</p>
<pre><code class="language-bash">#!/bin/bash
#
# git-find-lost-code.sh
# A script to find lost Git commits, stashes, or other changes.
#
# This script searches for &quot;lost&quot; commits in two places:
# 1. Unreachable commits: Commits that are no longer referenced by any branch,
#    tag, or stash. This is where dropped stashes and hard-resets end up.
# 2. The Reflog: A log of all recent movements of HEAD, which acts as a
#    powerful safety net.
#
# USAGE:
#   chmod +x git-find-lost-code.sh
#   ./git-find-lost-code.sh [optional/path/to/file]
#
# If you provide a file path, the script will only show commits that modified
# that specific file. If you don&#39;t, it will show ALL lost commits it can find.
# Note: Without a file path, the reflog search may output many commits.

set -e

FILE_PATH=&quot;$1&quot;

# --- Method 1: Search Dangling (Unreachable) Commits ---
echo &quot;---&quot;
echo &quot;🔎 Searching for dangling (unreachable) commits...&quot;
echo &quot;---&quot;
UNREACHABLE_COMMITS=$(git fsck --unreachable | grep commit | cut -d&#39; &#39; -f3)

if [ -z &quot;$UNREACHABLE_COMMITS&quot; ]; then
    echo &quot;No dangling commits found.&quot;
else
    FOUND_IN_FSCK=0
    for commit in $UNREACHABLE_COMMITS; do
        if [ -n &quot;$FILE_PATH&quot; ]; then
            # If a file path is provided, check if the commit modified it
            if git show --name-only --pretty=&quot;&quot; &quot;$commit&quot; 2&gt;/dev/null | grep -q &quot;^${FILE_PATH}$&quot;; then
                echo &quot;✅ Found dangling commit [$commit] that modified &#39;$FILE_PATH&#39;:&quot;
                git log -n 1 --oneline --stat &quot;$commit&quot;
                echo &quot;------------------------------------------------&quot;
                FOUND_IN_FSCK=1
            fi
        else
            # If no file path, just show all dangling commits
            echo &quot;✅ Found dangling commit [$commit]:&quot;
            git log -n 1 --oneline --stat &quot;$commit&quot;
            echo &quot;------------------------------------------------&quot;
            FOUND_IN_FSCK=1
        fi
    done
    if [ &quot;$FOUND_IN_FSCK&quot; -eq 0 ]; then
        echo &quot;No dangling commits found that modified &#39;$FILE_PATH&#39;.&quot;
    fi
fi


# --- Method 2: Search The Reflog ---
echo &quot;&quot;
echo &quot;---&quot;
echo &quot;🔎 Searching reflog...&quot;
echo &quot;---&quot;
REFLOG_COMMITS=$(git reflog | awk &#39;{print $1}&#39;)

FOUND_IN_REFLOG=0
for commit in $REFLOG_COMMITS; do
    if [ -n &quot;$FILE_PATH&quot; ]; then
        # If a file path is provided, check if the commit modified it
        if git show --name-only --pretty=&quot;&quot; &quot;$commit&quot; 2&gt;/dev/null | grep -q &quot;^${FILE_PATH}$&quot;; then
            echo &quot;✅ Found reflog commit [$commit] that modified &#39;$FILE_PATH&#39;:&quot;
            git log -n 1 --oneline --stat &quot;$commit&quot;
            echo &quot;------------------------------------------------&quot;
            FOUND_IN_REFLOG=1
        fi
    else
        # If no file path, just show all reflog commits
        echo &quot;✅ Found reflog commit [$commit]:&quot;
        git log -n 1 --oneline --stat &quot;$commit&quot;
        echo &quot;------------------------------------------------&quot;
        FOUND_IN_REFLOG=1
    fi
done

if [ &quot;$FOUND_IN_REFLOG&quot; -eq 0 ]; then
    echo &quot;No commits found in reflog that modified &#39;$FILE_PATH&#39;.&quot;
fi

echo &quot;&quot;
echo &quot;✨ Search complete.&quot;
echo &quot;&quot;
echo &quot;💡 To recover a commit you found:&quot;
echo &quot;   - Cherry-pick it: git cherry-pick &lt;commit-hash&gt;&quot;
echo &quot;   - Create a branch: git checkout -b recovery-branch &lt;commit-hash&gt;&quot;
echo &quot;   - View the changes: git show &lt;commit-hash&gt;&quot;
</code></pre>
<h2>How to use</h2>
<ol>
<li>Save the script to a file (e.g., <code>git-find-lost-code.sh</code>)</li>
<li>Make it executable: <code>chmod +x git-find-lost-code.sh</code></li>
<li>Run it in your Git repository:<ul>
<li>Find all lost commits: <code>./git-find-lost-code.sh</code></li>
<li>Find commits that modified a specific file: <code>./git-find-lost-code.sh path/to/file.txt</code></li>
</ul>
</li>
</ol>
<h2>Recovering your data</h2>
<p>Once you&#39;ve found the commit you&#39;re looking for, you can recover it using:</p>
<ul>
<li><strong>Cherry-pick the changes</strong>: <code>git cherry-pick &lt;commit-hash&gt;</code></li>
<li><strong>Create a new branch from it</strong>: <code>git checkout -b recovery-branch &lt;commit-hash&gt;</code></li>
<li><strong>View the full changes</strong>: <code>git show &lt;commit-hash&gt;</code></li>
<li><strong>Apply as a patch</strong>: <code>git show &lt;commit-hash&gt; | git apply</code></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Kube Bin Packing</title>
      <link>https://ayushsingh.dev/blog/kube-bin-packing</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/kube-bin-packing</guid>
      <pubDate>Sun, 29 Jun 2025 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Script I used to get size of all pods in a Kubernetes cluster.</description>
      <content:encoded><![CDATA[<p>I used the following script to get the sizes of all the pods in the kube cluster. It calculates the total CPU and memory requests for each pod and outputs them in TSV.</p>
<pre><code class="language-bash">#!/usr/bin/env bash

# Function to parse CPU request (in millicores)
parse_cpu() {
  local cpu_str=&quot;$1&quot;
  if [[ &quot;$cpu_str&quot; == *&quot;m&quot;* ]]; then
    # Remove &quot;m&quot; and convert to integer
    echo &quot;$(echo &quot;$cpu_str&quot; | sed &#39;s/m//&#39; | awk &#39;{print int($1)}&#39;)&quot;
  else
    # Convert to millicores (e.g., &quot;2&quot; -&gt; 2000, &quot;0.5&quot; -&gt; 500)
    echo &quot;$(echo &quot;$cpu_str&quot; | awk &#39;{print int($1 * 1000)}&#39;)&quot;
  fi
}

# Function to parse memory request (in Mi)
parse_memory() {
  local mem_str=&quot;$1&quot;
  if [[ &quot;$mem_str&quot; == *&quot;Mi&quot;* ]]; then
    echo &quot;$(echo &quot;$mem_str&quot; | sed &#39;s/Mi//&#39; | awk &#39;{print int($1)}&#39;)&quot;
  elif [[ &quot;$mem_str&quot; == *&quot;Gi&quot;* ]]; then
    echo &quot;$(echo &quot;$mem_str&quot; | sed &#39;s/Gi//&#39; | awk &#39;{print int($1 * 1024)}&#39;)&quot;
  elif [[ &quot;$mem_str&quot; == *&quot;Ki&quot;* ]]; then
    echo &quot;$(echo &quot;$mem_str&quot; | sed &#39;s/Ki//&#39; | awk &#39;{print int($1 / 1024)}&#39;)&quot;
  else
    # Assume Mi if no suffix
    echo &quot;$(echo &quot;$mem_str&quot; | awk &#39;{print int($1)}&#39;)&quot;
  fi
}


echo &quot;=== Node Allocatable Resources ===&quot;
kubectl get nodes -o json | jq -r &#39;
  .items[]
      node: .metadata.name,
      cpu_allocatable: .status.allocatable.cpu,
      mem_allocatable: .status.allocatable.memory
    }
&#39;

echo &quot;&quot;
echo &quot;=== Pods and Their Total Requests (CPU in m, Mem in Mi) ===&quot;
kubectl get pods -A -o json |
while IFS= read -r line; do
  # Extract relevant data from the JSON using jq and process it
  local namespace=$(echo &quot;$line&quot; | jq -r &#39;.metadata.namespace&#39;)
  local pod=$(echo &quot;$line&quot; | jq -r &#39;.metadata.name&#39;)
  local node=$(echo &quot;$line&quot; | jq -r &#39;(.spec.nodeName // &quot;-&quot;)&#39;)

  local cpu_request_m=0
  local mem_request_mi=0

  # Calculate CPU and Memory requests
  local containers=$(echo &quot;$line&quot; | jq -c &#39;.spec.containers[]&#39;)
  if [[ -n &quot;$containers&quot; ]]; then
    while IFS= read -r container; do
      local cpu_req_str=$(echo &quot;$container&quot; | jq -r &#39;.resources.requests.cpu // &quot;0&quot;&#39;)
      local mem_req_str=$(echo &quot;$container&quot; | jq -r &#39;.resources.requests.memory // &quot;0&quot;&#39;)
      cpu_request_m=$((cpu_request_m + $(parse_cpu &quot;$cpu_req_str&quot;)))
      mem_request_mi=$((mem_request_mi + $(parse_memory &quot;$mem_req_str&quot;)))
    done &lt;&lt;&lt; &quot;$(echo &quot;$containers&quot; | jq -c &#39;.&#39;)&quot;
  fi


  # Output the results in TSV format
  echo -e &quot;$namespace\t$pod\t$node\t${cpu_request_m}m\t${mem_request_mi}Mi&quot;
done &lt; &lt;(kubectl get pods -A -o json | jq -c &#39;.items[]&#39;)
</code></pre>
<p>Also one of the most useful commands I found was:</p>
<pre><code class="language-bash">eks-node-viewer -resources cpu,memory
</code></pre>
<p>You can install it with:</p>
<pre><code class="language-bash">brew tap aws/tap
brew install eks-node-viewer

# or

go install github.com/awslabs/eks-node-viewer/cmd/eks-node-viewer@latest
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Guessing Age</title>
      <link>https://ayushsingh.dev/blog/guessing-age</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/guessing-age</guid>
      <pubDate>Sat, 05 Apr 2025 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>A humorous take on how we perceive technology and age.</description>
      <content:encoded><![CDATA[<p>I&#39;ve come up with a set of rules that describe our reactions to technologies:</p>
<ol>
<li>Anything that is in the world when you’re born is normal and ordinary and is just a natural part of the way the world works.</li>
<li>Anything that&#39;s invented between when you’re fifteen and thirty-five is new and exciting and revolutionary and you can probably get a career in it.</li>
<li>Anything invented after you&#39;re thirty-five is against the natural order of things.</li>
</ol>
<p>-- Douglas Adams</p>
]]></content:encoded>
    </item>
    <item>
      <title>Embracing AI Prompting</title>
      <link>https://ayushsingh.dev/blog/alteast-learn-prompting</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/alteast-learn-prompting</guid>
      <pubDate>Sun, 12 Jan 2025 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Paradigm Shift in Web Development</description>
      <content:encoded><![CDATA[<blockquote>
<p>This blog was generated using gpt-o1-mini AI. You can find the Jupyter Notebook used for its creation <a href="https://gist.github.com/haloboy777/03afa602b7c3fcc45a7906722ccc50b1">here</a>.</p>
</blockquote>
<p>The world of web development is undergoing a seismic change, and it&#39;s not just about JavaScript frameworks and responsive design anymore. With the advent of artificial intelligence, particularly AI prompting, developers have a chance to elevate their game like never before.</p>
<h2>Why AI Prompting?</h2>
<ol>
<li><p><strong>Enhanced Efficiency</strong>: Imagine cutting down hours spent on coding tasks by simply asking an AI to generate complex code snippets or solve bugs. AI prompting allows you to harness the power of machine learning to streamline your workflow.</p>
</li>
<li><p><strong>Creative Collaboration</strong>: AI can serve as a brainstorming partner, helping you come up with unique ideas and solutions that you might not have considered. It&#39;s like having a co-developer who&#39;s always ready to assist!</p>
</li>
<li><p><strong>Continuous Learning</strong>: As web technologies evolve rapidly, keeping up is crucial. Learning how to effectively use AI prompting not only enhances your skill set but also positions you at the forefront of this paradigm shift.</p>
</li>
<li><p><strong>Empowering Problem Solving</strong>: With AI, you can tackle more complex challenges with ease. Whether it&#39;s optimizing performance or enhancing user experience, AI can provide insights and solutions based on vast data analysis.</p>
</li>
</ol>
<p>Incorporating AI prompting into your toolkit isn&#39;t just an option, it&#39;s becoming a necessity. As web developers, we need to embrace this shift and evolve alongside the technology that is reshaping our industry.</p>
<p>Embracing AI prompting is your next step in staying relevant and innovative as web development evolves.</p>
<p>Stay curious, stay ahead!</p>
]]></content:encoded>
    </item>
    <item>
      <title>India’s Rise</title>
      <link>https://ayushsingh.dev/blog/india-betrayed</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/india-betrayed</guid>
      <pubDate>Fri, 27 Dec 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>A Story of Vision, Betrayal, and a Lost Future</description>
      <content:encoded><![CDATA[<p>India’s journey to global prominence didn’t happen overnight. It began with leaders like Dr. Manmohan Singh, whose 1990s reforms pulled India from the brink of economic collapse and set us on a path to growth. Those policies created the foundation for opportunities and industries that thrive even today.</p>
<p>But progress in a country as vast as ours takes time. By the 2000s, we were seeing results: a booming tech sector, a stronger middle class, and global recognition. These systems weren’t perfect, but they worked because they were built for long-term stability.</p>
<p>Then came 2014, and with it, the BJP. Modi’s government rode in on promises of change, but what they’ve done is disheartening.</p>
<h2>Dismantling the Pillars of Progress</h2>
<p>The BJP didn’t just claim credit for growth they didn’t build; they also started dismantling the institutions that made it possible:</p>
<ul>
<li><strong>Education</strong>: Universities and research centers that fuel innovation. With that changing the textbooks to suit their narrative.</li>
<li><strong>Democracy</strong>: A free press, independent judiciary, and robust checks on power. Now it&#39;s just a puppet show.</li>
<li><strong>Economic systems</strong>: Policies that supported industry and global integration. Now it&#39;s just a mess.</li>
<li><strong>Taxation</strong>: A system that funded development. Now it&#39;s just a burden on the common man.</li>
</ul>
<p>Under BJP rule, these institutions have been weakened. Universities are losing autonomy. The judiciary and press face mounting pressure. The tech industry, which thrived on openness, is being stifled by control-focused policies.</p>
<p>These aren’t just political shifts - <strong>they’re generational losses</strong>.</p>
<h2>The Exodus: Why Many Are Leaving</h2>
<p>The erosion of India’s foundational institutions has led to a climate of uncertainty and disillusionment.</p>
<p>In recent years, the rate at which Indians are leaving the country has reached alarming levels, driven by a combination of dwindling opportunities, social tensions, and governance challenges.</p>
<p>As freedoms are curtailed and aspirations are stifled, many are seeking stability, personal security, and better prospects abroad.</p>
<p>This brain drain not only reflects individual choices but also signifies a collective loss for the nation - a drain of talent, innovation, and potential that India can scarcely afford.</p>
<h2>Why I Hate the BJP</h2>
<p>I hate the BJP because they’re destroying what made modern India possible. The opportunities I had, the systems that supported me, and the stability I relied on are being eroded. What we inherited is slipping away, and future generations will pay the price. My children will grow up in a country that’s less free, less fair, and less prosperous.</p>
<p>This isn’t just bad governance - it’s a betrayal.</p>
<h2>A Tribute to Dr. Manmohan Singh</h2>
<p>The passing of Dr. Manmohan Singh marks the end of an era. His vision transformed India, from lifting millions out of poverty to building the systems that opened doors for people like me. As a leader, he was quiet yet impactful, focusing on progress over propaganda.</p>
<p>India owes much of its rise to his reforms. His legacy reminds us of what leadership rooted in vision and integrity can achieve.</p>
<h2>Looking Ahead</h2>
<p>India’s rise wasn’t inevitable-it was built on strong institutions and patient reform. But these gains are fragile, and they’re being hollowed out for short-term power plays.</p>
<p>As citizens, we need to ask: What kind of country do we want to leave behind? Are we okay with trading long-term stability for short-term applause?</p>
<p>We owe it to future generations to rebuild what’s being lost and to demand leadership that values nation-building over credit-grabbing.</p>
<p><em>In memory of Dr. Manmohan Singh (1932–2024), whose leadership gave India the foundation to dream bigger.</em></p>
]]></content:encoded>
    </item>
    <item>
      <title>Coolify + Nginx = ❤️</title>
      <link>https://ayushsingh.dev/blog/coolify-nginx</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/coolify-nginx</guid>
      <pubDate>Fri, 20 Dec 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Nginx configuration for Coolify</description>
      <content:encoded><![CDATA[<p>I recently deployed <a href="https://coolify.io">Coolify</a> on my server and wanted to share the Nginx configuration I used to make it work.</p>
<p>Here&#39;s the Nginx configuration I used:</p>
<pre><code class="language-nginx">server {
    server_name &lt;HOST_NAME&gt;;

    # ACME Challenge for Certbot
    location ~ &quot;^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)$&quot; {
        default_type text/plain;
        return 200 &quot;$1.&lt;CERTBOT_CHALLENGE&gt;&quot;;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate [CERT_PATH]; # managed by Certbot
    ssl_certificate_key [CERT_PATH]; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security &quot;max-age=7200&quot;;

    # Handle /app/* requests
    location /app/ {
        proxy_pass http://127.0.0.1:6001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection &#39;upgrade&#39;;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-Proto https;
    }

    # Handle /terminal/ws requests
    location /terminal/ws {
        proxy_pass http://127.0.0.1:6002;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection &#39;upgrade&#39;;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-Proto https;
    }

    # Handle all other traffic
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection &#39;upgrade&#39;;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-Proto https;
    }
}

server {
    if ($host = &lt;HOST_NAME&gt;) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name &lt;HOST_NAME&gt;;

    listen 80;
    return 404; # managed by Certbot
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Places I&apos;ve been</title>
      <link>https://ayushsingh.dev/blog/map</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/map</guid>
      <pubDate>Mon, 09 Dec 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>I stayed atleast 1 day there</description>
      <content:encoded><![CDATA[<iframe src="https://www.google.com/maps/d/u/0/embed?mid=1a3t56XotSIZngCmZWiODVtt3IsExDlI&ehbc=2E312F" class="max-w-4xl w-full h-[512]"></iframe>
]]></content:encoded>
    </item>
    <item>
      <title>Fix ScyllaDB startup</title>
      <link>https://ayushsingh.dev/blog/fix-scylladb-startup</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/fix-scylladb-startup</guid>
      <pubDate>Mon, 04 Nov 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>How to fix &quot;Failed to start a Raft group&quot;</description>
      <content:encoded><![CDATA[<p>I&#39;ve been getting the following error when trying to start a ScyllaDB cluster on my local machine:</p>
<pre><code class="language-log">node2  | ERROR 2024-11-03 23:01:03,249 [shard 0:main] init - Startup failed: seastar::internal::backtraced&lt;std::runtime_error&gt; (Failed to start a Raft group 22e5a340-996b-11ef-a7df-a3a43d2a3037: seastar::internal::backtraced&lt;std::runtime_error&gt; (topology[0xe00004c506a0]: node=0xe00004b6f6c0  idx=2 host_id=329b6bdd-3b84-4525-914d-d244cdcec46c endpoint=172.18.0.4 dc=datacenter1 rack=rack1 state=normal shards=1 this_node=false: node endpoint already mapped to node=0xe00004c58240  idx=0 host_id=7e833809-c052-449d-bbc0-b0b51188145f endpoint=172.18.0.4 dc=datacenter1 rack=rack1 state=normal shards=1 this_node=true Backtrace: 0x5325257 0x53257e7 0x4a7d15b 0x4a7ce97 0x517e70b 0x372c547 0x37303fb 0x3733b13 0x36dc667 0x375cbdf 0x390618f 0x38072d3 0x51b6f7b 0x51b8427 0x51b91ff 0x51b889b 0x514f5f3 0x514ead7 0x121b927 0x121cf3f 0x121a3f3 /opt/scylladb/libreloc/libc.so.6+0x30a1b /opt/scylladb/libreloc/libc.so.6+0x30afb 0x1217faf
</code></pre>
<p>Looking at the error message, I realized the issue was due to a node endpoint already mapped to another node.</p>
<p>Specifically, the error message says:</p>
<pre><code class="language-log">Failed to start a Raft group
</code></pre>
<p>and</p>
<pre><code class="language-log">node endpoint already mapped to node=0xe00004c58240  idx=0 host_id=7e833809-c052-449d-bbc0-b0b51188145f endpoint=
</code></pre>
<p>To fix it, I removed the existing node mappings and restarted the ScyllaDB cluster.</p>
<h2>Fixing ScyllaDB startup issue</h2>
<ul>
<li><p><strong>Step 1:</strong> Stop the ScyllaDB cluster using the following command:</p>
<pre><code class="language-bash">docker-compose down
</code></pre>
</li>
<li><p><strong>Step 2:</strong> Update <code>docker-compose.yml</code> file to use static IP for the nodes, which were available to the nodes when the cluster was started for the first time. For me it was the following configuration:</p>
<pre><code class="language-yaml">services:
  node1:
    image: scylladb/scylla
    container_name: node1
    command: --overprovisioned 1 --smp 1 --reactor-backend=epoll
    networks:
      default:
        ipv4_address: 172.18.0.4
    volumes:
      - /&lt;USER_HOME&gt;/scylladb/data/node1:/var/lib/scylla # Mount node1&#39;s data to /var/lib/scylla

  node2:
    image: scylladb/scylla
    container_name: node2
    command: --seeds=node1 --overprovisioned 1 --smp 1 --reactor-backend=epoll
    networks:
      default:
        ipv4_address: 172.18.0.3
    volumes:
      - /&lt;USER_HOME&gt;/scylladb/data/node2:/var/lib/scylla # Mount node2&#39;s data to /var/lib/scylla

  node3:
    image: scylladb/scylla
    container_name: node3
    command: --seeds=node1 --overprovisioned 1 --smp 1 --reactor-backend=epoll
    networks:
      default:
        ipv4_address: 172.18.0.2
    volumes:
      - /&lt;USER_HOME&gt;/scylladb/data/node3:/var/lib/scylla # Mount node3&#39;s data to /var/lib/scylla

networks:
  default:
    driver: bridge
    ipam:
    config:
      - subnet: 172.18.0.0/16
        gateway: 172.18.0.1
</code></pre>
</li>
<li><p><strong>Step 3:</strong> Start the ScyllaDB cluster again using the following command:</p>
<pre><code class="language-bash">docker-compose up -d
</code></pre>
</li>
</ul>
<p>The ScyllaDB cluster started successfully after updating the node mappings and restarting the cluster, resolving the issue without any further errors.</p>
]]></content:encoded>
    </item>
    <item>
      <title>ScyllaDB basics</title>
      <link>https://ayushsingh.dev/blog/scylla-basics</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/scylla-basics</guid>
      <pubDate>Sat, 26 Oct 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Notes on ScyllaDB</description>
      <content:encoded><![CDATA[<p>ScyllaDB is a <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a>, peer-to-peer distributed database built to manage big data while eliminating single points of failure. It ensures high availability even in the event of hardware or network issues.</p>
<p>The database design is based on several key principles:</p>
<ul>
<li><strong>High Scalability</strong>: ScyllaDB can scale both horizontally (by adding more <a href="https://university.scylladb.com/topic/node/">nodes</a>) and vertically (by efficiently utilizing modern multi-core CPUs, multi-CPU nodes, and high-capacity storage).</li>
<li><strong>High Availability</strong>: The system maintains low latency and remains operational even if one or more nodes fail or there is a network disruption.</li>
<li><strong>High Performance</strong>: ScyllaDB operates close to the hardware level, ensuring low, consistent latency and high throughput.</li>
<li><strong>Low Maintenance</strong>: It includes user-friendly features such as automated configurations and self-tuning capabilities, reducing the need for manual intervention.</li>
</ul>
<p>For users familiar with <a href="http://cassandra.apache.org/">Apache Cassandra®</a>, many ScyllaDB commands and features will feel intuitive. This is because ScyllaDB was designed to be fully compatible with Cassandra at the API level.</p>
<h2>My setup script</h2>
<pre><code class="language-bash"># Setup scylla db

# Echo get the number of nodes to run
echo &quot;Enter the number of nodes to run&quot;
read num_nodes

# Setup docker network scylla_net if it does not exist
docker network inspect scylla_net &gt; /dev/null 2&gt;&amp;1

if [ $? -eq 1 ]; then
    docker network create scylla_net
fi

# Run scylla db node1
docker run --name node1 --network scylla_net -d scylladb/scylla:6.1.1 --overprovisioned 1 --smp 1 --reactor-backend=epoll

# Seed node with ip of node1
seed_ip=$(docker inspect -f &#39;{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39; node1)

# Echo seed ip
echo &quot;Seed node ip: $seed_ip&quot;

# Run the rest of the nodes
if [ $num_nodes -gt 1 ]; then
    for i in $(seq 2 $num_nodes); do
        docker run --name node$i --network scylla_net -d scylladb/scylla:6.1.1 --seeds=&quot;$seed_ip&quot; --overprovisioned 1 --smp 1 --reactor-backend=epoll
    done
fi
</code></pre>
<h2>Node</h2>
<p>A node is the fundamental building block of a ScyllaDB database, consisting of the ScyllaDB server software running on a physical or virtual server.</p>
<p>Each node holds a portion of the overall database cluster&#39;s data and is divided into multiple independent shards.</p>
<p>In ScyllaDB, all nodes are equal, with no master or slave roles. Every node is capable of handling requests, and they collaborate to ensure continuous service, even if one node becomes unavailable due to a failure.</p>
<h2>Keyspace and Table</h2>
<p>A Keyspace is a collection of tables with settings that determine how data is replicated across nodes (Replication Strategy). It includes several options that apply to all the tables within it. Typically, it&#39;s advised to use one Keyspace per application, so a cluster might have only a single Keyspace.</p>
<p>A Table represents how ScyllaDB organizes and stores data, functioning as a collection of rows and columns.</p>
<h2>Cluster – Node Ring</h2>
<p>A Cluster in ScyllaDB is a collection of nodes used to store and manage data, with the nodes arranged in a logical ring structure. Typically, a cluster consists of at least three nodes, and data is automatically replicated across these nodes based on the defined Replication Factor.</p>
<p>This ring-like architecture is based on a hash ring, which guides how data is distributed across the nodes within the cluster.</p>
<p>Clusters can scale dynamically, either by adding nodes to increase storage and processing capabilities or by removing nodes through planned decommissioning or in response to failures. When the cluster&#39;s topology changes, ScyllaDB automatically reconfigures itself to rebalance the data.</p>
<p>While a ScyllaDB cluster requires a minimum of three nodes, it can scale to include hundreds. Communication between nodes within the cluster is peer-to-peer, eliminating any single point of failure. For external communication, such as read or write operations, a ScyllaDB client connects to a single node called the coordinator. This coordinator is selected for each client request, preventing any one node from becoming a bottleneck. Further details on this process are provided later in the lesson.</p>
<p>A Partition Key consists of one or more columns that determine how data is distributed across the nodes. It decides where a specific row will be stored. Typically, data is replicated across multiple nodes, ensuring that even if one node fails, the data remains accessible, providing reliability and fault tolerance.</p>
<p>For example, if the Partition Key is the ID column, a consistent hash function will determine which nodes store the data.</p>
<p>ScyllaDB transparently partitions and distributes data throughout the cluster. Data replication ensures availability, and the cluster is visualized as a ring, where each node manages a range of tokens. Each data value is associated with a token using a partition key:
<img src="https://ayushsingh.dev/scylla_key.png" alt="scylla_key"></p>
<h2>Data Replication</h2>
<p>To eliminate any single point of failure, ScyllaDB uses data replication, which involves storing copies of data across multiple nodes. This ensures that even if one node fails, the data remains accessible, providing reliability and fault tolerance. The number of copies, or Replication Factor (RF), determines how many times the data is duplicated.</p>
<p>For instance, a Replication Factor of 3 (RF=3) means that three copies of the data are maintained at all times. Users set the RF for a specific keyspace, and based on this setting, the coordinator distributes the data to other nodes, known as replicas, to ensure redundancy and fault tolerance.</p>
<h2>Shard</h2>
<p>Each ScyllaDB node is divided into several independent shards, with each shard managing a portion of the node&#39;s data. ScyllaDB allocates one shard per core (technically, one per hyperthread, meaning a physical core may support multiple virtual cores). Each shard follows a shared-nothing architecture, meaning it has dedicated RAM and storage, manages its own CPU and I/O scheduling, performs compactions (explained further later), and maintains its own multi-queue network connection. Shards operate as single threads and communicate asynchronously with each other without the need for locking.</p>
<p>From an external perspective, nodes are treated as unified entities, with operations executed at the node level.</p>
<h2>Datacenter</h2>
<p>A datacenter is a physical facility that houses servers, storage systems, and networking equipment. Cloud providers operate multiple datacenters across various countries worldwide.</p>
<p>ScyllaDB is designed to be fault-tolerant at the software level and is also aware of the datacenter&#39;s topology. For instance, you might want to place replica nodes on different racks within a datacenter to reduce the risk of disruptions caused by rack-specific network or power failures. ScyllaDB manages this using a mechanism called snitches.</p>
<p>A Rack is a metal framework that holds hardware components such as servers, hard drives, and networking devices. ScyllaDB recognizes logical racks to add an extra layer of fault tolerance, ensuring that if one rack (or even an entire datacenter) fails, data remains accessible.</p>
<p>ScyllaDB also supports multi-datacenter replication, enabling data sharing and distribution across two or more datacenters. The replication strategy allows you to specify the number of datacenters for replication and set distinct replication factors for each one.</p>
<p>Datacenters in ScyllaDB are configured in a peer-to-peer manner, meaning there is no central authority, nor are there &quot;primary/replica&quot; hierarchical relationships between clusters.</p>
<p>This setup enables data replication across clusters to handle localized traffic with minimal latency and high throughput, and to ensure resilience in case of a complete datacenter outage.
<img src="https://ayushsingh.dev/scylla_dc.png" alt="scylladb_datacenter"></p>
<h2>Replication Strategy</h2>
<p>The Replication Strategy defines how replicas are distributed across nodes. ScyllaDB offers two replication strategies:</p>
<ul>
<li><strong>SimpleStrategy</strong>: The first replica is placed on the node determined by the partitioner, which is a hash function used to map data to specific nodes in the cluster. Subsequent replicas are positioned clockwise around the node ring. This strategy is not recommended for production environments.</li>
<li><strong>NetworkTopologyStrategy</strong>: Replicas are placed clockwise around the ring until a node on a different rack is reached. This strategy is ideal for clusters spread across multiple datacenters, as it allows you to specify the number of replicas for each datacenter.</li>
</ul>
<p>For example, if there are two datacenters, DC1 with a replication factor of 3 and DC2 with a replication factor of 2, the overall replication factor for the keyspace would be 5. Below, we&#39;ll demonstrate how to create such a keyspace.</p>
<h2>Token Ranges</h2>
<p>In a ScyllaDB ring, each node is responsible for a specific token range. The hash function generates a token based on the partition key, which determines where the data is stored within the cluster.</p>
<p>Without virtual nodes (Vnodes), each node would manage only a single token range. However, with Vnodes, each physical node can handle multiple, non-contiguous token ranges, effectively allowing it to act as many virtual nodes. By default, each physical node is configured to host 256 virtual nodes.
<img src="https://ayushsingh.dev/scylla_tokens.png" alt="scylladb tokens"></p>
<h2>Consistency Level (CL)</h2>
<p>The number of nodes that must confirm a read or write operation before it is considered successful is defined by the consistency level.</p>
<p>To ensure data is correctly written or read, a sufficient number of nodes need to agree on its current state. Although consistency levels can be set globally for all operations (on the client side), ScyllaDB allows each read or write operation to have its own specific consistency level, a feature known as tunable consistency.</p>
<p>Here are some common consistency levels:</p>
<ul>
<li><strong>CL of 1</strong>: Wait for a response from a single replica node.</li>
<li><strong>CL of ALL</strong>: Wait for a response from all replica nodes.</li>
<li><strong>CL LOCAL_QUORUM</strong>: Wait for responses from a majority of replica nodes in the local datacenter, calculated as <code>floor((#dc_replicas / 2) + 1)</code>. For example, if a datacenter has 3 replica nodes, the operation will wait for a response from 2 nodes.</li>
<li><strong>CL EACH_QUORUM</strong>: In multi-datacenter setups, each datacenter must reach a LOCAL_QUORUM. This level is not supported for read operations.</li>
<li><strong>CL ALL</strong>: Requires responses from all replica nodes, providing the highest level of consistency but at the cost of reduced availability.</li>
</ul>
<p>Since data may be updated on the coordinator node but not yet fully replicated across all nodes, ScyllaDB implements eventual consistency. With this model, all replicas will eventually synchronize to the same data state, even as operations continue to update the database.</p>
<h2>Cluster Level Read/Write Interaction</h2>
<p>So what happens when data is read or written at the <a href="https://university.scylladb.com/topic/cluster-node-ring/">cluster</a> level? Note that what happens at the <a href="https://university.scylladb.com/topic/node/">node</a> level will be explained in another lesson.</p>
<p>Since each node is equal in ScyllaDB, any node can receive a read/write request. These are the main steps in the process:
<img src="https://ayushsingh.dev/scylla_cluster.png" alt="scylla_cluser">]</p>
<ol>
<li>A client connects to a ScyllaDB node using the CQL shell and performs a CQL request</li>
<li>The node the client is connected to is now designated as the Coordinator Node. The Coordinator Node, based on <a href="https://en.wikipedia.org/wiki/Hash_function">hashing</a> the data, using the partition key and on the <a href="https://university.scylladb.com/topic/replication-strategy/">Replication Strategy</a>, sends the request to the applicable nodes. Internode messages are sent through a messaging queue asynchronously.</li>
<li>The <a href="https://university.scylladb.com/topic/consistency-level-cl/">Consistency Level</a> determines the number of nodes the coordinator needs to hear back from for the request to be successful.</li>
<li>The client is notified if the request is successful.</li>
</ol>
<h2>Gossip</h2>
<p>ScyllaDB, similar to Apache Cassandra, employs a decentralized internode communication protocol known as Gossip. This protocol allows nodes to exchange information without relying on a single point of failure. Gossip is used for tasks such as peer node discovery and the distribution of metadata across the cluster. Communication happens periodically, with each node interacting with three other nodes. Over a short period (usually a few seconds), this information spreads throughout the entire cluster.</p>
<h2>Snitch</h2>
<p>The Snitch in ScyllaDB determines which racks and datacenters should be used for reading and writing data. ScyllaDB offers the following types of snitches:</p>
<ul>
<li><strong>SimpleSnitch</strong>: The default option, recommended only for single datacenter clusters.</li>
<li><strong>RackInferringSnitch</strong>: Assigns nodes to datacenters and racks based on their broadcast IP addresses.</li>
<li><strong>GossipingPropertyFileSnitch</strong>: Explicitly defines the rack and datacenter for each node. Preferred over SimpleSnitch for better configuration.</li>
<li><strong>Ec2Snitch</strong>: Automatically detects the cluster topology using the AWS API, suitable for single-region deployments on AWS where the region acts as a datacenter.</li>
<li><strong>Ec2MultiRegionSnitch</strong>: Similar to Ec2Snitch but designed for clusters spread across multiple AWS regions.</li>
<li><strong>GoogleCloudSnitch</strong>: Designed for ScyllaDB deployments on Google Cloud Engine (GCE). Treats regions as datacenters and availability zones as racks within those datacenters.</li>
</ul>
<h1>My ScyllaDB docker-compose setup</h1>
<pre><code class="language-yaml">services:
  node1:
    image: scylladb/scylla
    container_name: node1
    command: --overprovisioned 1 --smp 1 --reactor-backend=epoll
    volumes:
      - ./data/node1:/var/lib/scylla

  node2:
    image: scylladb/scylla
    container_name: node2
    command: --seeds=node1 --overprovisioned 1 --smp 1 --reactor-backend=epoll
    volumes:
      - ./data/node2:/var/lib/scylla

  node3:
    image: scylladb/scylla
    container_name: node3
    command: --seeds=node1 --overprovisioned 1 --smp 1 --reactor-backend=epoll
    volumes:
      - ./data/node3:/var/lib/scylla
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>CAP theorem</title>
      <link>https://ayushsingh.dev/blog/cap-theorem</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/cap-theorem</guid>
      <pubDate>Fri, 25 Oct 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Notes on CAP theorem</description>
      <content:encoded><![CDATA[<p>So CAP theorem states that Distributed systems can strive for three characteristics</p>
<ul>
<li>Consistency</li>
<li>Availability</li>
<li>Partition Tolerance</li>
</ul>
<p>However the CAP theorem states that there is a trade off between these three attributes, we can only choose two out of these three</p>
<h2>Availability</h2>
<p>We still be able to serve requests when there is some kind of failure. When some of our nodes in our distributed system become unavailable.</p>
<p>This is done by replicating data. For each piece of data, we have multiple copies spread across multiple DBs.</p>
<h2>Consistency</h2>
<p>For our read request we will always get the latest write.</p>
<h2>Partition Tolerance</h2>
<p>In case of a network failure between nodes, the system should work and try to get back to consistent state when failure disappears.</p>
<h2>Examples</h2>
<h3>CP databases</h3>
<ul>
<li>Apache HBase</li>
<li>MongoDB</li>
</ul>
<h3>AP databases</h3>
<ul>
<li>ScyllaDB</li>
<li>Casandra</li>
<li>DynamoDB</li>
</ul>
<h3>CA databases</h3>
<ul>
<li>Vertica</li>
<li>MySQL</li>
<li>Postgres</li>
</ul>
<p>This doesn&#39;t mean databases don&#39;t have all three attributes. But the databases favours certain attributes in favour of other in case of a failure.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How to fix helm upgrade</title>
      <link>https://ayushsingh.dev/blog/fix-helm-upgrade</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/fix-helm-upgrade</guid>
      <pubDate>Mon, 21 Oct 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Fixing resource mapping for older helm releases</description>
      <content:encoded><![CDATA[<p>Recently, I was trying to upgrade a Helm chart in an EKS cluster and I encountered the following error:</p>
<pre><code>Helm upgrade failed: resource mapping not found for name: &quot;&lt;RELEASE_NAME&gt;&quot; namespace: &quot;&quot; from &quot;&quot;: no matches for kind &quot;HorizontalPodAutoscaler&quot; in version &quot;autoscaling/v2beta1&quot;
</code></pre>
<h3>To fix this I did the following:</h3>
<ol>
<li>Installed the <code>helm-mapkubeapis</code> plugin</li>
</ol>
<pre><code class="language-bash">helm plugin install https://github.com/helm/helm-mapkubeapis
</code></pre>
<ol start="2">
<li>Run the plugin to update the resource mapping</li>
</ol>
<pre><code class="language-bash">helm mapkubeapis &lt;RELEASE_NAME&gt;
</code></pre>
<ol start="3">
<li>Upgrade/Delete the Helm chart</li>
</ol>
<pre><code class="language-bash">helm upgrade &lt;RELEASE_NAME&gt; &lt;CHART_NAME&gt;

# or

helm delete &lt;RELEASE_NAME&gt;
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Allow any unknown developer app on macOS</title>
      <link>https://ayushsingh.dev/blog/allow-any-mac-app</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/allow-any-mac-app</guid>
      <pubDate>Thu, 03 Oct 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Reason to hate macOS 312</description>
      <content:encoded><![CDATA[<p>macOS is a great operating system. But sometimes it can be frustrating. One such thing is the restriction on installing apps from unknown developers. This is a good security feature, but sometimes it can be annoying.</p>
<p>To allow any unknown developer app on macOS, you can use the following command in the terminal.</p>
<pre><code class="language-bash">sudo spctl --master-disable
</code></pre>
<p>Then go to <code>System Preferences</code> -&gt; <code>Privacy &amp; Security</code> -&gt; scroll down to <code>Security</code> -&gt; <code>Allow Applications from</code> -&gt; <code>Anywhere</code></p>
<p><img src="https://ayushsingh.dev/allow_macos_app.png" alt="macos_settings"></p>
<p>This will allow you to install any app on macOS without any restrictions. But be careful, as this will allow you to install any app on your system.</p>
]]></content:encoded>
    </item>
    <item>
      <title>DS Algo Questions</title>
      <link>https://ayushsingh.dev/blog/interview-questions</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/interview-questions</guid>
      <pubDate>Thu, 03 Oct 2024 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>A set of DS Algo question that one should know before going for an interview</description>
      <content:encoded><![CDATA[<h2>Arrays</h2>
<ul>
<li><a href="https://www.interviewbit.com/problems/repeat-and-missing-number-array/">Repeat and Missing Number Array (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-a-repeating-and-a-missing-number/">Find a Repeating and a Missing Number (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/">Find Two Non-Repeating Elements in an Array (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-maximum-sum-triplets-array-j-k-ai-aj-ak/">Find Maximum Sum Triplets (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/stock-buy-sell/">Stock Buy Sell (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-maximum-number-possible-by-doing-at-most-k-swaps/">Find Maximum Number Possible by Doing at Most K Swaps (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/">Minimum Number of Jumps to Reach End (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/longest-increasing-subsequence/solution/">Longest Increasing Subsequence (LeetCode)</a> (<a href="https://www.youtube.com/watch?v=TocJOW6vx_I&ab_channel=takeUforward">Video Explanation</a>)</li>
<li><a href="https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/">Form the Biggest Number (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/">Search a Word in a 2D Grid (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/trapping-rain-water/solution/">Trapping Rain Water (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/max-points-on-a-line/">Max Points on a Line (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/">Check If Array Pairs Are Divisible by K (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/merge-intervals/solution/">Merge Intervals (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/subarray-product-less-than-k/solution/">Subarray Product Less Than K (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/3sum/">3Sum (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/set-matrix-zeroes/">Set Matrix Zeroes (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/range-sum-query-2d-immutable/">Range Sum Query 2D (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/first-missing-positive/">First Missing Positive (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/top-k-frequent-elements/">Top K Frequent Elements (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/longest-palindromic-substring/">Longest Palindromic Substring (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/sort-colors/">Sort Colors (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/">Maximum Points You Can Obtain from Cards (LeetCode)</a></li>
</ul>
<h2>Hashing</h2>
<ul>
<li><a href="https://leetcode.com/problems/4sum-ii/solution/">4Sum II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/longest-consecutive-sequence/">Longest Consecutive Sequence (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/lru-cache/">LRU Cache (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/length-of-the-longest-substring-with-equal-1s-and-0s/">Longest Substring with Equal 1s and 0s (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/range-module/">Range Module (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/my-calendar-i/">My Calendar I (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/my-calendar-ii/">My Calendar II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/my-calendar-iii/">My Calendar III (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/time-based-key-value-store/">Time-Based Key-Value Store (LeetCode)</a></li>
</ul>
<h2>Cyclic Sort</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/">Minimum Number of Swaps Required to Sort an Array (GeeksforGeeks)</a></li>
</ul>
<h2>Sorting</h2>
<ul>
<li><a href="https://leetcode.com/problems/kth-largest-element-in-an-array/">Kth Largest Element in an Array (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/count-of-smaller-numbers-after-self/">Count of Smaller Numbers After Self (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/reverse-pairs/">Reverse Pairs (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/top-k-frequent-elements/">Top K Frequent Elements (LeetCode)</a></li>
</ul>
<h2>LinkedList</h2>
<ul>
<li><a href="https://www.interviewbit.com/problems/partition-list/">Partition List (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/partition-list/">Partition List (LeetCode)</a></li>
<li><a href="https://www.interviewbit.com/problems/palindrome-list/">Palindrome List (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/palindrome-linked-list/">Palindrome Linked List (LeetCode)</a></li>
<li><a href="https://www.interviewbit.com/problems/list-cycle/">List Cycle (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/flattening-a-linked-list/">Flattening a Linked List (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/">Reverse a List in Groups (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/reverse-nodes-in-k-group/">Reverse Nodes in K-Group (LeetCode)</a></li>
</ul>
<h2>String</h2>
<ul>
<li><a href="https://leetcode.com/problems/group-anagrams/solution/">Group Anagrams (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/">Find the Smallest Window Containing All Characters (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/minimum-window-subsequence/">Minimum Window Subsequence (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/">Longest Substring with at Most K Distinct Characters (LeetCode)</a></li>
</ul>
<h2>Binary Search</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/allocate-minimum-number-pages/">Allocate Minimum Number of Pages (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/woodcutting-made-easy/">Woodcutting Made Easy (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/">Kth Smallest Element in a Sorted Matrix (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/maximum-length-possible-by-cutting-n-given-woods-into-at-least-k-pieces/">Maximum Length Possible by Cutting Woods (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">Median of Two Sorted Arrays (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/k-th-element-two-sorted-arrays/">Kth Element in Two Sorted Arrays (GeeksforGeeks)</a></li>
</ul>
<h2>Heaps &amp; Priority Queues</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/merge-k-sorted-linked-lists-set-2-using-min-heap/">Merge K Sorted Linked Lists Using Min-Heap (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/merge-k-sorted-lists/solution/">Merge K Sorted Lists (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/nearly-sorted-algorithm/">Nearly Sorted Algorithm (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/top-k-frequent-words/">Top K Frequent Words (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/find-median-from-data-stream/solution/">Find Median from Data Stream (LeetCode)</a></li>
<li><a href="https://practice.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1">Minimum Cost of Ropes (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/sliding-window-median/">Sliding Window Median (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/max-value-of-equation/">Max Value of Equation (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/trapping-rain-water-ii/">Trapping Rain Water II (LeetCode)</a></li>
</ul>
<h2>Stacks/Queues</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/">Sliding Window Maximum (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/">Design a Stack That Supports GetMin (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/min-stack/solution/">Min Stack (LeetCode)</a></li>
<li><a href="https://www.interviewbit.com/problems/first-non-repeating-character-in-a-stream-of-characters/">First Non-Repeating Character in a Stream (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/zigzag-tree-traversal/">Zigzag Tree Traversal (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/">Binary Tree Zigzag Level Order Traversal (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/sort-a-stack-using-recursion/">Sort a Stack Using Recursion (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/largest-rectangle-in-histogram/submissions/">Largest Rectangle in Histogram (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/maximal-rectangle/solution/">Maximal Rectangle (LeetCode)</a></li>
<li><a href="https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/">Max Rectangle in Binary Matrix (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/next-greater-element-i/">Next Greater Element I (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/valid-parenthesis-string/discuss/107577/Short-Java-O(n)-time-O(1)-space-one-pass">Valid Parenthesis String (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/decode-string/">Decode String (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/car-fleet-ii/">Car Fleet II (LeetCode)</a></li>
</ul>
<h2>Greedy</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/">Minimum Number of Platforms Required (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/majority-element/">Majority Element (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/minimize-cash-flow-among-given-set-friends-borrowed-money/">Minimize Cash Flow Among Friends (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/maximum-number-of-overlapping-intervals/?ref=rp">Maximum Number of Overlapping Intervals (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/task-scheduler/">Task Scheduler (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/guess-the-word/">Guess the Word (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/sentence-screen-fitting/">Sentence Screen Fitting (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/">Maximum Number of Events That Can Be Attended (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/queue-reconstruction-by-height/">Queue Reconstruction by Height (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/random-pick-with-blacklist/">Random Pick with Blacklist (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/random-pick-with-blacklist/discuss/144624/Java-O(B)-O(1)-HashMap">Random Pick with Blacklist - Java Discussion (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/video-stitching/">Video Stitching (LeetCode)</a></li>
</ul>
<h2>Trees</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/">Check if Array Can Represent Preorder Traversal of BST (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/2sum-binary-tree/">2 Sum Binary Tree (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-a-pair-with-given-sum-in-bst/">Find a Pair with Given Sum in BST (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/two-sum-iv-input-is-a-bst/">Two Sum IV - Input is a BST (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/">Construct Binary Tree from Postorder and Inorder (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/find-minimum-depth-of-a-binary-tree/">Find Minimum Depth of a Binary Tree (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/least-common-ancestor/">Least Common Ancestor (InterviewBit)</a></li>
<li><a href="https://www.interviewbit.com/problems/flatten-binary-tree-to-linked-list/">Flatten Binary Tree to Linked List (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/">Flatten Binary Tree to Linked List (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/sorted-linked-list-to-balanced-bst/">Sorted Linked List to Balanced BST (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/">Convert Sorted List to Binary Search Tree (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/">Inorder Tree Traversal Without Recursion (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/">Symmetric Tree - Tree Mirror Image of Itself (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/minimum-iterations-pass-information-nodes-tree/">Minimum Iterations to Pass Information in Nodes (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/query-ancestor-descendant-relationship-tree/">Query Ancestor-Descendant Relationship in Tree (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/">Check if a Binary Tree is BST (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/">Print Nodes at Distance K in Binary Tree (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/">Construct BST from Preorder Traversal (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/">Serialize/Deserialize Binary Tree (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/shortest-distance-between-two-nodes-in-bst/">Shortest Distance Between Two Nodes in BST (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/merge-two-binary-tree/">Merge Two Binary Trees (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/">Binary Tree Zigzag Level Order Traversal (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/connect-nodes-at-same-level-with-o1-extra-space/">Connect Nodes at Same Level with O(1) Space (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/">Maximum XOR of Two Numbers in an Array (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/sum-of-distances-in-tree/">Sum of Distances in Tree (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/find-duplicate-subtrees/">Find Duplicate Subtrees (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/">Binary Search Tree - Delete (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/delete-node-in-a-bst/">Delete Node in a BST (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/recover-binary-search-tree/solution/">Recover Binary Search Tree (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/">Smallest Subtree with All the Deepest Nodes (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/">Lowest Common Ancestor of Deepest Leaves (LeetCode)</a></li>
</ul>
<h2>Trie</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/find-all-shortest-unique-prefixes-to-represent-each-word-in-a-given-list/">Find All Shortest Unique Prefixes to Represent Words (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/shortest-unique-prefix/">Shortest Unique Prefix (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-set-2/?ref=rp">Print All Anagrams Together (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/design-search-autocomplete-system/solution/">Design Search Autocomplete System (LeetCode)</a></li>
</ul>
<h2>DSU (Disjoint Set Union)</h2>
<ul>
<li><a href="https://leetcode.com/problems/accounts-merge/">Accounts Merge (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/">Most Stones Removed with Same Row or Column (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/">Checking Existence of Edge Length Limited Paths (LeetCode)</a></li>
</ul>
<h2>Graph</h2>
<ul>
<li><a href="https://leetcode.com/problems/diameter-of-binary-tree/">Diameter of Binary Tree (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/longest-path-undirected-tree/">Longest Path in an Undirected Tree (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/topological-sorting/">Topological Sorting (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/clone-an-undirected-graph/">Clone an Undirected Graph (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/word-ladder-i/">Word Ladder I (InterviewBit)</a></li>
<li><a href="https://www.geeksforgeeks.org/word-ladder-length-of-shortest-chain-to-reach-a-target-word/">Word Ladder Length of Shortest Chain (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/detect-cycle-undirected-graph/">Detect Cycle in an Undirected Graph (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/detect-cycle-in-a-graph/">Detect Cycle in a Graph (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/">Find Precedence of Characters (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/">Minimum Time for All Oranges to Rot (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/graph-coloring-set-2-greedy-algorithm/?ref=rp">Graph Coloring - Greedy Algorithm (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/snake-ladder-problem-2/">Snake and Ladder Problem (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-in-java-using-priorityqueue/">Dijkstra&#39;s Shortest Path Algorithm (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/01-matrix/">0/1 Matrix (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/count-vowels-permutation/">Count Vowels Permutation (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/count-vowels-permutation/discuss/398222/Detailed-Explanation-using-Graphs-With-Pictures-O(n)">Count Vowels Permutation Discussion (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/574943/Java-Detailed-Explanation-with-Graph-Demo-DP-Easy-Understand">Number of Ways to Paint N x 3 Grid (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/critical-connections-in-a-network/">Critical Connections in a Network (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/redundant-connection/">Redundant Connection (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/longest-increasing-path-in-a-matrix/">Longest Increasing Path in a Matrix (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/course-schedule-ii/">Course Schedule II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/cheapest-flights-within-k-stops/">Cheapest Flights Within K Stops (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/path-with-minimum-effort/solution/">Path with Minimum Effort (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/string-transforms-into-another-string/">String Transforms into Another String (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/pacific-atlantic-water-flow/">Pacific Atlantic Water Flow (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/path-rectangle-containing-circles/#:~:text=There%20is%20a%20m*n%20rectangular,end%20without%20touching%20any%20circle">Path Rectangle Containing Circles (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/couples-holding-hands/discuss/153882/Simple-Easy-Java-Solution-99-LESS-THAN-10-LINES!-NO-COMPLEX-CONCEPT">Couples Holding Hands - Java Solution (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/couples-holding-hands/">Couples Holding Hands (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/">Minimum Cost to Make At Least One Valid Path in a Grid (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/0-1-bfs-shortest-path-binary-graph/">0-1 BFS Shortest Path in a Binary Graph (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/shortest-path-visiting-all-nodes/">Shortest Path Visiting All Nodes (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/shortest-path-with-alternating-colors/">Shortest Path with Alternating Colors (LeetCode)</a></li>
<li><a href="https://practice.geeksforgeeks.org/problems/steps-by-knight5927/1">Steps by Knight (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/best-meeting-point/">Best Meeting Point (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/shortest-distance-from-all-buildings/">Shortest Distance from All Buildings (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/walls-and-gates/">Walls and Gates (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/confusing-number-ii/">Confusing Number II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/the-most-similar-path-in-a-graph/">The Most Similar Path in a Graph (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/jump-game-iv/">Jump Game IV (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/loud-and-rich/">Loud and Rich (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/where-will-the-ball-fall/">Where Will the Ball Fall (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/count-pairs-of-nodes/">Count Pairs of Nodes (LeetCode)</a></li>
</ul>
<h2>DP (Dynamic Programming)</h2>
<ul>
<li><a href="https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/">Longest Palindromic Subsequence (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/longest-palindromic-subsequence/">Longest Palindromic Subsequence (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/champagne-tower">Champagne Tower (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/subset-sum-problem-dp-25">Subset Sum Problem (GeeksforGeeks)</a></li>
<li><a href="https://www.interviewbit.com/problems/longest-common-subsequence/">Longest Common Subsequence (InterviewBit)</a></li>
<li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/">Best Time to Buy and Sell Stock III (LeetCode)</a></li>
<li><a href="https://www.youtube.com/watch?v=2FROyvnnrrM&ab_channel=KeertiPurswani">Best Time to Buy and Sell Stock III (YouTube)</a></li>
<li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/solution/">Best Time to Buy and Sell Stock IV (LeetCode)</a></li>
<li><a href="https://www.youtube.com/watch?v=4wNXkhAky3s&ab_channel=TECHDOSE">Best Time to Buy and Sell Stock IV (YouTube)</a></li>
<li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/">Best Time to Buy and Sell Stock with Cooldown (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/maximum-product-subarray/">Maximum Product Subarray (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/decode-ways/">Decode Ways (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/word-break-ii/">Word Break II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/split-array-largest-sum/">Split Array Largest Sum (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/perfect-squares/">Perfect Squares (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-cost-for-tickets/">Minimum Cost for Tickets (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-cost-for-tickets/discuss/630868/explanation-from-someone-who-took-2-hours-to-solve">Minimum Cost for Tickets Discussion (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/2-keys-keyboard/">2 Keys Keyboard (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/dungeon-game/">Dungeon Game (LeetCode)</a></li>
<li><a href="https://www.youtube.com/watch?v=4uUGxZXoR5o&ab_channel=TECHDOSE">Dungeon Game (YouTube)</a></li>
<li><a href="https://leetcode.com/problems/longest-arithmetic-subsequence/">Longest Arithmetic Subsequence (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/triangle/">Triangle (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-number-of-refueling-stops/">Minimum Number of Refueling Stops (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/">Best Time to Buy and Sell Stock with Transaction Fee (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/encode-string-with-shortest-length/">Encode String with Shortest Length (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/regular-expression-matching/">Regular Expression Matching (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/">Minimum Swaps to Make Sequences Increasing (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/stone-game-iii/">Stone Game III (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/">Maximum Sum of 3 Non-Overlapping Subarrays (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/burst-balloons/">Burst Balloons (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/predict-the-winner/">Predict the Winner (LeetCode)</a></li>
<li><a href="https://www.geeksforgeeks.org/optimal-strategy-for-a-game-dp-31/">Optimal Strategy for a Game (GeeksforGeeks)</a></li>
<li><a href="https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/">Palindrome Partitioning (GeeksforGeeks)</a></li>
<li><a href="https://leetcode.com/problems/as-far-from-land-as-possible/">As Far from Land as Possible (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/russian-doll-envelopes/">Russian Doll Envelopes (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/">Minimum Number of Removals to Make Mountain Array (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/binary-tree-cameras/">Binary Tree Cameras (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/make-array-strictly-increasing/">Make Array Strictly Increasing (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/make-array-strictly-increasing/discuss/379095/C%2B%2B-DFS-%2B-Memo">Make Array Strictly Increasing Discussion (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/race-car/submissions/">Race Car (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/new-21-game/">New 21 Game (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/cherry-pickup-ii/">Cherry Pickup II (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/cherry-pickup/">Cherry Pickup (LeetCode)</a></li>
<li><a href="https://leetcode.com/problems/house-robber-iii/">House Robber III (LeetCode)</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Happy New Year</title>
      <link>https://ayushsingh.dev/blog/happy-new-year</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/happy-new-year</guid>
      <pubDate>Sun, 31 Dec 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>My life with my friends is practically over now. I need a new life project.</description>
      <content:encoded><![CDATA[<p>Alright, time to get a bit mushy about my bois – don&#39;t worry, it won&#39;t happen too often. They know how much I love them, with all their quirks and strengths.</p>
<p>Now they&#39;re getting married and moving on with their lives. I&#39;m happy for them and you should be too.</p>
<iframe src="https://www.youtube.com/embed/jwC06Izp1a8?autoplay=1" class="youtube"></iframe>

<p>P.S. This song perfectly sums up everything. Happy New Year!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Maximizing Impact</title>
      <link>https://ayushsingh.dev/blog/maximizing-impact</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/maximizing-impact</guid>
      <pubDate>Tue, 26 Dec 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Maximizing Impact as a Tech Lead: Essential Strategies for Application Excellence</description>
      <content:encoded><![CDATA[<p>Ensuring performance, quality, and responsiveness in an application involves a multifaceted approach that spans across various stages of the application development and maintenance lifecycle. Here&#39;s a breakdown of the key strategies:</p>
<ul>
<li><p><strong>Requirements Gathering and Planning:</strong></p>
<ul>
<li>Understanding user needs and system requirements is crucial. This helps in designing an application that meets performance expectations and quality standards.</li>
<li>Setting clear performance goals as part of the non-functional requirements.</li>
</ul>
</li>
<li><p><strong>Design and Architecture:</strong></p>
<ul>
<li>Adopting a robust and scalable architecture that can handle the anticipated load and allows for future expansion.</li>
<li>Using design patterns that promote modularity, reusability, and maintainability.</li>
</ul>
</li>
<li><p><strong>Development Practices:</strong></p>
<ul>
<li>Writing efficient and optimized code to enhance performance.</li>
<li>Utilizing frameworks and libraries that are known for their performance and reliability.</li>
<li>Implementing responsive design principles to ensure the application adapts to different device screens and resolutions.</li>
</ul>
</li>
<li><p><strong>Testing:</strong></p>
<ul>
<li>Conducting various types of testing such as unit testing, integration testing, system testing, and user acceptance testing to ensure quality.</li>
<li>Performing performance testing to identify bottlenecks and optimize the system’s response time, throughput, and scalability.</li>
<li>Using automated testing tools to ensure continuous quality control.</li>
</ul>
</li>
<li><p><strong>Deployment:</strong></p>
<ul>
<li>Optimizing server configurations and resources based on the application’s needs.</li>
<li>Implementing load balancing and clustering for high-availability applications.</li>
</ul>
</li>
<li><p><strong>Monitoring and Maintenance:</strong></p>
<ul>
<li>Continuously monitoring the application’s performance using tools that can track response times, server health, and error rates.</li>
<li>Regularly updating the application and its dependencies to the latest versions for performance improvements and security patches.</li>
<li>Analyzing user feedback and usage patterns to make iterative improvements.</li>
</ul>
</li>
<li><p><strong>Scalability:</strong></p>
<ul>
<li>Designing the application with scalability in mind, so it can handle increased loads without a significant drop in performance.</li>
<li>Using cloud services and technologies that allow for easy scaling up or down based on demand.</li>
</ul>
</li>
<li><p><strong>Security Considerations:</strong></p>
<ul>
<li>Ensuring that security measures do not adversely impact performance.</li>
<li>Balancing security needs with usability to maintain a responsive user experience.</li>
</ul>
</li>
<li><p><strong>User Experience:</strong></p>
<ul>
<li>Focusing on the frontend performance to reduce load times and enhance interactivity.</li>
<li>Simplifying the user interface to improve responsiveness and ease of use.</li>
</ul>
</li>
<li><p><strong>Feedback Loop:</strong></p>
<ul>
<li>Establishing a feedback loop with end-users to continuously gather insights on performance and usability, allowing for timely improvements.</li>
</ul>
</li>
</ul>
<p>Each of these steps plays a critical role in ensuring that the application not only meets its performance targets but also provides a high-quality and responsive experience for its users.</p>
]]></content:encoded>
    </item>
    <item>
      <title>What is a Functor?</title>
      <link>https://ayushsingh.dev/blog/what-is-functor</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/what-is-functor</guid>
      <pubDate>Mon, 25 Dec 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Functors are objects that can be used as though they are a function or function pointer.</description>
      <content:encoded><![CDATA[<p>In C++, a functor is an object that can be used like a function. This is achieved by providing an overload of the <code>operator()</code> in a class. When you create an instance of such a class, you can use this instance as if it were a function by invoking it with the same syntax as a function call. This makes functors very flexible, as they can store state and have properties like regular objects, while still being usable as functions.</p>
<p>Here&#39;s a simple example of a functor in C++:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;

using namespace std;

class Adder {
public:
    Adder(int n) : n_(n) {}

    int operator()(int x) const {
        return x + n_;
    }

private:
    int n_;
};

int main() {
    Adder addFive(5);
    cout &lt;&lt; &quot;Result: &quot; &lt;&lt; addFive(3) &lt;&lt; endl; // Result: 8
    return 0;
}
</code></pre>
<p>In this example, <code>Adder</code> is a functor. It is initialized with a number, and when it is called as a function, it adds this number to its argument. The <code>operator()</code> method makes this possible. This pattern is particularly useful in C++ for things like custom comparison functions in sorting algorithms, or for creating small function objects that carry state.</p>
<h2>Why is functor useful?</h2>
<p>The key difference between using a functor and simply passing an additional variable to a function in C++ lies in the encapsulation of both state and behavior, as well as the potential for increased flexibility and efficiency.</p>
<ol>
<li><p><strong>Encapsulation of State and Behavior</strong>: </p>
<ul>
<li>A functor encapsulates both data (state) and a specific operation (behavior) in one object. In the <code>Adder</code> example, the state is the value to add (<code>n_</code>), and the behavior is the addition operation itself.</li>
<li>In contrast, passing an extra variable to a function only provides additional data. The function&#39;s behavior is fixed and cannot be changed unless you modify the function&#39;s code.</li>
</ul>
</li>
<li><p><strong>Object-Oriented Approach</strong>: </p>
<ul>
<li>Functors align well with object-oriented programming principles. They allow you to bundle data and functionality together, and they can also inherit from other classes or implement interfaces.</li>
<li>Passing additional variables does not inherently leverage object-oriented principles.</li>
</ul>
</li>
<li><p><strong>Flexibility and Reusability</strong>: </p>
<ul>
<li>Functors can be more flexible. For instance, you can create different functor classes that implement the same interface but perform different operations. This makes it easy to swap out one functor for another without changing the code that uses them.</li>
<li>With a simple variable, this level of flexibility is not achievable. The function that uses the variable is limited to a specific operation defined in its implementation.</li>
</ul>
</li>
<li><p><strong>Efficiency in Certain Contexts</strong>: </p>
<ul>
<li>In some cases, using functors can be more efficient, especially in templated code like in the Standard Template Library (STL). Functors can be inlined by the compiler, potentially leading to more efficient code than using a pointer to a function.</li>
<li>Passing a variable doesn&#39;t have this potential for compiler optimization in the context of the operation&#39;s implementation.</li>
</ul>
</li>
<li><p><strong>Compatibility with STL and Other Libraries</strong>: </p>
<ul>
<li>Functors are widely used in C++ standard libraries, such as for custom comparison functions in sorting algorithms. They are designed to be used where the library expects an object that can be called like a function.</li>
<li>While passing variables is a common practice, it doesn&#39;t serve the same purpose as a functor in the context of these libraries.</li>
</ul>
</li>
</ol>
<p>In summary, functors offer a more encapsulated, flexible, and potentially efficient way to bundle data and operations together, aligning with object-oriented principles and offering advantages particularly in templated and library code. Passing additional variables to functions is a simpler approach but lacks these advantages.</p>
]]></content:encoded>
    </item>
    <item>
      <title>HashMaps basics</title>
      <link>https://ayushsingh.dev/blog/hashmaps</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/hashmaps</guid>
      <pubDate>Sun, 19 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Basic explanation of hash maps and various nuances</description>
      <content:encoded><![CDATA[<p>Definition: Hashmaps is a data structure that is structured as a key-value pair. It is also known as a dictionary, map, or associative array.</p>
<h1>Common operations</h1>
<ul>
<li>Access</li>
<li>Set</li>
<li>Remove</li>
<li>Traverse/Search<ul>
<li>For a key</li>
<li>For a value</li>
</ul>
</li>
</ul>
<h1>Big O</h1>
<table>
<thead>
<tr>
<th>Action</th>
<th>Time</th>
<th>Space</th>
</tr>
</thead>
<tbody><tr>
<td>Access</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Set</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Remove</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Traverse/Search</td>
<td></td>
<td></td>
</tr>
<tr>
<td>For a key</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>For a value</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
</tbody></table>
]]></content:encoded>
    </item>
    <item>
      <title>Isomorphic strings</title>
      <link>https://ayushsingh.dev/blog/isomorphic-strings</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/isomorphic-strings</guid>
      <pubDate>Sat, 18 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Check if a string is isomorphic to another string</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. s and t consist of any valid ascii character.</p>
<h1>Solution</h1>
<h1>Code</h1>
<h2>Brute force</h2>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;unordered_map&gt;
#include &lt;vector&gt;

using namespace std;

bool checkPair_slow(vector&lt;int&gt; arr, int target) {

  for (int i = 0; i &lt; arr.size(); i++) {
    for (int j = i; j &lt; arr.size(); j++) {
      if (arr[i] + arr[j] == target)
        return true;
    }
  }

  return false;
}

int main() {

  vector&lt;int&gt; arr = {3, 2, 7, 6, 5, 3, 2, 7, 12, 15, 1};

  printf(checkPair(arr, 54) ? &quot;t&quot; : &quot;f&quot;);
  printf(&quot;\n&quot;);

  return 0;
}
</code></pre>
<h2>Hashmap</h2>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;unordered_map&gt;
#include &lt;vector&gt;

using namespace std;

bool checkPair(vector&lt;int&gt; arr, int target) {
  unordered_map&lt;int, int&gt; umap;
  for (int i = 0; i &lt; arr.size(); i++) {
    if (umap.find(target - arr[i]) != umap.end()) {
      return true;
    } else {
      umap[arr[i]] = i;
    }
  }
  return false;
}

int main() {

  vector&lt;int&gt; arr = {3, 2, 7, 6, 5, 3, 2, 7, 12, 15, 1};

  printf(checkPair(arr, 54) ? &quot;t&quot; : &quot;f&quot;);
  printf(checkPair_slow(arr, 54) ? &quot;t&quot; : &quot;f&quot;);
  printf(&quot;\n&quot;);

  return 0;
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Two sums</title>
      <link>https://ayushsingh.dev/blog/two-sums</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/two-sums</guid>
      <pubDate>Sat, 18 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>The classic two sums problem</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>You are given an array of Integers and another integer targetValue. Write a function that will take these inputs and return the indices of the 2 integers in the array that add up targetValue.</p>
<h1>Solution</h1>
<h2>Brute force</h2>
<p>The brute force solution is quite simple. We can use 2 loops to iterate over the array and check if the sum of the 2 numbers is equal to the targetValue. If it is, we can return the indices of the 2 numbers.</p>
<h2>Hash table</h2>
<p>We can use a hash table to store the numbers and their indices. Then we can iterate over the array and check if the difference between the targetValue and the current number is in the hash table. If it is, we can return the indices of the 2 numbers.</p>
<h1>Code</h1>
<h2>Brute force</h2>
<pre><code class="language-cpp">vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {
    for(int i = 0; i &lt; nums.size(); i++) {
        for(int j = i + 1; j &lt; nums.size(); j++) {
            if(nums[i] + nums[j] == target) {
                return {i, j};
            }
        }
    }
    return {};
}
</code></pre>
<h2>Hash table</h2>
<pre><code class="language-cpp">vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {
    unordered_map&lt;int, int&gt; hash;
    for(int i = 0; i &lt; nums.size(); i++) {
        if(hash.find(target - nums[i]) != hash.end()) {
            return {hash[target - nums[i]], i};
        }
        hash[nums[i]] = i;
    }
    return {};
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Array basics</title>
      <link>https://ayushsingh.dev/blog/arrays</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/arrays</guid>
      <pubDate>Fri, 17 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Basic explanation of arrays and various nuances</description>
      <content:encoded><![CDATA[<p>Definition: Arrays is a data structure that is structured as a contiguous memory spaces for data values.</p>
<h1>Types</h1>
<ul>
<li>Static arrays</li>
<li>Dynamic arrays</li>
</ul>
<h1>Common operations</h1>
<ul>
<li>Access</li>
<li>Set</li>
<li>Traverse/Search</li>
<li>Copy</li>
<li>Insert<ul>
<li>at beginning</li>
<li>at end</li>
<li>somewhere in middle</li>
</ul>
</li>
<li>Remove<ul>
<li>at beginning</li>
<li>at end</li>
<li>somewhere in middle</li>
</ul>
</li>
</ul>
<h1>Big O</h1>
<table>
<thead>
<tr>
<th>Action</th>
<th>Time</th>
<th>Space</th>
</tr>
</thead>
<tbody><tr>
<td>Access</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Set</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Traverse/Search</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Copy</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Insert</td>
<td></td>
<td></td>
</tr>
<tr>
<td>at the beginning</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>at the end</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>somewhere in middle</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Remove</td>
<td></td>
<td></td>
</tr>
<tr>
<td>at the beginning</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>at the end</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>somewhere in middle</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
</tbody></table>
]]></content:encoded>
    </item>
    <item>
      <title>Monotonic arrays</title>
      <link>https://ayushsingh.dev/blog/monotonic-arrays</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/monotonic-arrays</guid>
      <pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Figuring out if an array is monotonic</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>An array is monotonic if it is either monotone increasing or monotone decreasing. An array is monotone increasing if all its elements from left to right are non-decreasing. An array is monotone decreasing if all its elements from left to right are non-increasing. Given an integer array return true if the given array is monotonic, or false otherwise.</p>
<h1>Solution</h1>
<p>The solution is quite simple. We can iterate over the array and check if it is monotone increasing or monotone decreasing. If it is neither, then it is not monotonic.</p>
<h2>Code</h2>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

bool isMonotonic(std::vector&lt;int&gt; &amp;arr) {
    bool increasing = true;
    bool decreasing = true;
    for (int i = 1; i &lt; arr.size(); i++) {
        if (arr[i] &lt; arr[i - 1]) {
            increasing = false;
        }
        if (arr[i] &gt; arr[i - 1]) {
            decreasing = false;
        }
    }
    return increasing || decreasing;
}

int main() {
    std::vector&lt;int&gt; arr = {1, 2, 3, 4, 5};
    std::cout &lt;&lt; isMonotonic(arr) &lt;&lt; std::endl;
    return 0;
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Most water</title>
      <link>https://ayushsingh.dev/blog/most-water</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/most-water</guid>
      <pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Find the container with the most water</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water(depth is constant across containers). Return the area(that the 2 lines and the X axis make) of container which can store the max amount of water. Notice that you may not slant the container.</p>
<h1>Solution</h1>
<h2>Brute force</h2>
<p>Keeping the height of the container constant, we can find the width of the container by iterating over all possible combinations of two lines. This would take O(n^2) time and O(1) space.</p>
<h2>Optimized</h2>
<p>We can use a two pointer approach to solve this problem in O(n) time and O(1) space. We start with two pointers, one at the start and one at the end of the array. We calculate the area of the container formed by these two lines and move the pointer with the smaller height inwards. This is because the area of the container is limited by the smaller height. We keep doing this until the two pointers meet. We return the maximum area we have seen so far.</p>
<h1>Code</h1>
<h2>Brute force</h2>
<pre><code class="language-cpp">#include &lt;algorithm&gt;
#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int area_with_most_water(vector&lt;int&gt; list) {
  int len = list.size();
  if (len &lt; 2)
    return 0;

  int max_area = 0;
  for (int i = 0; i &lt; len; i++) {
    int left_height = list[i];
    for (int j = i + 1; j &lt; len; j++) {
      int distance = j - i;
      int right_height = list[j];
      int min_height = right_height &gt; left_height ? left_height : right_height;
      int area = min_height * distance;
      if (area &gt; max_area) {
        max_area = area;
      }
    }
  }
  return max_area;
}

int main() {
  vector&lt;int&gt; arr = {3, 1, 2, 4, 5};
  printf(&quot;Largest storeable area: %d\n&quot;, area_with_most_water_fast(arr));
  return 0;
}
</code></pre>
<h2>Optimized</h2>
<pre><code class="language-cpp">#include &lt;algorithm&gt;
#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;


int area_with_most_water_fast(vector&lt;int&gt; lines) {

  int len = lines.size();

  // there needs to be atleast 2 lines to form an area with the x-axis as basis
  if (len &lt;= 1)
    return 0;

  int start = 0;
  int end = len - 1;

  int area = 0;

  while (start &lt; end) {

    int distance = end - start;
    area = max(area, min(lines[start], lines[end]) * distance);

    if (lines[start] &lt; lines[end]) {
      start += 1;
    } else {
      end -= 1;
    }
  }
  return area;
}

int main() {

  vector&lt;int&gt; arr = {3, 1, 2, 4, 5};

  printf(&quot;Largest storeable area: %d\n&quot;, area_with_most_water_fast(arr));

  return 0;
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Rotate arrays</title>
      <link>https://ayushsingh.dev/blog/rotate-array</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/rotate-array</guid>
      <pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Rotating arrays</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>Given an array, rotate the array to the right by k steps, where k is non-negative.</p>
<h1>Solution</h1>
<h2>With extra space</h2>
<p>The solution is quite simple. We can use a temporary array to store the elements that will be rotated. Then we can copy the elements from the temporary array to the original array.</p>
<h2>Without extra space</h2>
<p>The solution is quite simple. We can reverse the array. Then we can reverse the first k elements and the last n - k elements.</p>
<h2>Code</h2>
<h3>With extra space</h3>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

// rotate right
vector&lt;int&gt; rotate_arr_right(int k, vector&lt;int&gt; arr) {
  int len = arr.size();
  int finalShift = k % len;
  if (finalShift == 0)
    return arr;
  vector&lt;int&gt; newArr(len, 0);

  for (int i = 0, j = k; i &lt; len; j = (j + 1) % len, i++) {
    newArr[j] = arr[i];
  }
  return newArr;
}

int main() {
  vector&lt;int&gt; arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  vector&lt;int&gt; newArr = rotate_arr_right(3, arr);
  for (int i = 0; i &lt; newArr.size(); i++) {
    printf(&quot;%d &quot;, newArr[i]);
  }
  printf(&quot;\n&quot;);
  return 0;
}
</code></pre>
<h3>Without extra space</h3>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

void x_reverse(vector&lt;int&gt; &amp;arr, int startIdx, int endIdx) {
  if (startIdx &gt; endIdx || startIdx &gt;= arr.size() || endIdx &gt;= arr.size())
    throw invalid_argument(&quot;invalid index&quot;);
  if (endIdx - startIdx &lt;= 1)
    return;
  while (startIdx &lt;= endIdx) {
    int temp = arr[startIdx];
    arr[startIdx] = arr[endIdx];
    arr[endIdx] = temp;
    startIdx += 1;
    endIdx -= 1;
  }
}

void print_arr(vector&lt;int&gt; &amp;arr) {

  for (int i = 0; i &lt; arr.size(); i++) {
    printf(&quot;%d &quot;, arr[i]);
  }
}

// rotate right without extra space
void rotate_arr(int k, vector&lt;int&gt; &amp;arr) {
  int len = arr.size();
  int finalShift = k % len;
  printf(&quot;finalShift: %d\n&quot;, finalShift);
  if (finalShift == 0)
    return;
  // reverse full arr
  x_reverse(arr, 0, len - 1);
  //  print_arr(arr);
  // reverse again from 0 -&gt; finalShift
  x_reverse(arr, 0, finalShift - 1);
  //  print_arr(arr);
  // reverse again from finalShift -&gt; len
  x_reverse(arr, finalShift, len - 1);
  //  print_arr(arr);
}


int main() {
  vector&lt;int&gt; arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  rotate_arr(3, arr);
  for (int i = 0; i &lt; arr.size(); i++) {
    printf(&quot;%d &quot;, arr[i]);
  }
  printf(&quot;\n&quot;);
  return 0;
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Sorting squares</title>
      <link>https://ayushsingh.dev/blog/sorting-squares</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/sorting-squares</guid>
      <pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Sorting squares of an array</description>
      <content:encoded><![CDATA[<h1>Problem statement</h1>
<p>Sorted Squared Array - You are given an array of Integers in which each subsequent value is not less than the previous value. Write a function that takes this array as an input and returns a new array with the squares of each number sorted in ascending order.</p>
<h1>Solution</h1>
<h2>Brute force</h2>
<p>The brute force solution is to square each element and then sort the array. This would take O(nlogn) time and O(n) space.</p>
<h2>Optimized</h2>
<p>The optimized solution is to use two pointers, one at the beginning and one at the end of the array. Compare the squares of the two pointers and add the larger one to the result array. Then move the pointer of the larger value towards the center of the array. Repeat this process until the two pointers meet. This would take O(n) time and O(n) space.</p>
<h1>Code</h1>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

vector&lt;int&gt; sort_squared_slow(vector&lt;int&gt; arr) {

  int len = arr.size();
  vector&lt;int&gt; newArr(len, 0);

  for (int i = 0; i &lt; len; i++) {
    newArr[i] = arr[i] * arr[i];
  }
  sort(newArr.begin(), newArr.end());
  return newArr;
}

vector&lt;int&gt; sort_squared(vector&lt;int&gt; arr) {
  int len = arr.size();
  vector&lt;int&gt; newArr(len, 0);
  for (int i = 0; i &lt; len; i++) {
    arr[i] = arr[i] * arr[i];
  }

  int newArrIdx = len - 1;
  int startPtr = 0;
  int endPtr = len - 1;

  while (startPtr &lt;= endPtr &amp;&amp; newArrIdx &gt; -1) {
    if (arr[startPtr] &lt; arr[endPtr]) {
      newArr[newArrIdx] = arr[endPtr];
      endPtr = endPtr - 1;
    } else {
      newArr[newArrIdx] = arr[startPtr];
      startPtr = startPtr + 1;
    }
    newArrIdx = newArrIdx - 1;
  }
  return newArr;
}

int main() {
  // initalize an array of accending integers

  vector&lt;int&gt; arr{-10, -8, -7, -7, -6, -4, -3, -1, 0, 4, 5, 6, 7, 8, 12, 19};

  // vector&lt;int&gt; newArr = sort_squared_slow(arr);
  vector&lt;int&gt; newArrFast = sort_squared(arr);

  for (int i = 0; i &lt; newArrFast.size(); i++) {
    printf(&quot;%d &quot;, newArrFast[i]);
  }
  printf(&quot;\n&quot;);
  return 0;
}
</code></pre>
]]></content:encoded>
    </item>
    <item>
      <title>Using LLDB</title>
      <link>https://ayushsingh.dev/blog/use-lldb</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/use-lldb</guid>
      <pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Using LLDB to debug C++ code</description>
      <content:encoded><![CDATA[<p>Using lldb is quite pleasant. It is a command line debugger that is available on MacOS and Linux. It is similar to gdb and I heared gdb is nicer. But on macos it&#39;s available by default so we&#39;ll use this only. It is also possible to use lldb on Windows but I have not tried it.</p>
<h2>Installation</h2>
<p>On MacOS, lldb is installed by default. On Linux, you can install it using the following command:</p>
<pre><code class="language-bash">sudo apt install lldb
</code></pre>
<h2>Usage</h2>
<p>To debug a program, you can use the following command:</p>
<pre><code class="language-bash">lldb &lt;program&gt;
</code></pre>
<p>This will open the lldb prompt. You can then use the following commands to debug your program:</p>
<ul>
<li><code>run</code>: Run the program</li>
<li><code>b &lt;line_num&gt;</code>: Set a breakpoint at the specified line</li>
<li><code>b &lt;function_name&gt;</code>: Set a breakpoint at the specified function</li>
<li><code>b 0x&lt;address&gt;</code>: Set a breakpoint at the specified address</li>
<li><code>b</code>: List all breakpoints</li>
</ul>
<p>There is also a gui mode that can be used by running the following command:</p>
<pre><code class="language-bash">lldb &lt;program&gt;
b &lt;function_name&gt;
run
gui
</code></pre>
<h2>Example</h2>
<p>Let&#39;s say we have the following program:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;

int main() {
    int a = 1;
    int b = 2;
    int c = a + b;
    std::cout &lt;&lt; c &lt;&lt; std::endl;
    return 0;
}
</code></pre>
<p>Then make sure you complie it with the <code>-g</code> flag:</p>
<pre><code class="language-bash">g++ -std=c++11 -g main.cpp
</code></pre>
<p>We can debug it using the following commands:</p>
<pre><code class="language-bash">lldb a.out
b 5
run
</code></pre>
<p>This will set a breakpoint at line 5 and run the program. The program will stop at line 5 and we can use the following commands to inspect the variables:</p>
<ul>
<li><code>p a</code>: Print the value of <code>a</code></li>
<li><code>p b</code>: Print the value of <code>b</code></li>
<li><code>p c</code>: Print the value of <code>c</code></li>
<li><code>n</code>: Execute the next line</li>
<li><code>s</code>: Step into the next function call</li>
<li><code>bt</code>: Print the stack trace</li>
<li><code>l</code>: List the source code around the current line</li>
<li><code>c</code>: Continue execution until the next breakpoint</li>
<li><code>q</code>: Quit the debugger</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="https://lldb.llvm.org/use/tutorial.html">LLDB Tutorial</a></li>
<li><a href="https://lldb.llvm.org/use/map.html">LLDB Command Line Options</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Update on time tracker</title>
      <link>https://ayushsingh.dev/blog/trackmyday-1</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/trackmyday-1</guid>
      <pubDate>Fri, 14 Jul 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>It has a new name now</description>
      <content:encoded><![CDATA[<p>I&#39;m done with all the tech that lure me into their documentations.</p>
<p>I say stop to it.</p>
<p>My current setup is as follows</p>
<table>
<thead>
<tr>
<th>Domain</th>
<th>My choice</th>
</tr>
</thead>
<tbody><tr>
<td>frontend</td>
<td>svelte on sveltekit</td>
</tr>
<tr>
<td>design framework</td>
<td>tailwind ui</td>
</tr>
<tr>
<td>backend</td>
<td>actix on rust</td>
</tr>
<tr>
<td>db</td>
<td>sqlite3 with litefs</td>
</tr>
</tbody></table>
<p>I&#39;ll expand on my choices in later updates as I get more comfortable with them.</p>
<p>Other than that, this application has a new name now</p>
<p>It is &quot;Track My Day&quot;</p>
<p>The current page is deployed on <a href="https://trackmy.day">https://trackmy.day</a>. At the point of writing the page only has one <code>h1</code> tag and one <code>p</code> tag.</p>
<p>I&#39;m happy I got this domain.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Attention tracking</title>
      <link>https://ayushsingh.dev/blog/chronologger-start</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/chronologger-start</guid>
      <pubDate>Wed, 28 Jun 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Trying to track time I&apos;ve lost</description>
      <content:encoded><![CDATA[<p>I&#39;ve been thinking about working on a new way of looking at time tracking.</p>
<p>Time tracking requires a lot of effort and discipline to get it right. What I want to do with this application is to try to remove the headache of tracking attention on various devices for a single individual and sync them in such a manner that, it stays true to the correct timeline of one&#39;s attention.</p>
<blockquote>
<p>My main insight for this application is that, As much as I try to multitask my brain serializes all the tasks I throw at it.</p>
</blockquote>
<p>One can always try to maximise the efficiency of the work that they&#39;re trying to accomplish by limiting the meaningful interactions seen by the brain.</p>
<p><img src="https://ayushsingh.dev/chronologger.png" alt="inspiration"></p>
<p>And given the current tooling available there are two different problems I&#39;ve faced</p>
<ul>
<li>You need to install different applications to track time on various different platforms which produce results which are incompatible to reconcile</li>
<li>You need to start and stop time tracking manually most of the time</li>
</ul>
<p>With this application I&#39;m trying to bridge the gap between different platforms by</p>
<ul>
<li>passively recording app open and close<ul>
<li>record &quot;in app&quot; tasks using extensions, which are easy to build using simple API to tag attention point correctly</li>
</ul>
</li>
<li>reconcile all the inputs from various platforms programatically<ul>
<li>one solution I&#39;m exploring right now is CRDT&#39;s<ul>
<li>and it is looking promising</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>And my current goal is to make this work okayish for me. I&#39;ll try to update asap.</p>
<p>Till then stay classy.</p>
]]></content:encoded>
    </item>
    <item>
      <title>LiteFS is not a magic bullet</title>
      <link>https://ayushsingh.dev/blog/playing-with-litefs</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/playing-with-litefs</guid>
      <pubDate>Tue, 27 Jun 2023 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Playing with distributed databases and deployments</description>
      <content:encoded><![CDATA[<p>As brilliant as <a href="https://github.com/superfly/litefs">this tool</a> is, it&#39;s not totally void of shortcomings. LiteFS is not a magic bullet for small projects as I previously thought it would be.</p>
<p>I need to accomplish some tasks before I move on to proper deployment piepline for the rust backend</p>
<ul>
<li>Create a docker file that allows me to just start the container anywhere with some urls as environment variables</li>
<li>To do that I need to copy litefs correctly into the docker container and run it</li>
<li>To schedule database syncing before starting the application to enusre data consistency</li>
</ul>
<hr>
<p>As I&#39;m reading more and more about this. I&#39;m not sure if it&#39;s the right decision to run litefs.</p>
<blockquote>
<p>The thing is that I don&#39;t know if its right to run while maintaining lighting speed during its production deployment.</p>
</blockquote>
<p>Turns out you can&#39;t run write queries on replica databases which renders the whole use of litefs null and void.</p>
<blockquote>
<p>Why even bother.. lol.</p>
</blockquote>
<p>Read the following paragraph</p>
<blockquote>
<p><em>Cluster management using leases</em></p>
<p>SQLite operates as a single-writer database which means only one transaction can write at a time. Because of this, we utilize a lease system whereby a single node acts as the &quot;primary&quot; node at any given time. All writes should be directed to that node and it will propagate changes to the rest of the cluster.</p>
<p>However, nodes can die or become disconnected from the cluster so the primary must be able to change dynamically. LiteFS is built to be run on ephemeral environments where cluster membership can change quickly and frequently so it utilizes leases via Consul to determine the current primary node.</p>
<p>When a LiteFS node starts up, it checks a key within the Consul server for the current primary node. If no primary node exists, then the LiteFS node attempts to obtain a lease from Consul to become a primary node itself. If successful, it updates the Consul key to share its API URL so other LiteFS nodes can connect to it.</p>
</blockquote>
<p>Now With this cleared.. I need to look at alternatives for replacing litefs as my primary data store.</p>
<hr>
<p>I can use a managed service for all my database needs and be done with it or I can look at other opensource services like following</p>
<h3><a href="https://vlcn.io/docs">VLCN</a> or <a href="https://github.com/marcua/ayb">ayb</a></h3>
<p>Exciting thing about <a href="https://vlcn.io/docs">VLCN</a> is that it provides multi-master replication and partition tolerance to SQLite via conflict free replicated data types (CRDTs)</p>
<p>And <a href="https://github.com/marcua/ayb">ayb</a> also provides simillar feature set but it is in its pre-alpha stage so not a good candidate for deployment right now.</p>
<hr>
<p>Turns out planetscale allow writes on replicas but it&#39;s counted as a proper paid database which I&#39;m not paying for an application that I haven&#39;t built yet.</p>
<p>Then there&#39;s <a href="https://turso.tech/">turso</a> and <a href="https://developers.cloudflare.com/d1/">Cloudflare D1</a> which in turn are doing the same thing that I can do with LiteFS without the added cost of using an external service.</p>
<blockquote>
<h2>D1 fineprint</h2>
<p>Larger databases: During the alpha period, the maximum per-database size is limited to 100 MB. We plan to support not only larger databases, but more databases, in the near future.</p>
<p>Read replication: D1 will create and distribute replicas of your data across the Cloudflare global network, reducing the latency for your read queries. Cloudflare distributes your data close to where your users are and keeps your read replicas up to date with changes.</p>
</blockquote>
<p>Most probably will go ahead with litefs and come up with an working application by the end of this week.</p>
<p>Till then stay classy.</p>
]]></content:encoded>
    </item>
    <item>
      <title>I&apos;m done making web apps</title>
      <link>https://ayushsingh.dev/blog/i-dont-want-to-make-webapps</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/i-dont-want-to-make-webapps</guid>
      <pubDate>Wed, 14 Dec 2022 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>I&apos;m not learning anything new</description>
      <content:encoded><![CDATA[<p>Making web apps is super easy now these days. Don&#39;t get me wrong, it&#39;s still very very labour intensive task. But I wouldn&#39;t say it&#39;s tough.</p>
<p>You end-up stringing multiple services to flow data from one point to another.
And in then direct everything into a database.</p>
<blockquote>
<p>DATABASES ARE DEAD. LONG LIVE THE DATABASE.</p>
</blockquote>
<p>Why the f*** is everything on web? Why are we not allowed to struggle offline anymore? Do we even want that?</p>
<p>No, we want everything right here and right now. And web does that for them. And web is the perfect tool for that. Everything is possible on web, because there people making sure it feels that way.</p>
<p>But when I used dream about working on software I used to think my software will run on big servers doing very important stuff like computing maths related to black holes or something related to it.</p>
<p>But what I ended up doing is something horrible instead. I started working on web.
Why does everything need to be a service? Why can&#39;t I just enjoy a piece of software and appreciate it&#39;s design.</p>
<p>I&#39;ll try to figure out what I&#39;ll do next. Till then stay classy.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Async in JavaScript</title>
      <link>https://ayushsingh.dev/blog/async-js</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/async-js</guid>
      <pubDate>Fri, 03 Dec 2021 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Javascript asynchronous code execution flow</description>
      <content:encoded><![CDATA[<p>Javascript is a wonderful language and really provides many tools for code execution. One of the strengths of js is how it handles Asynchronous (async) code.</p>
<p>Rather than blocking the main execution thread, async code gets pushed to the event queue that fires after all other code executes. It can, however, be difficult for beginners to follow async code. This article aims to clarify all of that.</p>
<h1>Understanding Async Code</h1>
<p>So the most basic example of asynchronous code in js are <code>setTimout</code> and <code>setInterval</code>.
<code>setTimout</code> executes a function after a certain amount of time passes. It accepts a <em>callback</em> function and time(in milliseconds) as the second argument.</p>
<pre><code class="language-js">console.log(&#39;a&#39;)
setTimeout(function () {
  console.log(&#39;c&#39;)
}, 100)
setTimeout(function () {
  console.log(&#39;d&#39;)
}, 100)
setTimeout(function () {
  console.log(&#39;e&#39;)
}, 100)
console.log(&#39;b&#39;)

/* The output will be 
a
b
c
d
e
*/
</code></pre>
<p>Here we can see that the output matches our expectation.</p>
<p>The execution of code happened as following,</p>
<ul>
<li>on first line it blocking-ly executed <code>console.log(&#39;a&#39;)</code></li>
<li>then it saw an asynchronous function which it added to the event queue.<ul>
<li>understand that it hasn&#39;t started executing the code yet, that will happen later.</li>
</ul>
</li>
<li>similarly it added second and third <code>setTimeout</code> to event queue.</li>
<li>eventually it reached <code>console.log(&#39;b&#39;)</code> which it executed blocking-ly.</li>
<li>and after all the code has been executed in the block. then only js engine starts executing the async code from event queue.</li>
</ul>
<p>The <strong>event loop</strong> is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The javascript engine doesn&#39;t start processing the event loop until the code after an async function has executed. This allows us to see that our js code is not multi-threaded, even though it appears so.</p>
<p>The <strong>Event loop</strong> is a FIFO queue, meaning the callback function will execute in the order they were added onto the queue. And using <a href="https://nodejs.org">node</a> allows us to use this asynchronous behavior on the backend as well.</p>
<h1>Various ways to use async code execution</h1>
<ul>
<li>Callbacks<ul>
<li>Named function [passing functions as variables]</li>
<li>Promises [dependent on callbacks]</li>
</ul>
</li>
<li><em>Events</em></li>
</ul>
<h2>Callbacks</h2>
<p>This is the main method any async code is executed. Async programming lends itself to what&#39;s commonly referred to as <em>&quot;callback hell&quot;</em>. Because virtually all async functions in JavaScript use callbacks, performing multiple sequential async functions result in many nested callbacks--resulting in hard to read code.</p>
<pre><code class="language-js">const fs = require(&#39;fs&#39;)

fs.exists(&#39;index.js&#39;, function () {
  fs.readFile(&#39;index.js&#39;, &#39;utf8&#39;, function (err, contents) {
    contents = someFunction(contents) // do something with contents
    fs.writeFile(&#39;index.js&#39;, &#39;utf8&#39;, function () {
      console.log(&#39;whew! Done finally...&#39;)
    })
  })
})
console.log(&#39;executing...&#39;)
</code></pre>
<p>Nested callbacks can get really nasty, but there are several solutions to this style of coding.</p>
<h3>Named functions</h3>
<p>An easy solution that cleans nested callbacks is simply avoiding nesting more than two levels. Instead of passing anonymous functions to the callback arguments, pass a named function, which is a feature that javascript provides us.</p>
<pre><code class="language-js">var fromLatLng, toLatLng

// And lastly this function will execute
var routeDone = function (e) {
  console.log(&quot;ANNNND FINALLY here&#39;s the directions...&quot;)
  // do something with e
}

// Secondly this function will execute
var toAddressDone = function (results, status) {
  if (status == &#39;OK&#39;) {
    toLatLng = results[0].geometry.location
    map.getRoutes({
      origin: [fromLatLng.lat(), fromLatLng.lng()],
      destination: [toLatLng.lat(), toLatLng.lng()],
      travelMode: &#39;driving&#39;,
      unitSystem: &#39;imperial&#39;,
      callback: routeDone,
    })
  }
}

// First this function will execute
var fromAddressDone = function (results, status) {
  if (status == &#39;OK&#39;) {
    fromLatLng = results[0].geometry.location
    GMaps.geocode({
      address: toAddress,
      callback: toAddressDone,
    })
  }
}

// Initializing function
GMaps.geocode({
  address: fromAddress, // address object is defined globally
  callback: fromAddressDone,
})
</code></pre>
<h3>Promises</h3>
<p>While using named functions is a neat concept that is widely used, but keeping track of named function variables can get quite daunting, quite fast.</p>
<p>And there&#39;s no guarantee that those variables can&#39;t be overridden by other parts of our program.</p>
<p>For this reason and where we are sure about the flow of the data. We can use promises, which allows us to chain functions to achieve a desired state in our application.</p>
<p>Let&#39;s look at how we can initialize a promise</p>
<pre><code class="language-javascript">let promise = new Promise(function (resolve, reject) {
  // the executor function is executed
  // automatically when the promise is constructed

  // after 1 second signal that the job is
  // done with the result &quot;done&quot;
  setTimeout(() =&gt; resolve(&#39;done&#39;), 1000)
})
</code></pre>
<h3>Consumers</h3>
<p>Now the part where we chain the consumer functions
A Promise object serves as a link between the executor (the “producing code”) and the consuming functions, which will receive the result or error. Consuming functions can be registered (subscribed) using methods <code>.then</code>, <code>.catch</code> and <code>.finally</code>.</p>
<h4>then</h4>
<p>The most important, fundamental one is <code>.then</code>.</p>
<pre><code class="language-javascript">promise.then(
  function (result) {
    /* handle a successful result */
  },
  function (error) {
    /* handle an error */
  }
)
</code></pre>
<p>The first argument of <code>.then</code> is a function that runs when the promise is resolved, and receives the result.</p>
<p>The second argument of <code>.then</code> is a function that runs when the promise is rejected, and receives the error.</p>
<h4>catch</h4>
<p>If we’re interested only in errors, then we can use <code>null</code> as the first argument: <code>.then(null, errorHandlingFunction)</code>. Or we can use <code>.catch(errorHandlingFunction)</code>, which is exactly the same:</p>
<pre><code class="language-javascript">let promise = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; reject(new Error(&#39;Whoops!&#39;)), 1000)
})

// .catch(f) is the same as promise.then(null, f)
promise.catch(alert) // shows &quot;Error: Whoops!&quot; after 1 second
</code></pre>
<p>The call <code>.catch(f)</code> is a complete analog of <code>.then(null, f)</code>, it’s just a shorthand.</p>
<h4>finally</h4>
<p>Just like there’s a <code>finally</code> clause in a regular <code>try {...} catch {...}</code>, there’s <code>finally</code> in promises.</p>
<p>The call <code>.finally(f)</code> is similar to <code>.then(f, f)</code> in the sense that <code>f</code> always runs when the promise is settled: be it resolve or reject.</p>
<p><code>finally</code> is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed anymore, no matter what the outcome is.</p>
<p>Like this:</p>
<pre><code class="language-javascript">new Promise((resolve, reject) =&gt; {
  /* do something that takes time, and then call resolve/reject */
})
  // runs when the promise is settled
  // doesn&#39;t matter successfully or not
  .finally(() =&gt; stop loading indicator)
  // so the loading indicator is always
  // stopped before we process the result/error
  .then(result =&gt; show result, err =&gt; show error)
</code></pre>
<p>That said, <code>finally(f)</code> isn’t exactly an alias of <code>then(f,f)</code> though. There are few subtle differences:</p>
<ol>
<li><p>A <code>finally</code> handler has no arguments. In <code>finally</code> we don’t know whether the promise is successful or not. That’s all right, as our task is usually to perform “general” finalizing procedures.</p>
</li>
<li><p>A <code>finally</code> handler passes through results and errors to the next handler.</p>
<p>For instance, here the result is passed through <code>finally</code> to <code>then</code>:</p>
</li>
</ol>
<pre><code class="language-javascript">new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; resolve(&#39;result&#39;), 2000)
})
  .finally(() =&gt; alert(&#39;Promise ready&#39;))
  .then((result) =&gt; alert(result)) // &lt;-- .then handles the result
</code></pre>
<p>And here there’s an error in the promise, passed through <code>finally</code> to <code>catch</code>:</p>
<pre><code class="language-javascript">new Promise((resolve, reject) =&gt; {
  throw new Error(&#39;error&#39;)
})
  .finally(() =&gt; alert(&#39;Promise ready&#39;))
  .catch((err) =&gt; alert(err)) // &lt;-- .catch handles the error object
</code></pre>
<p>That’s very convenient, because <code>finally</code> is not meant to process a promise result. So it passes it through.</p>
<h2>Events</h2>
<p>Events are another solution to communicate when async callbacks finish executing. An object can become an emitter and publish events that other objects can listen for. This type of eventing is called the <strong>observer pattern</strong>.</p>
<blockquote>
<h2>The Event Loop is a queue of callback functions.</h2>
</blockquote>
<p>Browser JavaScript execution flow, as well as in Node.js, is based on an <em>event loop</em>.</p>
<p>Understanding how event loop works is important for optimizations, and sometimes for the right architecture.</p>
<p>In this chapter we first cover theoretical details about how things work, and then see practical applications of that knowledge.</p>
<h3>Event Loop</h3>
<p>The <em>event loop</em> concept is very simple. There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks.</p>
<p>The general algorithm of the engine:</p>
<ol>
<li>While there are tasks:<ul>
<li>execute them, starting with the oldest task.</li>
</ul>
</li>
<li>Sleep until a task appears, then go to 1.</li>
</ol>
<p>That’s a formalization for what we see when browsing a page. The JavaScript engine does nothing most of the time, it only runs if a script/handler/event activates.</p>
<p>Examples of tasks:</p>
<ul>
<li>When an external script <code>&lt;script src=&quot;...&quot;&gt;</code> loads, the task is to execute it.</li>
<li>When a user moves their mouse, the task is to dispatch <code>mousemove</code> event and execute handlers.</li>
<li>When the time is due for a scheduled <code>setTimeout</code>, the task is to run its callback.</li>
<li>…and so on.</li>
</ul>
<p>Tasks are set – the engine handles them – then waits for more tasks (while sleeping and consuming close to zero CPU).</p>
<p>It may happen that a task comes while the engine is busy, then it’s enqueued.</p>
<p>The tasks form a queue, so-called “macrotask queue” (v8 term):
<img src="https://ayushsingh.dev/async_queue.png" alt="tasks"></p>
<p>For instance, while the engine is busy executing a <code>script</code>, a user may move their mouse causing <code>mousemove</code>, and <code>setTimeout</code> may be due and so on, these tasks form a queue, as illustrated on the picture above.</p>
<p>Tasks from the queue are processed on “first come – first served” basis. When the engine browser is done with the <code>script</code>, it handles <code>mousemove</code> event, then <code>setTimeout</code> handler, and so on.</p>
<p>So far, quite simple, right?</p>
<p>Two more details:</p>
<ol>
<li>Rendering never happens while the engine executes a task. It doesn&#39;t matter if the task takes a long time. Changes to the DOM are painted only after the task is complete.</li>
<li>If a task takes too long, the browser can’t do other tasks, such as processing user events. So after a time, it raises an alert like “Page Unresponsive”, suggesting killing the task with the whole page. That happens when there are a lot of complex calculations or a programming error leading to an infinite loop.</li>
</ol>
<h2>Microtasks</h2>
<p>Along with <em>macrotasks</em>, described in this chapter, there are <em>microtasks</em>, mentioned in the chapter <a href="https://javascript.info/microtask-queue">Microtasks</a>.</p>
<p>Microtasks come solely from our code. They are usually created by promises: an execution of <code>.then/catch/finally</code> handler becomes a microtask. Microtasks are used “under the cover” of <code>await</code> as well, as it’s another form of promise handling.</p>
<p>There’s also a special function <code>queueMicrotask(func)</code> that queues <code>func</code> for execution in the microtask queue.</p>
<p><strong>Immediately after every <em>macrotask</em>, the engine executes all tasks from <em>microtask</em> queue, prior to running any other macrotasks or rendering or anything else.</strong></p>
<p>For instance, take a look:</p>
<pre><code class="language-javascript">setTimeout(() =&gt; alert(&#39;timeout&#39;))

Promise.resolve().then(() =&gt; alert(&#39;promise&#39;))

alert(&#39;code&#39;)
</code></pre>
<p>What’s going to be the order here?</p>
<ol>
<li><code>code</code> shows first, because it’s a regular synchronous call.</li>
<li><code>promise</code> shows second, because <code>.then</code> passes through the microtask queue, and runs after the current code.</li>
<li><code>timeout</code> shows last, because it’s a macrotask.</li>
</ol>
<p>The richer event loop picture looks like this (order is from top to bottom, that is: the script first, then microtasks, rendering and so on):
<img src="https://ayushsingh.dev/detailed_async_queue.png" alt="tasks2"></p>
<p>All microtasks are completed before any other event handling or rendering or any other macrotask takes place.</p>
<p>That’s important, as it guarantees that the application environment is basically the same (no mouse coordinate changes, no new network data, etc) between microtasks.</p>
<p>If we’d like to execute a function asynchronously (after the current code), but before changes are rendered or new events handled, we can schedule it with <code>queueMicrotask</code>.</p>
<h1>Summary</h1>
<p>A more detailed event loop algorithm (though still simplified compared to the <a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model">specification</a>):</p>
<ol>
<li>Dequeue and run the oldest task from the <em>macrotask</em> queue (e.g. “script”).</li>
<li>Execute all <em>microtasks</em>:<ul>
<li>While the microtask queue is not empty:<ul>
<li>Dequeue and run the oldest microtask.</li>
</ul>
</li>
</ul>
</li>
<li>Render changes if any.</li>
<li>If the macrotask queue is empty, wait till a macrotask appears.</li>
<li>Go to step 1.</li>
</ol>
<p>To schedule a new <em>macrotask</em>:</p>
<ul>
<li>Use zero delayed <code>setTimeout(f)</code>.</li>
</ul>
<p>That may be used to split a big calculation-heavy task into pieces, for the browser to be able to react to user events and show progress between them.</p>
<p>Also, used in event handlers to schedule an action after the event is fully handled (bubbling done).</p>
<p>To schedule a new <em>microtask</em></p>
<ul>
<li>Use <code>queueMicrotask(f)</code>.</li>
<li>Also promise handlers go through the microtask queue.</li>
</ul>
<p>There’s no UI or network event handling between microtasks: they run immediately one after another.</p>
<p>So one may want to <code>queueMicrotask</code> to execute a function asynchronously, but within the environment state.</p>
<p>In most Javascript engines, including browsers and Node.js, the concept of microtasks is closely tied with the “event loop” and “macrotasks”. As these have no direct relation to promises, they are covered in another part of the tutorial, in the article <a href="https://javascript.info/event-loop">Event loop: microtasks and macrotasks</a>.</p>
<h1>References</h1>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">Microtasks</a></li>
<li><a href="https://javascript.info/microtask-queue">MicroTasks</a></li>
<li><a href="https://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027">Async in JS</a></li>
<li><a href="https://pragprog.com/titles/tbajs/async-javascript/">Book to read</a></li>
<li><a href="https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers">HTML Spec</a></li>
<li><a href="https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0?gi=ddcc7a43e294">Understanding Execution</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>I love Rust?</title>
      <link>https://ayushsingh.dev/blog/i-love-rust</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/i-love-rust</guid>
      <pubDate>Mon, 26 Apr 2021 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>New found love for rust lang</description>
      <content:encoded><![CDATA[<p>I&#39;ve been learning rust for quite some time now and It&#39;s the best decision I&#39;ve made in a while.
For learning this language I&#39;ve only gone through <a href="https://doc.rust-lang.org/book/">The Book</a>. It&#39;s the best resource to learn this language. I&#39;ve also picked few useful stuff while going through this book.</p>
<ul>
<li>UTF-8 grapheme clusters.</li>
<li>Ownership and lifetimes.</li>
<li>Closures</li>
</ul>
<p>The concepts above are new to me. And I really had fun learning them. To be honest I found rust much better than Dart and Swift. And I don&#39;t think I&#39;ll let go of this language anytime soon.</p>
<p>Also I&#39;ve ditched the whole Nuxt.js bandwagon. It was fine, but I really didn&#39;t needed it. Now the whole website is static. Just like it should&#39;ve be from the beginning.</p>
<p>Anyway I have COVID. I&#39;ve lost taste and smell. Rest everything is fine.</p>
<p>Till then, take care.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Too Many Open Items</title>
      <link>https://ayushsingh.dev/blog/too-many-open-items</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/too-many-open-items</guid>
      <pubDate>Tue, 15 Dec 2020 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>Reducing the number of Open Items I currently have</description>
      <content:encoded><![CDATA[<p>Hi,
I have a problem. A big problem. I currently have too many projects open on my plate and I&#39;m neither efficient nor happy about it.
The recommended number of projects an individual can handle at a time is 3 or as much as one can efficiently manage [<a href="https://www.researchgate.net/publication/285549936_Concurrent_projects_How_many_can_you_handle">Research Paper</a>, <a href="https://opentextbc.ca/projectmanagement/chapter/chapter-11-resource-planning-project-management/">Project Management openbook</a>] and I&#39;m just a mess at managing stuff right now.
Let me list out the major areas I&#39;m currently wasting time in:</p>
<ul>
<li>Books</li>
<li>Application Projects</li>
<li>New Languages</li>
<li>New Frameworks</li>
</ul>
<h3>Books</h3>
<p>So the number of books is not huge for any well read individual, but the problem is I&#39;m try to read all of them at once, and that&#39;s mixing up storylines, ideas and key takeaways..
Currently I&#39;m reading:</p>
<ul>
<li>Triggers: Creating Behavior That Lasts - Marshall Goldsmith</li>
<li>The F*ck It Diet: Eating should be easy - Caroline Dooner</li>
<li>Art of Captivating conversation - Patrick King</li>
<li>The Prince of Milk - exurb1a</li>
<li>Cracking the Coding Interview - Gayle Laakmann McDowell</li>
</ul>
<p>And I listening to:</p>
<ul>
<li>Deep Work - Cal Newport [3rd Time]</li>
<li>The Optimist&#39;s Telescope - Bina Venkataraman</li>
</ul>
<h3>Application Projects</h3>
<p>I currently have 11 ongoing projects, including this blog; four of those are full size projects with their separate trello boards to keep track of all the bullshit I do with them on regular basis.</p>
<p><img src="https://ayushsingh.dev/too_many_projects_1.png" alt="tbh there are more than 4 projects"></p>
<p>And all of them take too much time to develop. One thing I do regularly is ask a simple question which derails all the work I&#39;ve done till now a and I start writing the whole application again is that, &quot;What new languages, frameworks are available right now in the market?&quot;
This brings us to the next section..</p>
<h3>New Languages</h3>
<p>I&#39;m currently trying to learn..</p>
<ul>
<li>Rust - personal reasons</li>
<li>Dart - personal reasons</li>
<li>Swift
Don&#39;t ask how but these have just taken over my life currently.</li>
</ul>
<h3>New Frameworks</h3>
<p>The reason, from my understanding, why I have picked up so many frameworks at once is that I have so many projects that have different need that can only be fulfilled by combination of these frameworks..</p>
<ul>
<li><a href="https://tailwindcss.com/docs">TailwindCSS</a></li>
<li><a href="https://bulma.io/">BulmaCSS</a></li>
<li><a href="https://flutter.dev/">Flutter</a></li>
<li><a href="https://tokio.rs/">Tokio</a> : Rust</li>
<li><a href="https://github.com/vitejs/vite">Vite</a> (Vue 3)</li>
<li><a href="https://nuxtjs.org/">Nuxt.JS</a> (Vue 2)</li>
<li><a href="https://kubernetes.io/">Kubernetes</a> [with all the supporting stack]</li>
<li><a href="https://material-ui.com/">Material-UI</a> (React)</li>
</ul>
<p>And I need time to process and internalize all of this information while I also listen to podcasts, youtube videos, etc.
Tbh I&#39;m burnt out.</p>
<p>In the moment all of this feels important and no sh*t <strong>IT IS</strong>. I&#39;ve tried all the ways under the sun where I can manage all of these at once, but I think I&#39;ve already hit a limit of my brain and no tool can help me with that.</p>
<p>And all of this happens after all the work I do at my job.. which is way more streamlined than this but it&#39;s still big..
At work currently I&#39;m trying to integrate the payment systems for Stripe, Android InApp Purchases and iOS InApp Purchases, Both Backend and Frontend (React, Android, iOS, Node).</p>
<p>You can only do so much at a time.</p>
<blockquote>
<p>Triage is important and should be done, but rarely and carefully otherwise the cost of complacency is huge.
I can explain why I&#39;ve decided to limit myself to work stuff and the following things:</p>
</blockquote>
<ul>
<li>Youtube Music</li>
<li>Cracking the Coding Interview - Gayle Laakmann McDowell</li>
<li>Flutter
But I won&#39;t. Ask me if you&#39;re curious.</li>
</ul>
<p>Rest everything is shelved now. I&#39;ll pick them up later on.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Russell&apos;s Paradox</title>
      <link>https://ayushsingh.dev/blog/russells-paradox</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/russells-paradox</guid>
      <pubDate>Mon, 07 Sep 2020 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>How a man destroyed one logicians dream to unify all the branches of mathematics.</description>
      <content:encoded><![CDATA[<p>So this is a super interesting story. It&#39;s about SET theory and basis of all of mathematics. So IDK how you&#39;ll respond. But whatever...</p>
<p>So it all started with the two greatest chums who seem to have touched every topic on earth, Plato and Aristotle.</p>
<p>It was 387 BC and Plato was chilling in <strong>Akademia</strong>[The academy founded by Plato. <a href="https://en.wikipedia.org/wiki/Platonic_Academy">Platonic Academy</a>]. He was going about his day messing with his students and philosophers after 2000 years from his time, a bloke came to him and asks him a simple question &quot;What are numbers&quot;, he got up and then went inside and started having a lukewarm mental breakdown.</p>
<p>After some time he comes out of the Akademia with <a href="https://plato.stanford.edu/entries/platonism-mathematics/">The Philosophy of Mathematics</a>.</p>
<p>His philosophy basically said. &quot;There are objects and there are forms. And numbers and the relations between them (like addition and stuff) are independent of us and objects of the real world and are in turn objects of world of forms. And we just relate to those objects from world of forms cause they allow us to define our world.&quot;</p>
<p>Plato was happy about his explanation, but there was one guy who took that definition not well to his heart, that was his star student Aristotle. Aristotle said there no other world than this, that old man is clearly out of his mind. I can&#39;t really tell.</p>
<p>So now he went inside Akademia and had his own version of mental breakdown.</p>
<blockquote>
<p>Having mental breakdowns was cool back then - Diogenes.</p>
</blockquote>
<p>So he comes out with his own theory about <a href="https://home.uchicago.edu/~jlear/docs/Aristotle's%20Philosophy%20of%20Mathematics.pdf">numbers</a>. It goes something like this..</p>
<p>&quot;There are objects in the world and objects have properties and one of the property of the object is a number attached to it. If you see a cube the number of surfaces is the property of the object.&quot; - this is what he said in a really broad sense.</p>
<p>And then both of them forgot about this little topic and went on to f@%k with the rest of philosophical society for lulz.</p>
<p>Fast forward to 1870&#39;s. Time was wild. First headphone jack was invented, by the way that design is still used to this day. Edison created a light thingy. Bell created phone. <a href="https://en.wikipedia.org/wiki/1870s_in_Western_fashion">Fashion</a> was shit.</p>
<p>In Germany there was a guy named <a href="https://en.wikipedia.org/wiki/Gottlob_Frege">Gottlob Frege</a>. And he was pissed. He was not happy about how Plato and Aristotle did not do their job properly and never reached a conclusion regarding the deal about numbers.</p>
<p>To be honest he just got stuck with the words <strong>&quot;Some&quot;</strong> and <strong>&quot;All&quot;</strong>, like a dedicated math freak after getting some good kush. He raised questions about the definition that Aristotle gave out. &quot;Numbers being properties of an object&quot;.</p>
<p>He said, &quot;If numbers were the properties of object then A single (1) bouquet and A group 25 of flowers shouldn&#39;t be the same thing. And if in-fact they are same, then an object should be having multiple &#39;&#39;number properties&#39; attached to it and that doesn&#39;t make any sense.&quot;</p>
<p>He then went ahead and proposed his own idea about what numbers are. He said - &quot;Numbers are extensions to a concept. And a concept can be anything you want.&quot;</p>
<ul>
<li><p>all the cats you know</p>
</li>
<li><p>all the cats you don&#39;t know</p>
</li>
<li><p>all the dogs you know</p>
</li>
<li><p>all the dogs you don&#39;t know</p>
</li>
<li><p>wheels in your house</p>
</li>
<li><p>rats in your house</p>
</li>
<li><p>all the yellow birds in Amazon forest</p>
</li>
<li><p>etc..</p>
</li>
</ul>
<p>So once you define a concept you can just go ahead and assign a number to that concept. And that number can be zero/infinity, whatever you want.</p>
<p>He was damm pleased with his explanations. And was about get them published. But then, an ultimate savage from Britain[<a href="https://en.wikipedia.org/wiki/Bertrand_Russell">Bertrand Russell</a> The ultimate savage.] wrote Frege a letter. Stating that - &quot;He loves his work and everything he formulated till now is wonderful, but there is one point Frege missed.&quot;</p>
<p>Okay this is little tricky, But bear with me on this one..</p>
<p><strong>&quot;Let us call a set &#39;Normal&#39; if it is not a member of itself, and &#39;Abnormal&#39; if it is a member of itself.&quot;</strong></p>
<p>Simple? Read it again if it&#39;s not settled in your brain.</p>
<p><strong>Now consider a Variable R and assume it is a set of all the &#39;Normal&#39; sets.</strong></p>
<p>Nothing wrong there? now determine whether R is normal or abnormal.</p>
<p>There are two scenarios, R is normal or R is abnormal.</p>
<p>If <strong>R</strong> is normal then <strong>R</strong> would contain itself since that&#39;s how we defined <strong>R</strong> - [set of all normal sets] and that would make <strong>R</strong> abnormal cause that&#39;s how we defined &#39;abnormal&#39;.</p>
<p>And if <strong>R</strong> is abnormal then <strong>R</strong> would would be a member of a set whose members are normal cause that&#39;s how we defined <strong>R</strong>.</p>
<p>Thus <strong>R</strong> is neither normal or abnormal. It&#39;s just there to mess with your brain.</p>
<p>This paradox literally caused him to go to hospital. You can search for Barber&#39;s paradox for similar kind of reasoning.</p>
<p>Later on we move away from Ferge&#39;s theory to <a href="https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory">Zermelo–Fraenkel set theory</a>. This theory is built in a way, that it just avoids this paradox. And there are contenders to this theory as well[<a href="https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory#Criticisms">Criticisms</a>]. So let&#39;s see what happens in future.</p>
<p>PS: I learned about this paradox from <a href="https://www.youtube.com/watch?v=xauCQpnbNAM">Jades Video</a>. I would highly suggest you to go and watch her. As she explains this in much more detail and much more effortlessly.</p>
<p>In this sort of informal story I took many artistic licences and made up a lot of stuff. Do come and shout on me at <a href="https://twitter.com/haloboy777">twitter</a> if I made any mistake.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Zettelkasten</title>
      <link>https://ayushsingh.dev/blog/must-have-tags</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/must-have-tags</guid>
      <pubDate>Thu, 27 Aug 2020 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>How tags and atomic notes helps to organise and collect data at monumental speed.</description>
      <content:encoded><![CDATA[<p>The way we organize notes in <strong>&#39;Indian Education System&#39;</strong> is just bullshit. From the beginning of my time I was taught to blindly copy the stuff which was written on the classroom board.</p>
<p>To be honest I&#39;ve struggled with this a lot. I&#39;ve had so many problems with this method</p>
<ul>
<li>You essentially write down everything that was spoken to you and try to keep up with the teachers ability to read his/her notes. Do try if you&#39;re feeling adventurous.</li>
<li>The notes you make during your childhood were never meant to be used by the adult you. I find that really frustrating. I mean if by making notes, we are organizing facts and ideas in a way to be used later by the future self, why not make those notes useful for the rest of one&#39;s life.</li>
<li>Whenever we come across a new PRIMARY SOURCE, we tend to ignore it completely and try to search for some ways where we can find the condensed information regarding that PRIMARY SOURCE, like a guide or summary.</li>
<li>And there is little to no way to tell if there has been a update regarding a topic, if the PRIMARY SOURCE was first published in 1863. NO GOES AROUND SEARCHING FOR FOLLOW-UPS. It should be available with the PRIMARY SOURCE linked with it as [Updates].</li>
</ul>
<p>For the last 3-4 months I&#39;ve been researching on the ways I can organize my thoughts and findings. I&#39;ve already looked at the following</p>
<ul>
<li>Have folders within folders to organize hierarchical data.</li>
<li>Have lots of files with the ability to search.</li>
<li>Have small index card which essentially have atomic information.</li>
<li>Or have tags.</li>
</ul>
<p>Tags have a special ability to link multiple facts and ideas, in a very simple and easy way. Whenever you find/produce a new piece of information, you just need to tag it.</p>
<p>Whether be it a link to a video or a long piece of article you wrote. You can find both of them later on super easily just by looking at a common tag. And these pieces of information can be found somewhere else also if more tags are attached to them.</p>
<p>And to give you some background, the use of tags predates computer storage. <a href="https://en.wikipedia.org/wiki/Paper_data_storage" title="Paper data storage">Paper data storage</a> devices, notably <a href="https://en.wikipedia.org/wiki/Edge-notched_card" title="Edge-notched card">edge-notched cards</a>, that permitted classification and sorting by multiple criteria were already in use prior to the twentieth century, and <a href="https://en.wikipedia.org/wiki/Faceted_classification" title="Faceted classification">faceted classification</a> has been used by libraries since the 1930s.</p>
<p>I&#39;ve come to terms with the fact that the fastest and easiest way to organize information is by using <a href="https://en.wikipedia.org/wiki/Zettelkasten">Zettelkasten</a> and tags.</p>
<blockquote>
<p>Both the ideas compliment each other so much that I instantly fell in love with it.</p>
</blockquote>
<p>For the uninitiated, Zettelkasten is the method of recording information in its atomic form, and linking those bits of information to create whole topic. This way all the complex topics in this world can be boiled down to basic bits of information. And you link those bits of information with direct links and tags. A good resource for learning more about zettelkasten, is <a href="https://zettelkasten.de/">here</a>.</p>
<p>One can argue that having a global fuzzy search might yield the same result. I agree you might be able to find the specific information/knowledge with a global search but tags offer you much more than that, tags bring networked knowledge to the table.</p>
<p>You can look at a tag and multiple data points come with their own tags and you can then follow them to find insights which you might not have been able to figure out if you just used search.</p>
<p>I still need to research how should one organize tags. Should one use hierarchy to organize them or just organize them alphabetically?</p>
<p>I want to implement tagging for my blog also, it would be fun, I think.</p>
<p>Stay at home. Stay safe.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Nuxt.js 404 Static page</title>
      <link>https://ayushsingh.dev/blog/nuxtjs-static-fallback</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/nuxtjs-static-fallback</guid>
      <pubDate>Tue, 28 Jul 2020 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>How to configure Nuxt.js to handle 404 error in static mode.</description>
      <content:encoded><![CDATA[<p>Hello,</p>
<p>So this one took a long time to figure out. And I went so many places to find a fix this one. To be honest I wasn&#39;t looking that text/htmlmuch.</p>
<p>I&#39;ll spare you all the hacks I did. Turns out the solution was dead easy.</p>
<h4>Steps</h4>
<ul>
<li><p>First open your nuxt.config.[js|ts] and specify the <code>fallback</code> page there</p>
<pre><code class="language-js">export default {
  // Other Stuff
  generate: {
    fallback: &#39;404.html&#39;,
  },
}
</code></pre>
</li>
<li><p>Run <code>npm run generate</code> to generate all the static files, it will generate the dist folder.</p>
</li>
<li><p>Copy the dist folder to the root of your site.</p>
</li>
<li><p>Then go to your nginx config and tell it to serve this specific 404 page, assuming that the root of the server has all the files from dist.</p>
<pre><code class="language-nginx">server {
# routes and certificates
  error_page 404 /404.html;
}
</code></pre>
</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Hello World</title>
      <link>https://ayushsingh.dev/blog/hello</link>
      <guid isPermaLink="true">https://ayushsingh.dev/blog/hello</guid>
      <pubDate>Sat, 18 Jul 2020 00:00:00 GMT</pubDate>
      <author>hi@ayushsingh.dev (Ayush Kumar Singh)</author>
      <description>New Blog. Trying to achieve minimalism.</description>
      <content:encoded><![CDATA[<p>Hey all,</p>
<p>So I&#39;ve created a new blog. And it&#39;s made using tech and standards I love, namely:</p>
<ul>
<li>Vue.js (Nuxt.js)</li>
<li>Markdown</li>
<li>Plain old HTML CSS</li>
</ul>
<p>I have some ideas that I would like to implement to the blog. Like having a way to categorize on the basis of tags, dates and authors.</p>
<p>The thing I am most happy about is the dark theme switcher. If you would have noticed, the blog automatically picked up your devices preference of dark mode and applied it.</p>
<blockquote>
<p>Pretty cool if you ask me.</p>
</blockquote>
<p>Anyways, I&#39;m planning to write posts on software development, politics and bunch of other stuff. And that&#39;s the reason I need tags.</p>
<p>I&#39;ll also expand upon how tags are different from categories and how you can utilize them most efficiently.</p>
<p>Till then, take care.</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
