<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Striker on Medium]]></title>
        <description><![CDATA[Stories by Striker on Medium]]></description>
        <link>https://medium.com/@striker-aryu56?source=rss-61742cf1b984------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rwlxbBK23faE1R1Oomxz4A.jpeg</url>
            <title>Stories by Striker on Medium</title>
            <link>https://medium.com/@striker-aryu56?source=rss-61742cf1b984------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:21:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@striker-aryu56/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A 5-Minute Hack to Make Claude Code and Codex More Productive]]></title>
            <link>https://striker-aryu56.medium.com/a-5-minute-hack-to-make-claude-code-and-codex-more-productive-8704ca81d618?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/8704ca81d618</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 08:07:46 GMT</pubDate>
            <atom:updated>2026-06-02T16:17:57.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXjDNlkr-0qIi-YfswfJoA.png" /></figure><p>When working with AI coding agents in the CLI, it’s common to switch tabs, grab a coffee, or focus on something else while the agent works.</p><p>The problem? You don’t always know when the agent is waiting for your approval or when it has finished its task.</p><p>Most desktop apps solve this with audio notifications, but CLI-based agents often leave you staring at the terminal or repeatedly checking back for updates.</p><p>By setting up simple sound hooks, you’ll hear a notification whenever the agent needs your attention or completes a task, allowing you to stay productive without constantly watching the terminal.</p><p><strong>Note:</strong> The instructions in this article were tested on <strong>macOS</strong>. Linux and Windows users will need to adjust the sound playback commands accordingly.</p><h3>Option 1: Let the Agent Configure It</h3><p>The easiest approach is to ask the agent to configure itself.</p><h3>Claude Code</h3><p>Paste the following prompt into Claude Code:</p><pre>Set up (or update) notification sound hooks in my ~/.claude/settings.json.<br><br>1. List the files in /System/Library/Sounds and play a few so I can hear them.<br>2. Ask me — using your question/selection UI — which sound to use for the &quot;approval/input needed&quot; event and which for the &quot;turn finished&quot; event. Offer the full list as options.<br>3. After I pick, play my two chosen sounds back to me with afplay and tell me which is which (e.g. &quot;approval = Glass, finish = Bottle&quot;). If I don&#39;t like them, let me re-pick before writing anything.<br>4. Once confirmed, write the hooks (merge, don&#39;t clobber existing keys like model/enabledPlugins):<br>   - &quot;Notification&quot; event -&gt; /usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/&lt;my approval sound&gt; &gt;/dev/null 2&gt;&amp;1 &amp;<br>   - &quot;Stop&quot; event -&gt; /usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/&lt;my finish sound&gt; &gt;/dev/null 2&gt;&amp;1 &amp;<br>   Both with timeout 2 and an empty matcher.<br>   If these hooks already exist, just replace the sound file paths instead of adding duplicates.<br>5. Validate the JSON with jq, then tell me to run /hooks (or restart) to activate.</pre><h3>Codex</h3><p>Paste this prompt into Codex:</p><pre>Set up (or update) notification sound hooks in my ~/.codex/config.toml.<br><br>1. List the files in /System/Library/Sounds and play a few so I can hear them.<br>2. Ask me which sound to use for the &quot;approval needed&quot; (PermissionRequest) event and which for the &quot;turn finished&quot; (Stop) event. Offer the full list as options.<br>3. After I pick, play my two chosen sounds back to me with afplay and tell me which is which (e.g. &quot;approval = Glass, finish = Bottle&quot;). If I don&#39;t like them, let me re-pick before writing anything.<br>4. Once confirmed, write the hooks (append, don&#39;t remove existing config):<br>   - [[hooks.PermissionRequest]] matcher &quot;.*&quot; -&gt; /usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/&lt;my approval sound&gt; &gt;/dev/null 2&gt;&amp;1 &amp;<br>   - [[hooks.Stop]] -&gt; /usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/&lt;my finish sound&gt; &gt;/dev/null 2&gt;&amp;1 &amp;<br>   Both with timeout 2 and a statusMessage.<br>   If these hooks already exist, just replace the sound file paths instead of adding duplicates.<br>5. Then tell me to restart Codex and trust the hooks via /hooks.</pre><p>The agent can handle both first-time setup and future sound changes.</p><h3>Option 2: Configure It Manually</h3><h3>Claude Code</h3><p>Open:</p><pre>~/.claude/settings.json</pre><p>Add:</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;Notification&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;&quot;,<br>        &quot;hooks&quot;: [<br>          {<br>            &quot;type&quot;: &quot;command&quot;,<br>            &quot;command&quot;: &quot;/usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/Glass.aiff &gt;/dev/null 2&gt;&amp;1 &amp;&quot;,<br>            &quot;timeout&quot;: 2,<br>            &quot;statusMessage&quot;: &quot;Playing approval sound&quot;<br>          }<br>        ]<br>      }<br>    ],<br>    &quot;Stop&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;&quot;,<br>        &quot;hooks&quot;: [<br>          {<br>            &quot;type&quot;: &quot;command&quot;,<br>            &quot;command&quot;: &quot;/usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/Bottle.aiff &gt;/dev/null 2&gt;&amp;1 &amp;&quot;,<br>            &quot;timeout&quot;: 2,<br>            &quot;statusMessage&quot;: &quot;Playing stop sound&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>Validate the configuration:</p><pre>jq -e &#39;.hooks.Notification[].hooks[].command, .hooks.Stop[].hooks[].command&#39; ~/.claude/settings.json</pre><p>Activate by running:</p><pre>/hooks</pre><p>or restart Claude Code.</p><h3>Codex</h3><p>Create or edit:</p><pre>~/.codex/config.toml</pre><p>Add:</p><pre>[[hooks.PermissionRequest]]<br>matcher = &quot;.*&quot;</pre><pre>[[hooks.PermissionRequest.hooks]]<br>type = &quot;command&quot;<br>command = &quot;/usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/Glass.aiff &gt;/dev/null 2&gt;&amp;1 &amp;&quot;<br>timeout = 2<br>statusMessage = &quot;Playing approval sound&quot;</pre><pre>[[hooks.Stop]]</pre><pre>[[hooks.Stop.hooks]]<br>type = &quot;command&quot;<br>command = &quot;/usr/bin/nohup /usr/bin/afplay /System/Library/Sounds/Bottle.aiff &gt;/dev/null 2&gt;&amp;1 &amp;&quot;<br>timeout = 2<br>statusMessage = &quot;Playing stop sound&quot;</pre><p>Restart Codex after saving.</p><p>The first time, Codex may ask you to trust the new hooks. Approve them through:</p><pre>/hooks</pre><h3>Testing</h3><p>Verify that sound playback works:</p><pre>afplay /System/Library/Sounds/Bottle.aiff</pre><p>If you hear the sound, the setup is functioning correctly.</p><h3>Customizing Sounds</h3><p>macOS ships with several built-in sound effects.</p><p>View available options:</p><pre>ls /System/Library/Sounds</pre><p>Popular choices include:</p><ul><li>Glass</li><li>Bottle</li><li>Ping</li><li>Hero</li><li>Pop</li><li>Submarine</li></ul><p>Simply replace the sound file name in the hook command to switch sounds.</p><h3>How It Works</h3><p>The hooks trigger simple shell commands:</p><ul><li><strong>Approval Request</strong> → plays Glass.aiff</li><li><strong>Task Completion</strong> → plays Bottle.aiff</li></ul><p>The command uses:</p><pre>nohup ... &amp;</pre><p>to run in the background so the agent doesn’t wait for the sound to finish.</p><p>Output is redirected to:</p><pre>&gt;/dev/null 2&gt;&amp;1</pre><p>to keep logs and terminal output clean.</p><h3>Final Thoughts</h3><p>This is a tiny quality-of-life improvement, but it makes a surprisingly big difference when working with AI coding agents. Instead of constantly checking the terminal, you can focus on other tasks and let audio cues tell you when the agent needs attention or has finished its work.</p><p>A few minutes of setup can make long coding sessions much more comfortable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8704ca81d618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building My Home Server from an Old Laptop]]></title>
            <link>https://striker-aryu56.medium.com/building-my-home-server-from-an-old-laptop-3d5936caba5f?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d5936caba5f</guid>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 11:22:53 GMT</pubDate>
            <atom:updated>2026-01-14T18:02:12.222Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>— <br>Title: Building Home Server<br>Date: 02–10–2025<br> — <br>Tags:</strong> server, ssh, ubuntu, NAS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8LR2iawmi_RLRyy2" /><figcaption><strong>Building Home Server</strong></figcaption></figure><p>A few months ago, I noticed my old laptop lying in the corner, untouched and gathering dust. It wasn’t powerful enough for my daily work anymore, but I didn’t feel like throwing it away either. That’s when the idea struck me: why not turn it into a home server?</p><p>I wiped everything off, installed a fresh copy of Ubuntu Server, and slowly started experimenting. At first, it was just about getting the basics running, but one thing led to another. Soon, I had a NAS for file storage, AdGuard to block ads across my network, a media server for streaming, a VPN for secure browsing, and even a place to run some of my own apps.</p><p>This blog covers how I set things up, the tools I used, and some lessons I picked up along the way. If you’ve got an old machine lying around, this might give you a reason to bring it back to life.</p><h3>Base Ubuntu Server Setup</h3><p>I won’t go too deep into the installation here (that probably deserves its own blog — let me know if you’d like one). If you’re new, you can follow this reference <a href="https://www.youtube.com/watch?v=2Btkx9toufg">video</a> — it’s a solid guide for installing Ubuntu Server. Just watch until the installation part if that’s all you need, or continue further if you want a deeper dive. Here’s a quick outline of the steps you’ll likely follow:</p><ul><li>Created a flash drive with the Ubuntu Server image.</li><li>Logged into BIOS and changed boot order.</li><li>Booted from USB and installed Ubuntu with mostly default values.</li><li>Chose DHCP for network initially (later switched to static IP).</li><li>Selected the laptop’s drive for installation.</li></ul><h3>SSH Setup</h3><p>First things first — let’s make this laptop feel like a real server by setting up SSH. This way, I can connect remotely without ever needing to touch it physically.</p><h4>Install SSH Server</h4><pre>sudo apt update &amp;&amp; sudo apt install openssh-server -y</pre><ul><li>Check status: systemctl status sshd</li><li>By default, it should start automatically.</li></ul><h4>Change Default SSH Port</h4><ul><li>Open the SSH config: sudo vi /etc/ssh/sshd_config</li><li>Find the line with #Port 22, uncomment it, and change it to something non-default, e.g.: Port 2222</li></ul><p>This helps avoid random automated attacks.</p><h4>Disable Password Authentication</h4><ul><li>Still in sshd_config, set: PasswordAuthentication<em>, </em>This ensures only key-based logins work — much safer.</li></ul><p><em>Sometimes you also need to update </em><em>/etc/ssh/sshd_config.d/50-cloud-init.conf.</em></p><h4>Add Your Public Key</h4><ul><li>On your <strong>client machine</strong>, generate a key if you don’t already have one:<br>ssh-keygen -t ed25519 -C “your_email@example.com”</li><li>Then copy it to the server:<br>ssh-copy-id -i ~/.ssh/id_ed25519.pub &lt;your-username&gt;@server-ip -p 2222 <strong>(Note:</strong> <strong>The steps below include ways to find your server’s IP address.)</strong></li><li>This adds your key to ~/.ssh/authorized_keys on the server.</li></ul><p>In the End Restart SSH Server sudo systemctl reload sshd, Now you can try connecting like this: ssh &lt;your-username&gt;@server-ip -p 2222</p><p>After setting up SSH keys, you might still not be able to connect from your client. That’s usually because of the firewall or changing IP addresses. To make things smooth, we’ll:</p><ol><li>Assign a <strong>static IP</strong> to the server.</li><li>Open the correct ports in the firewall.</li><li>Configure the client for easy SSH access.</li></ol><h4>Step 1: Find Your Current IP</h4><p>Before setting a static IP, you need to know your network interface and current IP. Here are a few ways:</p><ol><li>Using ip command: ip addr show. Look for inet under your ethernet interface (e.g., enp4s0).</li><li>Using ifconfig (may need sudo apt install net-tools):</li><li>Using<strong> </strong>hostname -I:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anu1O1Bqb51w3Zou-HZU-A.png" /><figcaption>Using ifconfig</figcaption></figure><p>This shows all IPs assigned to the machine.</p><h4>Step 2: Set a Static IP and Connect to wifi</h4><p>Connect to your router and pick an available IP. Usually, numbers at the higher end of the subnet (like .7, .100, etc.) are free. Then edit your netplan config (/etc/netplan/01-netcfg.yaml or similar):</p><pre>network:<br>  version: 2<br>  renderer: networkd<br>  ethernets:<br>    enp4s0:<br>      addresses:<br>        - 192.168.1.7/24<br>      gateway4: 192.168.1.1<br>      nameservers:<br>        addresses:<br>          - 8.8.8.8<br>          - 8.8.4.4<br>  wifis:<br>    wlan0:<br>      addresses:<br>        - 192.168.1.50/24       # your static Wi-Fi IP<br>      gateway4: 192.168.1.1     # usually same as router<br>      nameservers:<br>        addresses:<br>          - 8.8.8.8<br>          - 8.8.4.4<br>      access-points:<br>        &quot;Your_SSID&quot;:<br>          password: &quot;YourPassword&quot;</pre><p>Apply the new configuration: sudo netplan apply</p><p>Now your server will always have the same IP, which makes connecting much easier.|</p><h4>Step 3: Configure the Client</h4><p>On your client machine, you can simplify SSH access by creating ~/.ssh/config:</p><pre>Host MyServer<br>    HostName 192.168.1.7<br>    User your-username<br>    Port 2222      # or the port you set for SSH<br>    IdentityFile ~/.ssh/id_ed25519</pre><p>After this, you can connect simply with: ssh MyServer</p><h4>Step 4: Configure Firewall</h4><p>Ubuntu uses <strong>UFW </strong>to manage access.</p><ul><li>Enable/disable UFW:</li></ul><pre>sudo ufw enable<br>sudo ufw disable</pre><ul><li>Allow SSH (default port or custom port):</li></ul><pre>sudo ufw allow ssh           # if using default port 22<br>sudo ufw allow 2222/tcp      # replace 2222 with your custom SSH port</pre><ul><li>Check firewall status: sudo ufw status</li></ul><p>With a static IP and firewall configured, your SSH connection should work reliably from your client.</p><p>Alright, enough of the setup — let’s get into the good stuff.</p><h3>Network Storage (NAS with Samba)</h3><p>So, what’s the point of a NAS? Think of it like your personal cloud — a drive you can connect to from multiple devices at the same time, without messing with wires or constantly plugging in drives.</p><p>Before setting up the NAS, I mounted a 50GB external drive on my server. I recommend doing the same so that your operating system runs on a separate drive, and the mounted drive can be fully dedicated for storage.</p><h4>Step 1: Identify and Prepare the Drive</h4><ol><li>Check available storage: lsblk</li><li>Find the drive you want to use (e.g., /dev/sda).</li><li>If the drive has existing partitions, clear them:</li></ol><pre>sda<br>|<br>--sda1<br>--sda2<br><br># Command to clear this<br>sudo wipefs -a &lt;drive path&gt;<br># eg.<br>sudo wipefs -a /dev/sda</pre><blockquote><strong><em>Note: Moving Forward Please use your own drive path instead of</em></strong><em> </em><em>/dev/sda.</em></blockquote><h4>Step 2: Create a Partition</h4><ol><li>Start partitioning: sudo gdisk /dev/sda</li><li>Commands in gdisk:</li></ol><ul><li>n → create new partition</li><li>Accept defaults to use the entire drive</li><li>w → write changes</li><li>y → confirm</li></ul><ol><li>Verify the partition: sudo gdisk -l /dev/sda</li></ol><h4>Step 3: Format the Partition</h4><p>Create an ext4 filesystem: sudo mkfs.ext4 /dev/sda1</p><ul><li>If prompted about an existing filesystem, type y.</li></ul><h4>Step 4: Mount the Partition</h4><ul><li>Go to /mnt and create a folder:</li></ul><pre>cd /mnt<br>sudo mkdir data</pre><ul><li>Make the folder immutable (optional, prevents accidental deletion):</li></ul><pre>sudo chattr +i data</pre><ul><li>Find the UUID of your partition:</li></ul><pre>sudo blkid /dev/sda1<br><br># eg.<br>/dev/sda1: UUID=&quot;b2e62f4f-d338-470e-9ae7-4fc0e014858c&quot; TYPE=&quot;ext4&quot;<br><br># Copy<br>UUID=&quot;b2e62f4f-d338-470e-9ae7-4fc0e014858c&quot;</pre><ul><li>Edit /etc/fstab to mount automatically on boot: sudo vi /etc/fstab</li></ul><pre>UUID=&quot;b2e62f4f-d338-470e-9ae7-4fc0e014858c&quot; /mnt/data ext4 defaults 0 2</pre><ul><li>Mount the drive using sudo mount -a</li><li>Check it was mounted properly using df -h</li></ul><p>Now the drive will mount automatically on each restart, and you can freely create files in /mnt/data.</p><h3>Step 5: Set Up Network Storage with Samba</h3><ul><li>Install Samba and create a user:</li></ul><pre>sudo smbpasswd -a striker</pre><ul><li>Add a share configuration in /etc/samba/smb.conf:</li></ul><pre>[share]<br>path = /mnt/data<br>valid users = striker<br>read only = no</pre><ul><li>Restart the Samba service: sudo systemctl restart smbd.service</li><li>Allow in UFW: sudo ufw allow samba</li><li>Connect from another device (e.g., Mac) via Go &gt; Network Server, mounted at /Volumes/.</li></ul><p>Now you have a NAS you can access anytime on your local network. The steps to connect may vary slightly depending on the device.</p><h3>AdGuard Home with Docker</h3><p>Next, I wanted my server to act as a <strong>network-wide ad blocker</strong> using <a href="https://github.com/AdguardTeam/AdGuardHome">AdGuard Home</a>.</p><h4>Docker Compose for AdGuard</h4><ul><li>Create a directory for AdGuard (create on system storage not attached storage):</li></ul><pre>mkdir ~/adguard<br>cd ~/adguard</pre><ul><li>Create a docker compose file: vi docker-compose.yaml</li></ul><pre>version: &#39;3&#39;<br>services:<br>  adguard:<br>    image: adguard/adguardhome:latest<br>    container_name: adguard<br>    restart: unless-stopped<br>    ports:<br>      - &quot;53:53/tcp&quot;<br>      - &quot;53:53/udp&quot;<br>      - &quot;67:67/udp&quot;<br>      - &quot;68:68/tcp&quot;<br>      - &quot;80:80/tcp&quot;<br>      - &quot;443:443/tcp&quot;<br>      - &quot;3000:3000/tcp&quot;<br>    volumes:<br>      - ./adguard/work:/opt/adguardhome/work<br>      - ./adguard/conf:/opt/adguardhome/conf</pre><h4>Fixing the Port 53 Conflict</h4><p>Ubuntu’s <strong>systemd-resolved</strong> already uses port 53. To free it for AdGuard:</p><ul><li>Create a custom config in /etc/systemd/resolved.conf.d/adguardhome.conf</li></ul><pre>[Resolve] DNS=127.0.0.1 DNSStubListener=no</pre><ul><li>Backup existing config:</li></ul><pre>mv /etc/resolv.conf /etc/resolv.conf.backup</pre><ul><li>Create a symlink:</li></ul><pre>ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf</pre><ul><li>Restart systemd-resolved:</li></ul><pre>systemctl reload-or-restart systemd-resolved</pre><p>Now AdGuard runs on port 53 without issues.</p><h4>Steps</h4><ul><li>Run docker-compose up -d to start AdGuard</li><li>On another machine in same network, go to: http://&lt;your-server-static-ip&gt;:3000</li><li>You will see the <strong>Get Started</strong> screen. Select all the default options and create an admin user.</li><li>Log in to your admin account.</li><li>Update DNS settings:<br>- Go to <strong>Settings &gt; DNS Settings<br>- </strong>For <strong>Upstream DNS Server</strong>, clear the field and add <strong>1.1.1.1</strong> (Cloudflare)<br>- For <strong>Fallback DNS Server</strong>, add <strong>8.8.8.8</strong> (Google)<br>- Click <strong>Test Upstreams</strong> and then <strong>Apply</strong></li><li>To use AdGuard, change your router or devices to use this DNS server. It’s best to update at the <strong>network level</strong> so you don’t have to configure each device individually. If configured only on a device, it will work only for that device. Your server must keep running for AdGuard to function.</li><li>You can explore more settings to customize AdGuard, but the above steps cover the <strong>bare minimum setup</strong> needed.</li></ul><h3>Jellyfin Media Server with Docker</h3><p>To manage and stream my media, I installed <strong>Jellyfin</strong> — an open-source alternative to Plex.</p><h4>Docker Compose for Jellyfin</h4><ul><li>Create a directory for Jellyfin (create on system storage not attached storage):</li></ul><pre>mkdir ~/jellyfin<br>cd ~/jellyfin</pre><ul><li>Create a docker compose file: vi docker-compose.yaml</li></ul><pre>services:<br>  jellyfin:<br>    image: jellyfin/jellyfin<br>    container_name: jellyfin<br>    user: 1000:1000<br>    network_mode: &#39;host&#39;<br>    volumes:<br>      - ./src/config:/config<br>      - ./src/cache:/cache<br>      - type: bind<br>        source: /mnt/data/jellyfin-media<br>        target: /media<br>    restart: unless-stopped<br>    extra_hosts:<br>      - &#39;host.docker.internal:host-gateway&#39;</pre><h4>Steps</h4><ul><li>Run docker-compose up -d to start Jellyfin</li><li>Create the required directories for config, cache, and media:</li></ul><pre>mkdir -p /mnt/data/config<br>mkdir -p /mnt/data/cache<br>mkdir -p /mnt/data/media</pre><ul><li>Access Jellyfin from another machine in same network: <a href="http://localhost:8096/">http://&lt;</a>your-server-static-ip<a href="http://localhost:8096/">&gt;:8096</a></li><li>Follow the setup guide:<br>- Create a user for yourself.<br>- For the media folder, leave it as is for now.<br>- Select your preferred metadata language (default works fine).<br>- In Configure Remote Access, check both checkboxes.</li><li>At this point, the server page will load but show “nothing here” initially.</li><li>Add your media:<br>- Inside /mnt/data/media, create folders for your content (e.g., movies, tv).<br>- Go to Menu &gt; Dashboard &gt; Library in Jellyfin.<br>- Add your media libraries through this page.</li><li>Now your media will appear on the home page. You can:<br>- Create different folder structures for movies and TV series.<br>- Add multiple users.</li><li>I Suggest to Explore settings to customize further.</li></ul><p><strong>Note:</strong> Jellyfin automatically downloads metadata for your media.</p><blockquote>Currently, everything is available only on your local network. If you want remote access or want to deploy your apps for access from anywhere, check out this blog: <a href="https://medium.com/@striker-aryu56/host-local-projects-without-static-ip-using-cloudflare-tunnel-5cf9bd33f898"><em>Host Local Projects Without Static IP Using Cloudflare Tunnel</em>.</a> This allows you to move your apps from local-only to remote access.</blockquote><p>Setting up a home server on an old laptop has been surprisingly rewarding. From remote SSH access to a NAS for file storage, network-wide ad blocking with AdGuard, and a media server with Jellyfin, I now have a versatile system running multiple services smoothly.</p><p>If you’re curious about taking it further — like hosting your own AI models (think ChatGPT), setting up an automated torrent service with indexers, trackers, and downloaders, or deploying other custom applications — let me know. I can create dedicated blogs diving into each of these topics in detail.</p><p><strong>—</strong></p><p><strong>Refs:</strong></p><ul><li><a href="https://www.youtube.com/watch?v=2Btkx9toufg">Ubuntu Server Setup</a></li><li><a href="https://www.youtube.com/watch?v=YqaDnnREqI8">AdGuard Setup</a></li><li><a href="https://www.youtube.com/watch?v=eJvQKLVrmU8&amp;t=434s">Jellyfin Setup</a></li><li><a href="https://adguard.com/kb/">AdGuard Docs</a></li><li><a href="https://jellyfin.org/docs/">Jellyfin Docs</a></li></ul><p>202510110450</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d5936caba5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Upgraded PostgreSQL on AWS RDS in Production]]></title>
            <link>https://striker-aryu56.medium.com/how-we-upgraded-postgresql-on-aws-rds-in-production-e74f6a6b5f51?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/e74f6a6b5f51</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 21:14:13 GMT</pubDate>
            <atom:updated>2025-09-22T21:14:13.230Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>— <br>Title: </strong>Upgrading PostgreSQL on AWS RDS <strong><br>Date: 22–9–2025<br> — <br>Tags:</strong> aws, postgresql</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KQiIVyWaWyp3cOs1" /><figcaption>Guide to Upgrading PostgreSQL on AWS RDS for Production Environments</figcaption></figure><p>At one of my previous organizations, we were still running a PostgreSQL <strong>12.x</strong> version on AWS RDS. This database powered our <strong>Metabase instance</strong>, which was critical for analytics across the org. The catch? Since PostgreSQL 12 had already gone out of mainstream support, we had to rely on <strong>extended support</strong> — and pay extra for it.</p><p>Naturally, this sparked conversations about <strong>cost savings</strong> and <strong>long-term sustainability</strong>. The decision was clear: we needed to <strong>upgrade PostgreSQL</strong> to a supported version, for us it was <strong>PostgreSQL 17</strong>.</p><p>But like any database upgrade, it wasn’t just about clicking an “Upgrade” button. It meant understanding compatibility, preparing for edge cases, and making sure we didn’t bring down production dashboards that half the company relied on.</p><p>That’s when I started drafting a <strong>structured upgrade plan</strong> — something I wish I had when we first went through it.</p><h3>The Upgrade Journey: Steps I Followed</h3><h3>Step 1: Change Log</h3><p>First, I dug into PostgreSQL’s release notes. This was important to identify <strong>deprecated features</strong> or <strong>breaking changes</strong> that could cause Metabase queries to fail.</p><h3>Step 2: Compatible Target Version</h3><p><strong>AWS</strong> doesn’t allow skipping major versions, so I had to check the valid upgrade paths from <strong>12.x</strong> using the <strong>AWS CLI</strong>. Luckily, for us, it was a straightforward single-step upgrade.</p><pre>aws rds describe-db-engine-versions \<br>  --engine postgres \<br>  --engine-version 12 \<br>  --query &quot;DBEngineVersions[*].ValidUpgradeTarget[*].{EngineVersion:EngineVersion}&quot; \<br>  --output text</pre><p>📖 <strong>Reference:</strong> <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html">AWS RDS Upgrade Targets</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*s6HkwPYcTle7iudFotY46w.png" /><figcaption>Eg. Target Versions</figcaption></figure><h3>Step 3: Instance class compatibility</h3><p>Not every instance type supports all PostgreSQL versions, so I had to cross-check our RDS class against AWS’s documentation. In our case, we were on db.m6i.large, which turned out to support PostgreSQL 17 perfectly for our needs.</p><p>📖 <strong>Reference:</strong> <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.Support.html">AWS RDS Instance Class</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r5N6zrCwoMi5dzBqgLJLQ.png" /></figure><h3>Step 4: Parameter group</h3><p><strong>PostgreSQL</strong> upgrades can introduce new parameters or remove existing ones, which may impact your setup. To be safe, I created a new <strong>parameter group</strong> for the target version and reviewed it. Since we hadn’t customized much, the defaults worked fine.</p><h3>Step 5: Database Content</h3><p>Clean up potential blockers before upgrading:</p><p><strong>Prepared transactions:</strong></p><pre>SELECT count(*) FROM pg_catalog.pg_prepared_xacts;</pre><p><strong>Replication slots:</strong></p><pre>SELECT * FROM pg_replication_slots;</pre><p><strong>reg* data types:</strong></p><pre>SELECT count(*) FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a<br>  WHERE c.oid = a.attrelid<br>     AND NOT a.attisdropped<br>     AND a.atttypid IN (&#39;pg_catalog.regproc&#39;::pg_catalog.regtype,<br>                         &#39;pg_catalog.regprocedure&#39;::pg_catalog.regtype,<br>                         &#39;pg_catalog.regoper&#39;::pg_catalog.regtype,<br>                         &#39;pg_catalog.regoperator&#39;::pg_catalog.regtype,<br>                         &#39;pg_catalog.regconfig&#39;::pg_catalog.regtype,<br>                         &#39;pg_catalog.regdictionary&#39;::pg_catalog.regtype)<br>     AND c.relnamespace = n.oid<br>     AND n.nspname NOT IN (&#39;pg_catalog&#39;, &#39;information_schema&#39;);</pre><p><strong>Invalid databases:</strong></p><pre>SELECT datname FROM pg_database WHERE datconnlimit = -2;</pre><p><strong>Unknown data types:</strong></p><pre>SELECT DISTINCT data_type  FROM information_schema.columns <br>WHERE data_type ILIKE &#39;unknown&#39;;</pre><p>📖 <strong>Reference:</strong> <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.Process.html">Official Postgres Upgrade Docs</a></p><h3>Step 6: Extension Compatibility</h3><p>Extensions (like uuid-ossp, pgcrypto, etc.) are <strong>not automatically upgraded</strong> during a major version upgrade. So I listed all installed extensions and verified their compatibility with the new version.</p><pre>SELECT * <br>FROM pg_extension pe<br>JOIN pg_available_extension_versions pev <br>  ON pev.name = pe.extname;</pre><p>Verify compatibility in <a href="https://docs.aws.amazon.com/AmazonRDS/latest/PostgreSQLReleaseNotes/postgresql-extensions.html?source=post_page-----b5da3e713062---------------------------------------">AWS Postgres Extensions Release Note</a></p><h3>Step 7: Pending maintenance</h3><p>Checked RDS console for any pending maintenance tasks — these can conflict with upgrades, as running them during the upgrade can cause issues. You can view pending maintenance in the AWS RDS console under your DB instance’s “Maintenance &amp; backups” section.</p><h3>Step 8: Take snapshot</h3><p>Took a <strong>manual snapshot</strong> before starting. It serves as a fallback in case the upgrade fails or anything goes wrong.</p><h3>Step 9: Check Application Compatibility</h3><p>Finally, I tested <strong>Metabase</strong> itself with the upgraded <strong>PostgreSQL</strong> version in staging. This step was crucial because Metabase Docker images often lock supported <strong>PostgreSQL</strong> versions. That’s when we ran into a new issue: our current Metabase version didn’t support <strong>PostgreSQL 17</strong>. This meant we had to upgrade Metabase as well. I created a forked Docker image with a few of our custom patches, then tested it against the new database to ensure everything worked smoothly.</p><h3>Final Checklist</h3><pre>- [ ] Change log<br>- [ ] Compatible Target version<br>- [ ] Instance class compatibility<br>- [ ] Parameter group<br>- [ ] Database Content<br>- [ ] Extension compatibility<br>- [ ] Pending maintenance<br>- [ ] Take snapshot<br>- [ ] Application compatibility with new postgres version</pre><h3>Other Points to Consider</h3><ul><li><strong>Blue-Green Deployment:</strong> We used a blue-green deployment approach to test the upgrade on a separate environment, which allowed for a smooth transition to production.</li><li><strong>Performance Monitoring:</strong> Throughout the upgrade process, we monitored the RDS database diligently to ensure everything was working smoothly. We kept an eye on CPU, memory, disk usage, and query performance both before and after the upgrade to catch any regressions early.</li><li><strong>Driver &amp; Connection Compatibility:</strong> We made sure that all applications were using PostgreSQL drivers compatible with the new version to avoid connection issues.</li><li><strong>Security Review:</strong> We reviewed roles, permissions, and SSL settings to ensure security wasn’t impacted.</li><li><strong>Communicate Downtime:</strong> I announced the upgrade downtime for Metabase and scheduled it at night, when traffic was minimal, to reduce disruption for users.</li></ul><p>For us, the upgrade was about <strong>more than just security or new features</strong> — it was about avoiding unnecessary costs while ensuring reliability. What started as a cost-saving initiative turned into a lesson on <strong>systematic upgrades and resilience planning</strong>.</p><p>If you’re in a similar boat with aging PostgreSQL versions on RDS, hopefully, this step-by-step narrative gives you a practical starting point.</p><p>—</p><p><strong>Refs:</strong></p><ul><li><a href="https://docs.aws.amazon.com/AmazonRDS/latest/PostgreSQLReleaseNotes/postgresql-extensions.html?source=post_page-----b5da3e713062---------------------------------------">AWS Postgres Extensions Release Note</a></li><li><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.Process.html">Official Postgres Upgrade Docs</a></li><li><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.Support.html">AWS RDS Instance Class</a></li></ul><p>202509230243</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e74f6a6b5f51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails CSRF Internals Uncovered — And a Real-World Bug We Faced]]></title>
            <link>https://striker-aryu56.medium.com/rails-csrf-internals-uncovered-and-a-real-world-bug-we-faced-ffcb4ce8c52e?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcb4ce8c52e</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 22:22:07 GMT</pubDate>
            <atom:updated>2025-09-22T14:55:54.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails CSRF Internals Uncovered — And a Real-World Bug We Faced</h3><p><strong>— <br>Title: Case Study and Debugging of Rails CSRF Handling<br>Date: 22–9–2025<br> — <br>Tags:</strong> csrf, security, debug, case-study</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UulgwobSRs6GPyxJ" /></figure><p>In a previous post, I explored the <a href="https://medium.com/@striker-aryu56/behind-the-scenes-of-csrf-a-developers-deep-dive-a014c303689f"><strong>Fundamentals of CSRF</strong></a> — what it is, how it works, and the standard mechanisms used to prevent it. While these mechanisms often “just work” in most frameworks, things can get tricky when you’re building or debugging something custom.</p><p>At one of my Org, we encountered a puzzling issue: <strong>“Invalid CSRF token”</strong> errors appearing on two different pages, each caused by a different underlying reason. To debug it, I had to dive deep into how Rails handles CSRF tokens internally.</p><p>This post shares what I learned from that journey — including how Rails generates, masks, and verifies CSRF tokens, how we implemented similar logic in our codebase, and what ultimately caused the issue.</p><h3>💎 How Rails Handles CSRF (Under the Hood)</h3><p>Rails’ <strong>CSRF</strong> protection works out of the box, But once you peek under the hood, there’s some really clever stuff going on — especially around how tokens are generated, masked, and verified.</p><p>At its core, Rails generates a <strong>base token</strong>, stores it in the session, and then sends a <strong>masked version</strong> of that token in the forms or headers. When a request comes in, Rails unmasks the token from the request and simply compares it with the one stored in the session. If they match, the request is good to go. A little more breakdown for each step.</p><h3>1. Generating the CSRF Token</h3><p>When a new session starts, Rails creates a random string using SecureRandom and stores it in the session under :_csrf_token. This is the <strong>base token</strong> and stays the same for the entire session (unless something like a login/logout resets it). <br>File —<a href="https://github.com/rails/rails/blob/19eebf6d33dd15a0172e3ed2481bec57a89a2404/actionpack/lib/action_controller/metal/request_forgery_protection.rb"> request_forgery_protection.rb</a></p><pre>session[:_csrf_token] ||= SecureRandom.base64(32)</pre><p>This base token is what everything else is built on.</p><h3>2. Masking the Token (The Cool Part)</h3><p>Rails doesn’t just throw that raw token into your forms or headers. Instead, it <strong>masks</strong> the token every time it sends it to the client.</p><p>Here’s what that means:</p><ul><li>It creates a random one-time pad (same length as the token).</li><li>It XORs the base token with the pad to “encrypt” it.</li><li>It then sticks the pad and the encrypted result together.</li><li>Finally, the combined result is Base64-encoded.</li></ul><p>So even if the base token never changes, the token sent to the frontend <strong>looks different every time</strong>. This helps protect against attacks like BREACH.</p><h3>3. Where the Token Shows Up</h3><p>The masked token is:</p><ul><li>Embedded in forms via a hidden input field (authenticity_token)</li><li>Sent in the X-CSRF-Token header for AJAX or fetch requests</li></ul><p>This way, Rails knows to expect it during any state-changing request like POST, PUT, PATCH, or DELETE.</p><h3>4. Verifying the Token</h3><p>When a request comes in, Rails does the reverse dance:</p><ul><li>It grabs the token from the header or form field.</li><li>Decodes it from Base64.</li><li>If it’s a masked token (i.e., twice the expected length), it splits out the pad and encrypted part and XORs them to get back the original token.</li><li>Compares this unmasked token to what’s stored in the session (:_csrf_token).</li></ul><p>If anything’s off — wrong value, malformed format, etc. — Rails throws an InvalidAuthenticityToken error.</p><blockquote><em>To keep things extra safe, Rails regenerates the CSRF token after login or sign-up. So even though your session is still active, the CSRF token is refreshed. This prevents old tokens from being reused in new sessions.</em></blockquote><blockquote><em>This behaviour is defined in the Devise initialiser: </em><em>config/initializers/devise.rb:102</em></blockquote><p>Now let’s get started with the issues I ran into.<br>To make debugging easier, I first built a few <strong>common utilities</strong> for decoding and comparing CSRF tokens.</p><h3>Common Utils</h3><p><strong>To parse Session token</strong></p><pre>def decrypt_session(cookie_string, mode = &#39;json&#39;)<br>  serializer = case mode<br>  when &#39;json&#39; then JSON<br>  when &#39;marshal&#39; then ActiveSupport::MessageEncryptor::NullSerializer<br>  end<br>  cookie = CGI::unescape(cookie_string.strip)<br>  salt = Rails.configuration.action_dispatch.encrypted_cookie_salt<br>  signed_salt = Rails.configuration.action_dispatch.encrypted_signed_cookie_salt<br>  key_generator = ActiveSupport::KeyGenerator.new(<br>    Rails.application.secrets.secret_key_base,<br>    iterations: 1000<br>  )<br>  secret = key_generator.generate_key(salt)[0, 32]<br>  sign_secret = key_generator.generate_key(signed_salt)<br>  encryptor = ActiveSupport::MessageEncryptor.new(<br>    secret,<br>    sign_secret,<br>    serializer: serializer<br>  )<br>  result = encryptor.decrypt_and_verify(cookie)<br>  (mode == &#39;marshal&#39;) ? Marshal.load(result) : result<br>end</pre><p><strong>To parse CSRF token</strong></p><pre>def unmask_token(masked_token)<br>  token_length = masked_token.length / 2<br>  one_time_pad = masked_token[0...token_length]<br>  encrypted_token = masked_token[token_length..-1]<br>  xor_byte_strings(one_time_pad, encrypted_token)<br>end<br><br>def encode_token(token)<br>  Base64.strict_encode64(token)<br>end<br><br>def decode_token(token)<br>  Base64.strict_decode64(token)<br>end<br><br>def xor_byte_strings(s1, s2)<br>  s1.bytes.zip(s2.bytes).map { |(c1, c2)| c1 ^ c2 }.pack(&#39;c*&#39;)<br>end<br><br>def due(token)<br>  d = decode_token(token)<br>  u = unmask_token(d)<br>  encode_token(u)<br>end</pre><h3><strong>First Issue: Invalid CSRF Token on Landing Page</strong></h3><h3>Issue</h3><p>There was a recurring problem where users would sometimes face an <strong>Invalid CSRF token</strong> error on the new landing</p><h3>What I Found</h3><p>When the error happened, the two tokens didn’t match:</p><ul><li>The session contained one _csrf_token</li><li>The CSRF API returned another</li></ul><p>But in Rails, there are really only two valid scenarios:</p><ol><li><strong>No token exists yet</strong> → Rails generates one, saves it in the session, and returns it (after masking).</li><li><strong>Token already exists</strong> → Rails reuses it, masking it again before sending.</li></ol><p>So how could they be different?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9jPt7pDOrxNQqYDx.jpg" /></figure><p>It turned out to be a <strong>race condition</strong>:</p><ul><li>Two requests landed almost at the same time.</li><li>Both checked the session, saw no CSRF token, and decided to generate one.</li><li>One request won the race and saved its token in the session.</li><li>But the other request had already generated its own token, so it returned a value that was immediately outdated.</li></ul><p>This explains why the issue appeared when users hit the <strong>new landing page directly</strong> without any cookies (for example, in incognito mode).</p><h3>The Fix</h3><p>The problem was that we were <strong>eagerly calling the CSRF API</strong> as soon as the page loaded. That increased the chance of this race condition.</p><p>The solution was simple:<br> 👉 <strong>Remove the initial CSRF API call and instead fetch the token only when it’s actually needed — at the time of the first POST request.</strong></p><p>This way, only one request is responsible for generating and storing the token, eliminating the race.</p><h3>Second Issue: Invalid CSRF Token on Product Page</h3><h3>Issue</h3><p>We noticed users sometimes got <strong>“Invalid CSRF token”</strong> errors when opening the Product landing page from Slack links. The issue was inconsistent — only happening when the page was opened in Chrome’s Slack preview.</p><p>Here’s the request flow that caused the issue:</p><ol><li>User clicks a Slack link to open the Product landing page.</li><li>The page makes an initial API call to load content.</li><li>A subsequent API call (e.g., user/v2 for OTP) fails with an invalid CSRF token error.</li></ol><p>It seemed like the session was being <strong>dropped between requests</strong>, causing CSRF verification to fail. This issue was particularly tricky to debug.</p><h3>Debugging Process</h3><p>I approached this step by step, adding logs and tracing the request flow.</p><p><strong>1. Inspecting CSRF Verification</strong></p><ul><li>Added logging inside Rails’ request_forgery_protection.rb where the CSRF token is compared with the session.</li><li>Finding: The session was <strong>empty</strong> at this point, even though the cookie itself was present.</li></ul><p>This suggested the session was being created correctly initially, but something later in the middleware chain was removing it.</p><p><strong>2. Checking Session Creation</strong></p><ul><li>Added loggers in ActionDispatch::Request::Session and CookieStore.</li><li>Found that the <strong>session was properly populated</strong> from the cookie, including the CSRF token.</li></ul><p>So the drop wasn’t during session creation — it happened <strong>later in the middleware stack</strong>.</p><p><strong>3. Tracing Middleware Calls</strong></p><ul><li>Added logging in SanitizeQueryStringMiddleware.</li><li>Observation: The session was available <strong>before</strong> the middleware but gone <strong>after</strong>.</li><li>Testing middleware order confirmed that <strong>session availability depended on execution order</strong>.</li><li>Rack-protection middleware, especially session_hijacking.rb, ran after SanitizeQueryStringMiddleware.</li></ul><p><strong>4. Identifying the Root Cause</strong></p><ul><li>In rack-protection/lib/rack/protection/session_hijacking.rb, I found a check comparing the session’s tracking hash with request environment values.</li><li>Specifically, the HTTP_ACCEPT_LANGUAGE header differed between requests:</li></ul><p>Request HTTP_ACCEPT_LANGUAGEInitial Product APIen-USOTP API (user/v2)en-US,en;q=0.9,hi;q=0.8</p><ul><li>This difference triggered <strong>rack-protection’s session-hijacking check</strong>, which dropped the session.</li><li>Dropping the session invalidated the CSRF token, causing the failure.</li></ul><p><strong>5. Hypothesis Testing</strong></p><p><strong>Replicated the flow using Postman:</strong></p><ol><li>First, call the Product page to get the CSRF token.</li><li>Then, call user/v2 with the same cookies and CSRF token.</li></ol><p><strong>Results:</strong></p><ol><li><strong>Same Accept-Language header</strong> → CSRF passed</li><li><strong>Different header</strong> → CSRF failed</li></ol><p>This confirmed that the mismatch in headers caused the session drop and CSRF failure.</p><h3>Fix</h3><p>The fix was straightforward:</p><ul><li><strong>Remove HTTP_ACCEPT_LANGUAGE tracking</strong> in session-hijacking (already removed in newer rack-protection versions — <a href="https://github.com/sinatra/sinatra/commit/6cf49c885554fa6265f119e6ad5b8d3707c22f64"><strong>Commit Link</strong></a>).</li><li>Upgrade or patch the rack-protection middleware.</li></ul><p>Now, minor differences in request headers no longer drop the session, and the CSRF token remains valid across the flow — even in Slack preview.</p><p><strong>CSRF</strong> protection usually works behind the scenes, and you rarely notice it — until it breaks. Going through Rails’ internals and debugging these real issues reminded me that even small things, like request timing or headers, can trip it up. Understanding how the tokens are generated, masked, and verified made it much easier to find the root cause and fix it properly.</p><p>—</p><p><strong>Refs:</strong></p><ul><li><a href="https://github.com/rails/rails/blob/19eebf6d33dd15a0172e3ed2481bec57a89a2404/actionpack/lib/action_controller/metal/request_forgery_protection.rb">CSRF Protection Code</a></li><li><a href="https://github.com/sinatra/sinatra/blob/main/rack-protection/lib/rack/protection/session_hijacking.rb">Session Hijacking Code</a></li><li><a href="https://github.com/sinatra/sinatra/commit/6cf49c885554fa6265f119e6ad5b8d3707c22f64">Removal of ACCEPT_LANGUAGE Commit</a></li></ul><p>202509220350</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcb4ce8c52e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Host Local Projects Without Static IP Using Cloudflare Tunnel]]></title>
            <link>https://striker-aryu56.medium.com/host-local-projects-without-static-ip-using-cloudflare-tunnel-5cf9bd33f898?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf9bd33f898</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloudflare-tunnel]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[devtools]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 13:42:44 GMT</pubDate>
            <atom:updated>2025-04-11T13:42:44.608Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>— <br>Title: Hosting Server in Internal Network using cloudflare Tunnel<br>Date: 11–04–2025<br> — <br>Tags:</strong> cloudflare, tunnel , server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBZhloxAfIPZ5MDGMJu3Bw.png" /></figure><p>Setting up a public-facing server from your internal network usually comes with a major headache — <strong>you need a static IP and a DNS provider</strong>. Even if you’ve got your domain name ready, your ISP may not assign you a static IP, or worse, may charge extra for it.</p><p>But what if I told you there’s a way to bypass that entirely?</p><h3>🔐 Enter Cloudflare Tunnel (aka cloudflared)</h3><p>Cloudflare Tunnel allows you to expose your local server <strong>securely</strong> to the internet without needing a static IP or poking holes in your firewall. The magic? It establishes a <strong>persistent outbound connection</strong> from your machine to Cloudflare’s edge network.</p><p>So, instead of users directly hitting your home IP, their requests go through Cloudflare, which then forwards traffic through this tunnel to your internal server — and sends responses back the same way.</p><p>All you need is a <strong>registered domain on Cloudflare</strong>. No static IP, no port forwarding, and no exposing your machine directly.</p><h3>🛠️ Setting Up a Cloudflare Tunnel</h3><p>Let’s walk through the setup with a simple example.</p><h3>1. Go to Cloudflare Zero Trust Dashboard</h3><p>Navigate to the <strong>Zero Trust</strong> section in your Cloudflare dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*pNqTs36HkAF93jM2uKB4XQ.png" /><figcaption>Zero Trust Section</figcaption></figure><h3>2. Create Your Team Domain</h3><p>Pick any name for your team domain. This is just for internal structuring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlvHjLLSAjvArkoc9zPCNw.png" /><figcaption>Team Domain</figcaption></figure><h3>3. Select the Free Plan</h3><p>Yes, it’s completely free! Just proceed to payment, enter any method (no actual charges).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*JCjYs39xC21G5BMT9ELFDg.png" /><figcaption>Free Plan</figcaption></figure><h3>4. Navigate to “Networks &gt; Tunnels”</h3><p>On the sidebar, head to <strong>Networks → Tunnels</strong>, then click <strong>“Add a Tunnel.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM1B6gtn_4ZC-uvdyruWfA.png" /><figcaption>Add A Tunnel</figcaption></figure><h3>6. Start the Tunnel (Pick Your Environment)</h3><p>You’ll now get setup instructions based on your OS.</p><ul><li><strong>For macOS:</strong> brew install cloudflared and run as a service.</li><li><strong>Docker:</strong> You can also run it inside Docker — straightforward and clean.</li></ul><p>Once done, your tunnel status should show as <strong>Connected</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlpR9F0Yy1uKFw5mGfKZvQ.png" /><figcaption>Connected Tunnel</figcaption></figure><h3>🌐 Host Something Locally</h3><p>Let’s test it out by running a simple server:</p><h3>Option 1: NGINX via Docker</h3><pre>docker run -p 8080:80 nginx</pre><h3>Option 2: A Tiny Flask App</h3><p>Save this as app.py and run with python app.py:</p><pre>from flask import Flask<br>app = Flask(__name__)<br>@app.route(&#39;/&#39;)<br>def home():<br>    return &#39;Hello, Flask!&#39;<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h3>🌍 Expose It with a Public Hostname</h3><p>Once the tunnel is active:</p><ol><li>Add a new <strong>public hostname</strong></li><li>Choose any subdomain (e.g., demo.yourdomain.com)</li><li>Type: HTTP</li><li>URL: localhost:8080 (for NGINX) or localhost:5000 (for Flask)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSspTWgmxciLcFRJ4w0dtw.png" /><figcaption>Setting for public Host Name</figcaption></figure><p>Save it, and boom — you now have a public link to your local server!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ddk9I0BWUWOhlaPjHbksSQ.png" /><figcaption>Local Server On Public Domain</figcaption></figure><h3>🐛 Facing issue with HTTPS request</h3><p>In my setup:</p><ul><li><strong>Next.js frontend</strong> ran on port 3000 and was exposed via a tunnel to a subdomain.</li><li><strong>Python Flask backend</strong> ran on port 5000, also exposed via a tunnel.</li></ul><p>Both were running with <strong>HTTP</strong> internally.</p><p>Cloudflare provides an <strong>HTTPS URL</strong> for every tunnel. So even though my servers were running on HTTP, the frontend was making HTTPS requests to the backend.</p><p>This caused CORS or SSL handshake failures. The requests were made over HTTPS but seemed to break mid-way, possibly due to internal HTTP fallback.</p><h4><strong>Solution</strong></h4><p>I started the Flask server with an <strong>adhoc self-signed SSL certificate</strong>:</p><ul><li>flask run --cert=adhoc --host=0.0.0.0</li></ul><p>While setting up the public hostname in the tunnel:</p><ul><li>I used: https://&lt;private_ip&gt;:5000</li><li>Changed the <strong>TLS setting to “No TLS verify”</strong>, allowing Cloudflare to accept self-signed certs.</li></ul><p>Since Flask was generating the certificate on the fly, this was essential to avoid SSL errors.</p><h3>🧠 Final Thoughts</h3><p>Cloudflare Tunnel is a game-changer for self-hosting. Whether you’re building demos, internal tools, or working on projects that need remote access, you can now skip the static IP drama.</p><p>Try it out, and give your side projects a proper home on the internet — without compromising on security or simplicity.</p><p>If you face any issues while setting this up, feel free to reach out. Always happy to help!</p><p><strong>—</strong></p><p><strong>Refs:</strong></p><ul><li><a href="https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/">Cloudflare Docs</a></li></ul><p>202504111902</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf9bd33f898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes of CSRF: A Developer’s Deep Dive]]></title>
            <link>https://striker-aryu56.medium.com/behind-the-scenes-of-csrf-a-developers-deep-dive-a014c303689f?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/a014c303689f</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[browser-security]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 08:54:44 GMT</pubDate>
            <atom:updated>2025-04-09T08:54:44.393Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>— <br>Title: Cross-Site Request Forgery (CSRF)<br>Date: 09–04–2025<br> — <br>Tags:</strong> web, security</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QK3yOwy5VloOT1fmNDALjQ.png" /><figcaption>Behind the Scenes of CSRF: A Developer’s Deep Dive</figcaption></figure><p><strong>CSRF </strong>is one of those security issues that’s been around for a long time. There are well-known solutions and standard practices to prevent it — so much so that they’re often taken for granted. But sometimes, it’s worth taking a step back to understand the vulnerability more deeply and how each mitigation actually works under the hood.</p><p>A while back, I encountered a tricky CSRF-related issue that led me down a rabbit hole of understanding how <strong>Ruby on Rails</strong> internally handles CSRF protection. That experience inspired this post.</p><p>This blog is part one of that journey — focusing on what CSRF really is, the conditions that make it possible, and how different protective mechanisms work. In a future post, I’ll share how Rails tackles CSRF internally, what went wrong in my case, and how I ended up resolving it.</p><p>Let’s dive in.</p><h3>💣 What Even Is CSRF?</h3><p>At its core, <strong>Cross-Site Request Forgery (CSRF)</strong> is about abusing trust. If you’re logged into a website (say, your bank), and then unknowingly visit a malicious site, that site might trick your browser into sending a request to the bank on your behalf. The browser includes your cookies (like session tokens) automatically — so the bank thinks it’s you.</p><p>It’s like handing your house keys to a stranger because they asked in the right tone of voice.</p><p>Imagine this scenario:</p><ul><li>You’re logged into your account.</li><li>A malicious page includes something like:</li></ul><pre>&lt;img src=&quot;https://bank.com/transfer-money?amount=1000&amp;to=attacker&quot; /&gt;</pre><ul><li>Your browser sees it and thinks, “Sure! Let me attach your auth cookies and fire that off!”</li></ul><blockquote><strong><em>Note</em></strong><em>: If your API uses stateless, token-based authentication in headers (like JWT), CSRF isn’t typically an issue. This mainly affects cookie-based auth.</em></blockquote><h3>🔑 Conditions That Make CSRF Possible</h3><p>For a CSRF attack to succeed, a few conditions must align:</p><ul><li><strong>Important Action</strong>: The targeted action must be meaningful — like changing account details or transferring funds.</li><li><strong>Cookie-Based Authentication</strong>: If the browser automatically attaches auth cookies or headers, the server is easily fooled.</li><li><strong>Predictable Parameters</strong>: If request parameters are easy to guess or fixed, attackers can replicate them in malicious payloads.</li></ul><h3>🛠️ How a CSRF Attack Happens</h3><p>Attackers typically set up a webpage that silently triggers a request to a vulnerable endpoint. For example:</p><pre>&lt;img src=&quot;https://website.com/risky-path&quot;&gt;</pre><p>Or with a form:</p><pre>&lt;form action=&quot;https://vulnerable.com/update-email&quot; method=&quot;POST&quot;&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;email&quot; value=&quot;attacker@example.com&quot; /&gt;<br>&lt;/form&gt;<br>&lt;script&gt;document.forms[0].submit()&lt;/script&gt;</pre><p>Suddenly, your innocent browsing turns into a silent attack.</p><h3>🛡️ Preventing CSRF Attacks</h3><p>The goal is to <em>break the attack chain</em> — by introducing randomness or validating the origin of requests. Common strategies include:</p><h3>1. CSRF Tokens</h3><p>The server generates a unique, random token for each user session. This token must be sent back by the client with every sensitive request — via header or hidden form field.</p><p>But using CSRF tokens incorrectly opens up vulnerabilities:</p><ul><li>If the token is <strong>not tied to the session</strong>, attackers can use their own token.</li><li>If the token is stored in cookies and validated by simply matching values (called <strong>Double Submit</strong>), an attacker can manipulate both the token and the cookie if the browser allows it.</li></ul><p><strong>Best Practices</strong>:</p><ul><li>Tokens should be <strong>random</strong> and <strong>session-bound</strong>.</li><li>Tokens should <strong>not</strong> be sent in cookies.</li><li>For form-based actions, embed them as <strong>hidden fields</strong>.</li><li>For XHR requests, send them in <strong>custom headers</strong>.</li></ul><blockquote><em>Note: If sent via headers, only AJAX/XHR requests are supported — not native HTML forms.</em></blockquote><h3>2. SameSite Cookie Attribute</h3><p>This is a browser-level defense that controls when cookies are sent during cross-site requests.</p><ul><li><strong>Strict</strong>: Cookies are only sent in first-party contexts. Completely blocks CSRF but may break SSO and other flows.</li><li><strong>Lax (Default)</strong>: Cookies are sent on top-level GET navigations (like clicking a link), but blocked in other cross-site cases.</li><li><strong>None</strong>: Cookies are sent in all requests, but must include the Secure flag (HTTPS only).</li></ul><pre>Set-Cookie: sessionId=abc123; SameSite=None; Secure</pre><h4>Vulnerabilities in SameSite Protections:</h4><ul><li><strong>Lax Bypass</strong>: If the server treats both GET and POST similarly, attackers can misuse Lax rules.</li><li><strong>Strict Bypass via Redirection</strong>: Attacker-controlled redirections using URL parameters can indirectly trigger CSRF.</li><li><strong>Lax Delays</strong>: For SSO flows, browsers delay applying Lax for 120 seconds — creating a window of vulnerability.</li></ul><h3>3. Referrer-Based Validation</h3><p>Some servers rely on checking the Referrer header to ensure requests come from the right origin.</p><p>This method is <strong>less secure</strong>, and attackers can bypass it easily:</p><ul><li>Use meta tags to strip the referrer:</li></ul><p>&lt;meta name=&quot;referrer&quot; content=&quot;never&quot;&gt;</p><ul><li>Host malicious pages on subdomains like:</li></ul><p><a href="http://vulnerable.com.attacker.com/">http://vulnerable.com.attacker.com</a></p><p>Referrer validation should <em>never</em> be your only line of defense.</p><h3>🔚 Final Thoughts</h3><p>CSRF is dangerous because it abuses trust — your browser’s trust in cookies, your server’s trust in headers, and the user’s trust in your website.</p><p>The good news? It’s preventable. With the right strategies, you can turn this silent threat into a non-issue.</p><p><strong>—</strong></p><p><strong>Refs:</strong></p><ul><li><a href="https://portswigger.net/web-security/csrf/lab-no-defenses">Port Swigger Labs</a></li><li><a href="https://portswigger.net/web-security/csrf#what-is-csrf">Blog related to CSRF</a></li></ul><p>202504091409</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a014c303689f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered Competitive Coding: Your Path to Success]]></title>
            <link>https://tech.scaler.com/ai-powered-competitive-coding-your-path-to-success-baeebe4f532d?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/baeebe4f532d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 15:05:51 GMT</pubDate>
            <atom:updated>2023-07-31T07:52:37.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Embrace the Future of Programming with AI’s Support</p><figure><img alt="Illustration of Competitive coding companion" src="https://cdn-images-1.medium.com/max/1024/1*H7SuvbXMIMAjtFDKE71yfQ.png" /><figcaption>Competitive Coding Companion | <a href="https://storyset.com/web">Web illustrations using Storyset</a></figcaption></figure><p><em>French, Mandarin, and Spanish</em> — everyone wants to learn a new language and expand their knowledge of a new culture. However, as our lives increasingly revolve around technology, there are other languages that are an immense asset- <a href="https://en.wikipedia.org/wiki/Programming_language"><strong>Programming languages</strong></a>.</p><figure><img alt="Word cloud of programming languages" src="https://cdn-images-1.medium.com/max/620/1*wM5Ww436zs3vv5-Bqz3WKA.png" /><figcaption>Programming Languages</figcaption></figure><p>Learning a new <strong>programming language</strong> is more than just a valuable addition to one’s <strong>portfolio</strong>; it has become an indispensable skill in our digital age. As <strong>virtual platforms</strong> replace traditional <strong>classrooms</strong>, and apps like <a href="https://www.notion.so/"><strong>Notion</strong></a> streamline our <strong>note-taking</strong> <em>(saying this while using it to write the blog</em> 😂), even something as simple as ordering takeout through <strong>Zomato</strong> involves the language of code working behind the scenes. And I can go on about the essence of learning a new <strong>programming language</strong>, but I believe my argument is now clear and compelling.</p><h3><strong>What will help you gain an edge?</strong></h3><p>Let’s delve into how one can truly <strong>excel</strong> in the world of <strong>programming</strong>. This is where <strong>competitive coding</strong> comes into play, and it’s just “<em>an intimidating word for </em><strong><em>problem-solving</em></strong><em> using some </em><strong><em>programming language”</em></strong>. Yeah, and I don’t think there is anything else to say about it. You can get very complex definitions for this like the example presented below from <strong>chat GPT</strong>. But rest assured, The concept is as straightforward as I described it.</p><figure><img alt="GPT definition for competitive coding" src="https://cdn-images-1.medium.com/max/1024/0*v6K9NP8YygpusVcN" /><figcaption>GPT definition for competitive coding</figcaption></figure><p>But when it comes to practising <strong>competitive coding</strong>, things can get tricky, much like doing a workout. The concept is simple: “<em>training your body to gain strength and balance</em>” but the execution is where the challenge lies. Learning a <strong>programming language</strong> may be easy, but it becomes your most potent asset when you consistently practice it, and <strong>competitive coding</strong> offers no better way to achieve that.</p><h3>The New Era of Competitive Coding with AI</h3><p>I believe we are in a new era for <strong>competitive coding</strong> because it has never been easier to adopt it as a habit. There are numerous platforms and excellent educational resources available, including <strong>AI</strong> tools like <strong>Large language models</strong> (<a href="https://www.analyticsvidhya.com/blog/2023/03/an-introduction-to-large-language-models-llms/#:~:text=Large%20Language%20Models%20(LLMs)%20are,entity%20relationships%20in%20the%20language.)"><strong>LLMs</strong></a><strong>)</strong> such as <a href="https://chat.openai.com/"><strong>Chat GPT</strong></a>, which have become key enablers. In the past, resources were scarce, and there was little support available. Now, with AI assistance like <strong>Chat GPT</strong>, individuals can jump-start their <strong>competitive coding</strong> journey, benefiting especially those in the early stages.</p><blockquote>The ease and potential of AI usage have grown tremendously, and accessibility has significantly improved over the past years.</blockquote><p>In the following discussion, I will explain how you can utilize <strong>Chat GPT</strong> as your <strong>competitive coding companion</strong>, drawing insights from <strong>Scaler’s approach</strong> (<em>based on first-hand information </em>😜).</p><h3>GPT- Your competitive coding companion</h3><figure><img alt="Your competitive coding companion" src="https://cdn-images-1.medium.com/max/1024/1*x9KMTDGliDycc7-cg_Z0ZQ.png" /><figcaption>Your competitive coding companion</figcaption></figure><h3>Step 1: Set GPT Thermostat 🌡️</h3><p>There is <strong>one key point</strong> we should address first. When generating responses from <strong>GPT</strong>, it can generate either from pure imagination or based on real facts. You can control this behaviour using the ‘<strong>Temperature</strong>’ argument, which ranges from <strong>0 to 2</strong>. For the task of problem-solving, a good range is typically <strong>0.5 to 0.9</strong>. This allows <strong>GPT</strong> to be innovative while avoiding excessive hallucinations.</p><p>To specify the ‘<strong>Temperature</strong>’ in the GPT playground, there is a direct option for that. However, when using a <strong>GPT chatbot</strong>, you can set the ‘<strong>Temperature</strong>’ at the start of your conversation like this:</p><blockquote>use “temperature” value x on our conversation</blockquote><p><strong>A fun activity to try 💻</strong>, set a <strong>high-temperature </strong>value<strong> </strong>and ask some questions about non-existing things as I asked about the <strong>red peacock</strong>. Then ask the same question with a <strong>low-temperature</strong> value.</p><p><strong>Example for a high-temperature value(2)</strong></p><figure><img alt="High-temperature example" src="https://cdn-images-1.medium.com/max/1024/1*thTKGWMoFHuLtEEIe4w_9Q.png" /><figcaption>High-temperature example</figcaption></figure><p><strong>Same example for a low-temperature value(0)</strong></p><figure><img alt="Low-temperature example" src="https://cdn-images-1.medium.com/max/1024/1*uJu6ziloZabBbyrbDeY9Uw.png" /><figcaption>Low-temperature example</figcaption></figure><p>This shows how <strong>temperature</strong> can affect your response and stop <strong>GPT</strong> from hallucinating.</p><h3>Step 2: Know your stage 🧐</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zk54S5xVwUCgfgxC.png" /><figcaption>A comic strip by <a href="https://www.monkeyuser.com/2018/root-cause/">Monkey user</a></figcaption></figure><p>When working on a coding problem, it’s common to encounter multiple stages where you might get stuck, and sometimes these stages can appear quite similar. To effectively overcome these obstacles, it’s crucial to pinpoint the key issue causing the blockage. Let’s explore each stage and how you can recognise them:</p><ol><li><strong>The Problem Statement Stage:</strong> This is the initial stage. To begin, try explaining the problem to someone else. Following that, attempt to create your input test case and calculate the expected output. If you can accomplish these two tasks, you have cleared this stage.</li><li><strong>The Ideation Stage:</strong> At this stage, you need to develop a common logic that can be applied to multiple test cases without altering the core idea. If you can build one you can move ahead.</li><li><strong>The Approach Stage:</strong> We will delve deeper into this stage in the “I<strong>mplementation: Logical</strong>” section. The fundamental concept is to ensure that your approach covers all cases without failures. Failures can occur due to various reasons, such as missing edge cases, or exceeding time or memory limits. <br>Identifying issues like <a href="https://discuss.codechef.com/t/what-does-the-message-time-limit-exceeded-means/541"><strong>Time Limit Exceeded (TLE)</strong></a> or <a href="https://www.notion.so/New-Time-for-competitive-coding-63a718cf19ec40c5ad74d256470a8600?pvs=21"><strong>Memory Limit Exceeded (MLE)</strong></a> is relatively straightforward. As these issues are caused when your approach was right but not for larger test cases as the compiler was not able to generate an output within the bounds and hence it throws out an error specifying the error type.</li><li><strong>The Implementation: Syntax Stage:</strong> This stage is the easiest to recognize, as it is indicated by any compilation errors you encounter while running your code. These errors usually relate to incorrect syntax or programming language rules.</li><li><strong>The Implementation: Logical Stage:</strong> As mentioned earlier, this is where it becomes tricky. Both having the wrong approach and incorrectly implementing the right approach can lead to failed test cases. For now, let’s consider these two situations together, and there are two ways you can seek help from <strong>Chat GPT</strong>, which we’ll discuss in the next section.</li></ol><p>Moving forward, let’s explore how you can utilize <strong>Chat GPT</strong> to assist you with these coding problem-solving stages.</p><h3>Step 3: Start prompting ⌨️</h3><p>To make the most of GPT as your problem companion, follow these steps to set up the conversation<strong> (Also I have added an example of a full conversation with GPT at the end of this section)</strong>:</p><h4><strong>Set the Role, Parameters, and Tone:</strong></h4><p><strong>Role:</strong> Start by specifying the role of GPT, which is your problem-solving companion</p><p><strong>Tone:</strong> You can also indicate the desired tone of the responses, such as concise, long, stepwise, or any style that suits your learning preferences.</p><p><strong>Parameters:</strong> It’s essential to set the right parameters to ensure GPT provides the level of assistance you need. By default, GPT might try to offer complete solutions, but you can avoid that by instructing the model to provide hints or point you in the right direction. Emphasize that you don’t want direct solutions or code. You can customize this setup further based on your specific requirements to tailor your assistant.</p><p>In the end, your prompt will look like this:-</p><pre>You are &lt;role&gt;, who will provide &lt;tone&gt; response by &lt;parameter&gt;.<br>For the problem delimited by angular brackets.<br>&lt;problem_description&gt;</pre><pre>eg.<br>You are my personal problem-solving companion, who will provide me with a concise response<br>by either providing me hints or pointing me in the right direction and you should never give<br>me direct solutions or code. For the problem delimited by angular brackets.<br>&lt;<br>print a pyramid pattern<br>&gt;</pre><p>And now the setup is complete for your assistant. You can begin asking questions based on the stage where you are currently stuck.</p><h4><strong>Getting help for Problem statement</strong></h4><p>Here you can simply ask the model to explain the problem statement in simpler terms. A fun thing to try can be asking the model for analogies for the problem. It will give you creative examples which can help you build a new perspective.</p><p>It’s essential to note that relying on the model to explain test cases or visualize the problem statement might not always yield reliable responses. So, while these options are available, it’s best to use them with caution.</p><h4><strong>Getting help for Ideation</strong></h4><p>Here you can start asking for hints for the approach, the order which will work best is:</p><ol><li><strong>Ask for hints about the key challenges-</strong> It is the first thing you should figure out in the problem.</li><li><strong>Ask for hints about the key insights-</strong> the next step after finding the challenges is what insight you can gain from it.</li><li><strong>Ask for hints about the intuition-</strong> after figuring out the challenges and insights you should start building your intuition around it.</li><li><strong>Ask for hints about data structure and algorithm-</strong> building an intuition will lead to the planning of what DS/Algo concept you can use to implement that</li><li><strong>Ask for hints for the solution-</strong> the last thing will be the solution building upon all the points discussed above.</li></ol><p>And these 5 steps should help you get started with the approach.</p><h4><strong>Getting Help with Implementation</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*diIndtD4UDPjf_7J.png" /></figure><p>Here comes the last stage in problem-solving implementation, And here you can face multiple issues-</p><p><strong>Syntax-</strong> Getting help with code errors is easy. Just share your code and the specific error you’re facing, and ask for guidance on resolving the issues. Please request that <strong>GPT</strong> does not provide a complete fixed code to avoid potential inaccuracies. Instead, rely on <strong>GPT</strong> to point out syntax issues and guide you towards solutions. You can repeat the process until all syntax issues are resolved.</p><blockquote><strong><em>Note:</em></strong><em> </em>While providing an external text like code, errors which are not part of the prompt you should always tell GPT what part of the prompt is delimited by like please help me with my code delimited by square brackets [your code]</blockquote><p><strong>Logic-</strong> Once all syntax issues are resolved, you may encounter two cases. First, if you encounter <strong>Time Limit Exceeded (TLE)</strong> or <strong>Memory Limit Exceeded (MLE)</strong>, it is advisable to ask <strong>GPT</strong> for the maximum acceptable time and memory complexity based on the given constraints in the problem description(<em>ensure you have provided it in the problem description</em>). This will help you understand the efficiency requirements before exploring alternative approaches. Additionally, you can request suggestions for a more efficient solution or improvements to your current approach.</p><p>The second case is encountering <strong>logical errors</strong>. Here, you have two options. Firstly, you can ask <strong>GPT</strong> to assess your approach even before implementing it. Just provide your proposed approach and ask <strong>GPT</strong> to evaluate it for you. The other thing you can do is fix logical issues in your code, but here you can’t simply ask “<em>Please find logical errors”</em> to <strong>GPT</strong> as it will mostly give wrong responses.</p><p>To fix this you should give more context to <strong>GPT</strong> to compute. Consider providing generic steps that <strong>GPT</strong> can use as a basis for generating tailored advice based on your specific problem and solution. For instance, you could use something like:</p><pre>Please find the issue in the code delimited by triple backticks<br>```code```<br><br>please follow these steps to provide help:<br>1. Now, analyze the code to determine if it will work as a solution for the problem.<br>2. Identify any logical issues that may prevent it from being a correct solution.<br>3. Attempt to fix the logical issues and check if the solution works. If it doesn&#39;t, repeat steps 1-2. Otherwise, proceed to step 4.<br>4. Help the user address those logical issues.<br>5. Check the validity of your response by using generated response to fix the code and see if it works.<br>6. Fix mistakes in your response.<br><br>Please make sure you don&#39;t provide me with any form of code, and provide response in form of<br>&lt;brief about the issue&gt;<br>&lt;how to resolve it&gt;</pre><p>You can go through the example for the full conversation with chat GPT where I am using these principles — <a href="https://chat.openai.com/share/8b6fcd15-26a7-4e35-aa03-47a749077195"><strong>Conversation with Competitive Coding Companion</strong></a></p><h4><strong>Important</strong></h4><p>While trying any <strong>prompt</strong> please make sure a few things, your <strong>prompts</strong> have a <strong>clear structure</strong> and <strong>no typos</strong>. Also, You are using <strong>delimiters</strong> for providing external text as mentioned above. These small things keep <strong>GPT</strong> in check and ensure it is not going off the track. <em>You can provide your prompts in the comment section and I can assess them for you and suggest how you can improve them.</em></p><p>Great! With this, you should be able to use <strong>GPT</strong> to its full potential in helping you solve problems, and improve your <strong>competitive coding</strong> skills.</p><h3>Let’s see how Scaler did it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwPCAJHHtxt-T19zOihkwA.png" /><figcaption><a href="https://yourstory.com/2023/07/scaler-gpt-4-ai-teaching-assistant-learner-support-doubt-resolution">Newspost about Scaler using GPT</a></figcaption></figure><p>There are multiple <a href="https://yourstory.com/2023/07/scaler-gpt-4-ai-teaching-assistant-learner-support-doubt-resolution"><strong>news posts</strong></a> regarding how <strong>Scaler</strong> has embraced <strong>cutting-edge AI</strong>, utilizing a model like <strong>Chat GPT</strong> to revolutionize the learning experience. <strong>Scaler</strong> leverages the same core principles we discussed earlier to assist learners throughout their journey. It is the first-hand usage of those principles.</p><p>For those who don’t know, <strong>Scaler is an up-skilling platform</strong> that helps users build technical skills from the ground up, starting with <strong>competitive coding</strong> as their first stage. As most of the audience in <strong>Scaler</strong> is new to programming due to the nature of the platform, there was a crucial requirement of enablers which can help learners when they get stuck on a problem and these enablers were <strong>Teaching Assistants.</strong> But with the introduction of <strong>Chat GPT</strong>, the possibilities became intriguing. Every mind in scaler was thinking- “<em>How can we use it to be a better alternative to teaching assistant due to its obvious pros like availability, quick SLAs and quality</em>”. To explore this idea, <strong>Scaler</strong> began <strong>experimenting with GPT’s assistance</strong>, providing learners with nudges in the right direction without revealing a full solution.</p><p>The groundwork for this unique approach was set, and a comprehensive companion was developed. Learners could seek help with their doubts, and <strong>Scaler’s system</strong> adeptly gathered relevant information to create specially designed prompts. These prompts were then sent to <strong>GPT</strong>, generating appropriate responses to assist the learners effectively.</p><figure><img alt="Scaler Problem-solving companion" src="https://cdn-images-1.medium.com/max/1024/0*c2XxlbtHt5Rbkcnb" /><figcaption>Scaler Problem-solving companion</figcaption></figure><p>Currently, learners trigger assistance, but the team at <strong>Scaler</strong> is actively working on an automated system. This system will intelligently recognize when a learner is stuck based on their behaviours and provide timely help without requiring manual activation.</p><p>With <strong>AI</strong> as an ally, <strong>Scaler</strong> has transformed the way learners tackle challenges, opening up new possibilities and revolutionizing the future of upskilling. The integration of <strong>GPT</strong> into the learning process has streamlined problem-solving and made the competitive coding journey an enriching experience for every learner.</p><p>In conclusion, <strong>competitive coding</strong> can be an incredibly rewarding hobby, and the vast potential of <strong>GPT</strong> can assist you in ways you may not have imagined.</p><p>I hope you enjoyed reading the blog and gained valuable insights from it. If you have any questions or wanna share your experience drop a <strong>comment</strong>. Feel free to reach out in any form. <strong>Happy coding!</strong> 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baeebe4f532d" width="1" height="1" alt=""><hr><p><a href="https://tech.scaler.com/ai-powered-competitive-coding-your-path-to-success-baeebe4f532d">AI-Powered Competitive Coding: Your Path to Success</a> was originally published in <a href="https://tech.scaler.com/">ScalerTech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hamiltonian Cycle]]></title>
            <link>https://striker-aryu56.medium.com/hamiltonian-cycle-340b0033a06d?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/340b0033a06d</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[hamiltonian]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 06:41:55 GMT</pubDate>
            <atom:updated>2021-03-19T06:41:55.072Z</atom:updated>
            <content:encoded><![CDATA[<p>Great use of Hamiltonian cycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DmcnIQtKV9km0uXoUeuGg.png" /><figcaption>Hamiltonian cycle</figcaption></figure><p>Let’s take a step back and let’s see what’s a <a href="https://mathworld.wolfram.com/HamiltonianCycle.html"><strong>hamiltonian c</strong></a><strong>ycle</strong>. In the mathematical field, it’s a concept of <a href="https://en.wikipedia.org/wiki/Graph_theory#:~:text=In%20mathematics%2C%20graph%20theory%20is,also%20called%20links%20or%20lines)."><strong>graph theory</strong></a>. A <a href="https://en.wikipedia.org/wiki/Graph"><strong>graph</strong></a> is like a map of nodes. Where each node connects with an edge, and this represents that there is a path between those specific nodes. A graph is used in many ways to represent all kinds of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*_ZLmV0IH7_j8eQUrlG76hg.png" /><figcaption>Graph</figcaption></figure><p>The edges between nodes represent a direct connection between them. We can use a combination of these edges to show a path between two nodes that are not directly connected. A Hamiltonian path is a path in a graph where all nodes are only visited once. A hamiltonian cycle is a cycle of the hamiltonian path where the first node and last node are the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ZF0Gs8ttYKJN1QIiy0msFA.png" /><figcaption>Hamiltonian Cycle</figcaption></figure><h3><strong>How to find a Hamiltonian cycle in an undirected graph?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*t6aGUuYFD5t1ip89fqZ-ug.jpeg" /><figcaption>Kinds of graph</figcaption></figure><p>To find a Hamiltonian cycle in a graph (whenever I use a word graph I am talking about an undirected graph) we can use <a href="https://www.geeksforgeeks.org/backtracking-introduction/#:~:text=Backtracking%20can%20be%20defined%20as,search%20for%20a%20feasible%20solution."><strong>backtracking</strong></a>. In this algorithm, we will keep a log of the path till now, and we will add nodes to it. If the node is not already present in the path we will keep adding nodes. Else we will backtrack to the previous working state and check new nodes with that. In the end, if we can’t find any path with the required conditions we will say there is no possible hamiltonian cycle in this graph.</p><h3><strong>Let see the algorithm in-depth</strong></h3><p>First, let’s create a function to check if a node N is ok to add to the path. We will check if N and the last node have an edge between them. After that, we will see if N is not already present in the path. If both conditions hold, we will return true that it is ok to add N in the path.</p><pre>bool node_check(int node, vector&lt;vector&lt;int&gt;&gt; graph, vector&lt;int&gt; path, int pos){<br>    <br>    <strong>// node is not conneccted to the prev node of the path</strong><br>    if(graph[path[pos - 1]][node] == 0)<br>        return false;<br>        <br>    <strong>// check the node is already visited in the path</strong><br>    for(int i = 0; i &lt; pos; i++)<br>        if(path[i] == node)<br>            return false;<br>            <br>    return true;<br>}</pre><p>Now let’s create a <a href="https://www.geeksforgeeks.org/recursive-functions/"><strong>recursive function</strong></a> to find hamiltonian cyclen in the graph. The base case for this function will be if we have added all nodes in the path. Further, we will check if the last node and first node of the path have an edge between them. If an edge is present between those two nodes we will return true, or else we will return false. Let’s have a look over the recursive step. We will try to add each node in the path and check if it is valid or not. If the node is valid we will add it to the path and look further for the hamiltonian cycle using recursive call. If the function returns false, it shows we can’t find any hamiltonian cycle with the specific node. Then we will remove the node from the path and further check with other nodes.</p><pre>bool find_cycle(vector&lt;vector&lt;int&gt;&gt; graph, vector&lt;int&gt; &amp;path, int pos, int n)  {  <br>    <br>    <strong>// check all node are added to path</strong><br>    if(pos == n){  <br>        // And check the is a edge between first node and the last node of the path<br>        if(graph[path[pos - 1]][path[0]] == 1)  <br>            return true;  <br>        else<br>            return false;  <br>    }  <br>  <br>    <strong>// we will check all node</strong> <br>    for(int v = 0; v &lt; n; v++)  <br>    {  <br>        <strong>// check if node is valid to insert in cycle</strong><br>        if(node_check(v, graph, path, pos))  {  <br>           <br>            <strong>// we will add node to the path </strong><br>            path[pos] = v;  <br>  <br>            <strong>// check further </strong><br>            if(find_cycle(graph, path, pos + 1, n) == true)  <br>                return true;  <br>  <br>            <strong>// if no valid cycle with this node we will remove it from cycle</strong><br>            path[pos] = -1;  <br>        }  <br>    } <br>    <br>    return false; <br>}</pre><p>At last, let’s take a graph as an input and find a hamiltonian cycle in it.</p><p><strong><em>Include the necessary header file while running the code.</em></strong></p><pre>int main() {<br>    <br>    <strong>// to take input of a graph</strong><br>    int n, q;<br>    cin&gt;&gt;n&gt;&gt;q;<br>    vector&lt;vector&lt;int&gt;&gt; graph(n, vector&lt;int&gt;(n));<br>    vector&lt;int&gt; path(n, -1);<br>    path[0]=0;<br>    <br>    for(int i = 0; i &lt; q; i++){<br>        int a, b;<br>        cin&gt;&gt;a&gt;&gt;b;<br>        <br>        graph[a][b] = 1;<br>        graph[b][a] = 1;<br>    }<br> <br> <strong>// if there is a valid cycle</strong><br> if(find_cycle(graph, path, 1, n)){<br>     // print the path<br>     for(int i : path)cout&lt;&lt;i&lt;&lt;&quot; &quot;;<br>     cout&lt;&lt;path[0];<br>     cout&lt;&lt;endl;<br> }<br> else {<br>     cout&lt;&lt;&quot;No valid cycle \n&quot;;<br> }<br> <br> return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*76P7G-IFxXTWo5CeEj3YpQ.png" /><figcaption>Input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*hrZiV9pLYHn0Sa9DKfOcwg.png" /><figcaption>Output</figcaption></figure><p>Now let’s see what so great about the hamiltonian cycle. The property of touching a node only once, or we can say never crossing the path in a hamiltonian cycle provides high usability and can be used in real-life problems. Let’s look over one example, we can use these cycles to create a perfect path for the snake to follow in the snake game, so it will never collide with its tail or the border. This can work as the AI for the <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)"><strong>snake game</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*SyUqOX2JwnZULMKuHm64ZQ.gif" /><figcaption>Snake game</figcaption></figure><p>Feel free to contact me🔥.<strong> </strong><a href="https://www.linkedin.com/in/aryamaan-jain-9330a8190/"><strong>LinkedIn</strong></a><strong> </strong><a href="https://twitter.com/striker_aryu"><strong>Twitter</strong></a><strong> </strong><a href="https://www.instagram.com/striker_aryu/?hl=en"><strong>Instagram</strong></a></p><p>You can check my other projects and stay tuned for more.👀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=340b0033a06d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallax Images]]></title>
            <link>https://medium.com/analytics-vidhya/parallax-images-14e92ebb1bae?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e92ebb1bae</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[parallax]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 02:56:35 GMT</pubDate>
            <atom:updated>2020-11-29T07:14:28.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>A new way to look at boring 2D images</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*T2UzD6ZjHrkmCaJzcSSd7g.gif" /><figcaption>Demo of Parallax image</figcaption></figure><p>We have all seen 3D movies, illusion images, and know-how good they look, and this gave me the idea to make some tool that makes images shift their perspective as the user moves his head. Imagine how cool it will look.</p><p><strong>What will be the effect?</strong><br>We are all familiar with the term <a href="https://en.wikipedia.org/wiki/Parallax#:~:text=Parallax%20(from%20Ancient%20Greek%20%CF%80%CE%B1%CF%81%CE%AC%CE%BB%CE%BB%CE%B1%CE%BE%CE%B9%CF%82,inclination%20between%20those%20two%20lines."><strong>Parallax</strong></a> which is simply the different amount of change in the apparent position of the object, which depends on how far we are from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRiv1s96yDOQREyHXT72TA.jpeg" /><figcaption>Parallax</figcaption></figure><p>So if we can gain the same effect in 2D images that the different layers of images shift differently, then we can have a sense of dept in those images and a cool effect that we want.</p><h3><strong>Let’s break down the process</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*YRE9NHt8zeeUpyj3KVztqA.png" /><figcaption>Depth Map</figcaption></figure><p>So first, we need to break an image into different layers and, we need a depth map of the 2D image for that. A <a href="https://en.wikipedia.org/wiki/Depth_map"><strong>depth map</strong></a> is simply a black and white image where the whiteness of the images tells how close the object is to POV. After we got the basic layers, we need to <a href="https://en.wikipedia.org/wiki/Inpainting#:~:text=Inpainting%20is%20a%20conservation%20process,to%20present%20a%20complete%20image."><strong>inpaint</strong></a> the missing parts from each layer. So finally, we have broken a single image into different layers. Now we can show different layers on top of each other, which will look the same as the original image. Now we can use our camera for <strong>face detection</strong> and measure how the movement of the user’s head and then shift those layers to match the new POV.</p><h3><strong>Let’s see how to code this tool</strong></h3><p>So first, we need to import some files, So copy this code into your file.<br>I recommend using OpenCV of version 4.1.0.25 because there are few bugs in later versions when we use face_cascade. For other libraries, you can use any version but try to use the newer ones.</p><pre>import os, sys</pre><pre>import numpy as np<br>import pygame as pg<br>import cv2</pre><p>Now we need to load the image and the <strong>depth map </strong>and resize them to match the size. For now, we will provide a depth map to our code, but you can generate your own using a model <a href="https://github.com/intel-isl/MiDaS"><strong>MiDaS</strong></a>, which I have used in my main tool. You can have a look at my <a href="https://github.com/strikeraryu/Parallax_Image"><strong>GitHub repo</strong></a>.</p><pre>img = cv2.imread(&#39;moon.jpg&#39;, flags=cv2.CV_8UC4)<br>depth_map = cv2.imread(&#39;moon_depth_map.png&#39;)<br>depth_map = cv2.cvtColor(depth_map,cv2.COLOR_RGB2GRAY)<br>img = cv2.resize(img, depth_map.shape[:2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41zyuBp44yolCGsm9szgmA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-Zq9r6gFsPzSeogDv6W4hA.png" /></figure><p>Now, after we have loaded the depth map, we can create masks for different layers by thresholding the depth map at different Thresholds.<br>While making one layer we need two masks, one of this layer and the second of the previous layer to inpaint the missing parts. We will take the last layer outside the loop so we can extract all the remaining parts in this layer.</p><pre>   <br>layers = []     <br>prev_thres = 255<br>div=30<br>     <br>for thres in range(255 - div, 0, -div):        <br>   ret, mask = cv2.threshold(depth_map, thres, 255,          cv2.THRESH_BINARY)<br>        <br>   ret, prev_mask = cv2.threshold(depth_map, prev_thres, 255, cv2.THRESH_BINARY)  <br>       <br>   prev_thres = thres        <br>   inpaint_img = cv2.inpaint(img, prev_mask, 10, cv2.INPAINT_NS)<br>   layer = cv2.bitwise_and(inpaint_img, inpaint_img, mask = mask) </pre><pre>   layers.append(conv_cv_alpha(layer, mask))  <br>    <br># adding last layer <br>   <br>mask = np.zeros(depth_map.shape, np.uint8)    <br>mask[:,:] = 255   <br> <br>ret, prev_mask = cv2.threshold(depth_map, prev_thres, 255, cv2.THRESH_BINARY)<br>     <br>inpaint_img = cv2.inpaint(img, prev_mask, 10, cv2.INPAINT_NS)    layer = cv2.bitwise_and(inpaint_img, inpaint_img, mask = mask)</pre><pre>layers.append(conv_cv_alpha(layer, mask))<br>     <br>layers = layers[::-1]</pre><p>We have reversed the layers so we can arrange them in order of <strong>last to the first layer</strong>. While we are adding the layer to the list, we are using a function ‘<strong>conv_cv_alpha</strong>’ this will add the alpha value <strong>(make RGB to RGBA)</strong> and make parts of the layer transparent using the mask.</p><pre>def conv_cv_alpha(cv_image, mask):    <br>    b, g, r = cv2.split(cv_image)    <br>    rgba = [r, g, b, mask]    <br>    cv_image = cv2.merge(rgba,4)    <br>          <br>    return cv_image</pre><p>Now comes the part of face detection and showing the image. For face detection, we will use <a href="http://www.willberger.org/cascade-haar-explained/#:~:text=Haar%20Cascade%20is%20a%20machine,of%20Simple%20Features%22%20in%202001."><strong>haarcascade</strong></a>. download them from their official <a href="https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml">Github repository</a>.</p><p>To download them, right-click “Raw” =&gt; “Save link as”. Make sure they are in your working directory.</p><p>Now we will load haar cascade for face detection and make a function that will return the face-rect from the image.</p><pre>face_cascade = cv2.CascadeClassifier( &#39;haarcascade_frontalface_default.xml&#39;)   <br><br>def get_face_rect(img):    <br>    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    <br>    face_rects = face_cascade.detectMultiScale(gray_img, 1.3, 5)<br>    if len(face_rects) == 0:         <br>        return ()</pre><pre>    return face_rects[0]</pre><p>Now we have to show the image that will shift according to the user’s head. We will use <strong>OpenCV</strong> to read cam and then <strong>Pygame</strong> to render each frame on top of each other. To calculate the shift for each layer, we will calculate the shift of head from the center of the frame and then scale it down to get a small shift value. After that, we will multiply the index value of each layer to get the shift value for the respective layer, you can also multiply some constant value in that for better results.</p><p>We will create a Pygame window slightly smaller than the original image and load the camera. We have used <strong>scale</strong>, so you change its value to make the final result bigger.</p><pre>scale = 1<br>off_set = 20</pre><pre>width, height = layers[0].get_width(), layers[0].get_height()        win = pg.display.set_mode((int((width - off_set)*scale), int((height - off_set)*scale)))    <br>pg.display.set_caption(&#39;Parallax_image&#39;)</pre><pre>scaled_layers = []    <br>for layer in layers: <br>             scaled_layers.append(pg.transform.scale(layer, (int(width*scale), int(height*scale))))</pre><pre>cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)</pre><p>We will set some constants. you can play with these constants to get different results.</p><pre>x_transform = True     # allow shift in x-axis<br>y_transform = False    # allow shift in y-axis<br>sens = 50              # the amount of scale down of shift value<br>show_cam = False       # show your face cam<br>shift_x = 0    <br>shift_y = 0    <br>run = True</pre><p>Finally, the main loop to render all layers.</p><pre>while run:<br>    for event in pg.event.get():<br>        if event.type==pg.QUIT:<br>            run = False</pre><pre>    ret, frame = cap.read()<br>    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>    initial_pos = (frame.shape[0]/2, frame.shape[1]/2)<br>    face_rect = get_face_rect(frame)</pre><pre>    if len(face_rect) != 0:<br>        x,y,w,h, = face_rect<br>        face_rect_frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (255,255,0), 3)</pre><pre>        shift_x = (initial_pos[0] - (x + w/2))/(sens*scale)<br>        shift_y = (initial_pos[1] - (y + h/2))/(sens*scale)</pre><pre>    win.fill((255, 255, 255))<br>                 <br>    for i, layer in enumerate(scaled_layers):<br>        new_x = -off_set/2<br>        new_y = -off_set/2<br>        if x_transform:<br>            new_x = 0 + shift_x*i<br>        if y_transform:<br>            new_y = 0 + shift_y*i<br>        win.blit(layer, (new_x, new_y)) <br>        <br>   face_rect_frame = cv2.resize(face_rect_frame, (100, 100))<br>   if show_cam:<br>       win.blit(conv_cv_pygame(face_rect_frame), (0, 0))<br>   pg.display.update()</pre><pre>cap.release()<br>cv2.destroyAllWindows()<br>pg.quit()</pre><p>There it is, the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H6L0UFuTpWzD_IB0EFqSvg.gif" /><figcaption>Final Result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*24XN55FuLp0IKIa3PQefPw.gif" /><figcaption>demo for different image</figcaption></figure><p>I have created a more advanced version of this tool where you can just choose the image and it will automatically create the parallax image, the depth map will be automatically generated.</p><p>You can check more on my <a href="https://github.com/strikeraryu/Parallax_Image"><strong>GitHub</strong></a> repo.</p><p>Feel free to contact me🔥.<strong> </strong><a href="https://www.linkedin.com/in/aryamaan-jain-9330a8190/"><strong>LinkedIn</strong></a><strong> </strong><a href="https://twitter.com/striker_aryu"><strong>Twitter</strong></a><strong> </strong><a href="https://www.instagram.com/striker_aryu/?hl=en"><strong>Instagram</strong></a></p><p>You can check my other projects and stay tuned for more.👀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e92ebb1bae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/parallax-images-14e92ebb1bae">Parallax Images</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReVamp — Virtual Renovation]]></title>
            <link>https://striker-aryu56.medium.com/revamp-virtual-renovation-64bfd0f924d7?source=rss-61742cf1b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bfd0f924d7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[renovations]]></category>
            <dc:creator><![CDATA[Striker]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 18:32:53 GMT</pubDate>
            <atom:updated>2020-11-12T18:32:53.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>ReVamp — Virtual Renovation</h3><h4><em>Using augmented reality to move objects</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aAXgszzReEhlWxwl" /><figcaption>Photo by <a href="https://unsplash.com/@uniboa?utm_source=medium&amp;utm_medium=referral">UNIBOA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The virtual world is getting bigger. Everything from rocket simulation to grocery shopping is virtual now, and now a new thing is getting added to this list. Moving your furniture can be a tough job, and trying a new look on a virtual platform can give a new dimension and make it a little easier to do.</p><p>There are a few layers when you wish to give your room a new look. Usually, you want to add new furniture or move the old one to a new location, but it gets tricky when you want a perfect setting for your furniture or wants to buy a new one that will perfectly fit in your room’s theme. But we can add a virtual element in this and make visualization easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8-2JRy5w3newl6aUCM8QaQ.gif" /></figure><h3>What ReVamp brings to the table?</h3><p>In <strong>ReVamp</strong>, you can make a virtual element of your furniture using your camera. You can click on the object, and it will create a virtual overlay that you can move using your camera. It also allows you to use external images so you can use pictures of furniture you wish to buy to make the virtual overlay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pqIxyQN2sucoxHL5o0UkA.png" /></figure><h3>Technical view of ReVamp</h3><p>I was working on this project and finished a software version of <strong>ReVamp</strong><br>using <a href="https://www.python.org/"><strong>Python</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LRU7FVx5gkM2_wh3QI3kCA.gif" /><figcaption>ReVamp Demo</figcaption></figure><p><strong>Let’s see how ReVamp works.</strong></p><p>I used <a href="https://docs.opencv.org/master/d6/d00/tutorial_py_root.html"><strong>OpenCV</strong></a> to get the camera feed of the device or the IP cam for better quality. Using this, I get a continuous stream of frames that I use to extract the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gcp4JHIl804ok3-_du8qBQ.png" /><figcaption>Connection with camera</figcaption></figure><p>Extracting the object from a picture is tricky so, I tried different approaches to do that.</p><p><strong>Flood fill with the color difference</strong><br>I tried the flood fill algorithm with different <a href="https://en.wikipedia.org/wiki/Color_difference">color difference formula</a>.<br>I used <strong>Euclidean distance</strong> and <strong>Red Mean</strong>. Euclidean distance was better for computer-generated images, and Red Mean was good for the pictures taken from the camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aq9lUexFIRCck7AqqAG0uA.png" /><figcaption>Euclidean distance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoIa3eICpOzbjDLUaQ7OcQ.png" /><figcaption>Red Mean</figcaption></figure><p>All over the result were not as good as the <a href="https://photographylife.com/what-is-noise-in-photography">noise in the picture</a> is left out.</p><p><strong>Adding edge Detection</strong><br>The next big step in the results was adding edge-detection. Now to extract an object, I run a flood fill algorithm with low Delta-e on edge and, then I draw the contour on the resulted CV-MAT. Finally, we get a mask of the object, and applying that on the original image gives us the required virtual overlay of the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*BUqzEilN-6joMnaXhASsvQ.png" /><figcaption>Results after adding <strong>edge Detection</strong></figcaption></figure><p>There were a few flaws in this approach.</p><p><strong>Adding convolution filters and contour smoothing</strong><br>Adding convolution filters and contour smoothing removes the flaw in the previous approach. Before using the above approach, I preprocess the image with a different convolution filter. I tried many filters and, smooth + edge enhance works the best as it removes the noise and sharpens the edge. After this, I also added contour smoothing while creating the mask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*9niJd1PAt98hxW_BkpnCpA.png" /><figcaption>Results after <strong>adding convolution filters and contour smoothing</strong></figcaption></figure><p>The results were fine on different images. Still, there were outliers images where results were not up to the mark. While I was trying different approaches, I saw an idea similar to mine getting popular. So I started looking at the technologies used in that. There I found <a href="https://github.com/NathanUA/BASNet"><strong>BASNet</strong></a>, which provides very good results on object detection and segmentation.</p><p><strong>Using BASNet</strong><br><a href="https://github.com/NathanUA/BASNet"><strong>BASNet</strong></a> is a deep <a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">Convolutional neural network</a> used for salient object detection and accurately predict the fine structures with clear boundaries.<br>Using BASNet gave the best results for creating the overlay.</p><blockquote>Deep Convolutional Neural Networks have been adopted for salient object detection and achieved the state-of-the-art performance. Most of the previous works however focus on region accuracy but not on the boundary quality.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*jallgMWnqA4cu95tKWT_FQ.png" /><figcaption>Results using BASNet</figcaption></figure><p>And finally, the tricky part of the ReVamp was ready. Now I have to implement this in ReVamp and create a usable tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*wgaF-_NxHg5-72t0i4SLDA.gif" /></figure><p><strong>Interface/UI</strong></p><p>Now to create an interface, I used the <a href="https://www.pygame.org/docs/"><strong>Pygame</strong></a> library of python, I didn’t use other interfacing libraries like <a href="https://docs.python.org/3/library/tkinter.html"><strong>Tkinter</strong></a> as I want a little flexible UI with a different feature. So, I create my UI library for Pygame that provided me the flexibility I needed. Further, I used multi treading to make the flow of ReVamp seamless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3d6F-uUUFjCscoUaDJ5Hdw.png" /><figcaption>ReVamp Demo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEe0eX7S9pI6EnhUCkLm3Q.png" /><figcaption>Using external images</figcaption></figure><p>I used different techniques to provide the basic functionality of ReVamp like using external images to create the overlay, save/load overlay, basic camera function, and some basic function on the overlay.</p><p><strong>You can check more about ReVamp</strong></p><p><a href="https://github.com/strikeraryu/ReVamp"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bfd0f924d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>