<?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[Unlearning Labs - Medium]]></title>
        <description><![CDATA[Our open source initiative to create a comprehensive content for full stack engineering. - Medium]]></description>
        <link>https://medium.com/unlearninglabs?source=rss----3459ef45b2a0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Unlearning Labs - Medium</title>
            <link>https://medium.com/unlearninglabs?source=rss----3459ef45b2a0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:30:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/unlearninglabs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Vicious Circle of Infinite AI Code Reviews – Handwritten Post :)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/unlearninglabs/the-vicious-circle-of-infinite-ai-code-reviews-handwritten-post-06a75f98d52a?source=rss----3459ef45b2a0---4"><img src="https://cdn-images-1.medium.com/max/1536/1*4lXTG9WLiZPAgEXU9Ggt4Q.png" width="1536"></a></p><p class="medium-feed-snippet">Vibe coding solves the problem of writing code. But does it create a bigger problem of knowing when to stop?</p><p class="medium-feed-link"><a href="https://medium.com/unlearninglabs/the-vicious-circle-of-infinite-ai-code-reviews-handwritten-post-06a75f98d52a?source=rss----3459ef45b2a0---4">Continue reading on Unlearning Labs »</a></p></div>]]></description>
            <link>https://medium.com/unlearninglabs/the-vicious-circle-of-infinite-ai-code-reviews-handwritten-post-06a75f98d52a?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/06a75f98d52a</guid>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 05:42:08 GMT</pubDate>
            <atom:updated>2026-11-07T05:42:08.385Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[What Is Jev by TypeSafe AI? Understanding Fast, Structured Decisions in AI Applications]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/unlearninglabs/what-is-jev-by-typesafe-ai-understanding-fast-structured-decisions-in-ai-applications-2a45fcbc0067?source=rss----3459ef45b2a0---4"><img src="https://cdn-images-1.medium.com/max/1122/1*ZKFtd2aFN0cNcfM0b9R4vQ.png" width="1122"></a></p><p class="medium-feed-snippet">System 1 and System 2 thinking, a practical support-ticket example, and where Jev could fit into AI agents.</p><p class="medium-feed-link"><a href="https://medium.com/unlearninglabs/what-is-jev-by-typesafe-ai-understanding-fast-structured-decisions-in-ai-applications-2a45fcbc0067?source=rss----3459ef45b2a0---4">Continue reading on Unlearning Labs »</a></p></div>]]></description>
            <link>https://medium.com/unlearninglabs/what-is-jev-by-typesafe-ai-understanding-fast-structured-decisions-in-ai-applications-2a45fcbc0067?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a45fcbc0067</guid>
            <category><![CDATA[token]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[jevs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 20:21:13 GMT</pubDate>
            <atom:updated>2026-09-24T20:21:12.999Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Does anyone still reads]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/unlearninglabs/does-anyone-still-reads-a3c3374751a9?source=rss----3459ef45b2a0---4"><img src="https://cdn-images-1.medium.com/max/600/1*GI9F_MSsCCODi99rE20f_A.png" width="600"></a></p><p class="medium-feed-snippet">A handwritten story</p><p class="medium-feed-link"><a href="https://medium.com/unlearninglabs/does-anyone-still-reads-a3c3374751a9?source=rss----3459ef45b2a0---4">Continue reading on Unlearning Labs »</a></p></div>]]></description>
            <link>https://medium.com/unlearninglabs/does-anyone-still-reads-a3c3374751a9?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3c3374751a9</guid>
            <category><![CDATA[feelings]]></category>
            <category><![CDATA[human-touch]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[writers-block]]></category>
            <category><![CDATA[personal-story]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 05:40:10 GMT</pubDate>
            <atom:updated>2026-09-18T05:47:29.756Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[All about Core NodeJS — Part 2]]></title>
            <link>https://medium.com/unlearninglabs/all-about-core-nodejs-part-2-6d61d3d913f7?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/6d61d3d913f7</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[first-principles]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 06:07:34 GMT</pubDate>
            <atom:updated>2025-11-17T06:30:41.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>All about Core NodeJS — Part 2</h3><p><em>Your friendly neighborhood Node.js mentor 😄</em></p><blockquote><strong><em>If you are reading Part 2, congratulations — you survived Part 1.<br> Uncle Ben would be proud: “With great Node power comes great responsibility.”</em></strong></blockquote><p>In Part 1 we explored the fundamentals of Node — modules, require, process, buffers, streams, logging, benchmarking, and even built a tiny video streamer.</p><p>You can read Part 1 here <a href="https://codeburst.io/all-about-core-nodejs-part-1-b9f4b0a83278">All about Core NodeJS — Part 1. Learn all about essential NodeJS in… | by Rajesh Pillai | codeburst</a></p><p>In Part 2, we continue our journey deeper into the Node core — one concept at a time — explained from <em>first principles</em>, beginner-friendly but deep enough for senior engineers.</p><p>This article is your <strong>single-point reference</strong> for low-level Node concepts that every developer should know.</p><h3>⭐ Table of Contents</h3><ol><li>Networking in Node (from first principles)</li><li>Understanding TCP vs HTTP</li><li>Building your own TCP Server &amp; Client</li><li>A Minimal HTTP server (no frameworks)</li><li>EventEmitter Deep Dive (from usage → implementation)</li><li>Understanding the Event Loop</li><li>Microtasks vs Macrotasks</li><li>process.nextTick() vs setImmediate()</li><li>Child Processes — spawn, exec, fork</li><li>Clusters — scaling Node using multiple processes</li><li>Recap + What’s Coming in Part 3</li></ol><h3>1. Networking in Node (First Principles)</h3><h3>Why this matters</h3><p>Everything in Node eventually touches networking:</p><ul><li>REST APIs</li><li>WebSockets</li><li>Chat apps</li><li>Microservices</li><li>Database clients</li><li>Realtime dashboards</li><li>Even Express/Fastify sit <em>on top</em> of Node’s low-level net/http modules</li></ul><p>If you understand the base layers, everything else becomes easier.</p><h3>2. TCP vs HTTP — What’s the Difference?</h3><p>Let’s start simple.</p><h3>🔌 Analogy</h3><p><strong>TCP is the phone connection.<br>HTTP is the conversation.</strong></p><ul><li>TCP: “Connect me to this address.”</li><li>HTTP: “GET /index.html please.”</li></ul><p>Node gives you access to both layers.</p><h3>3. Build a Raw TCP Server (net module)</h3><p>We always start with <strong>API → Usage → Explanation</strong>.</p><h3>TCP Server</h3><p>tcp-server.js</p><pre>const net = require(&quot;net&quot;);<br><br>// Create a TCP server<br>const server = net.createServer((socket) =&gt; {<br>  console.log(&quot;New connection!&quot;);<br><br>  socket.write(&quot;Hello from Node TCP Server!\n&quot;);<br><br>  // Listen for incoming data<br>  socket.on(&quot;data&quot;, (data) =&gt; {<br>    console.log(&quot;Client says:&quot;, data.toString());<br>  });<br><br>  // Handle client disconnect<br>  socket.on(&quot;end&quot;, () =&gt; {<br>    console.log(&quot;Client disconnected&quot;);<br>  });<br><br>  // Always handle socket errors<br>  socket.on(&quot;error&quot;, (err) =&gt; {<br>    console.error(&quot;Socket error:&quot;, err);<br>  });<br>});<br><br>// Handle server-level errors (e.g., port already in use)<br>server.on(&quot;error&quot;, (err) =&gt; {<br>  console.error(&quot;Server error:&quot;, err);<br>});<br><br>server.listen(3000, () =&gt; {<br>  console.log(&quot;TCP server running on port 3000&quot;);<br>});</pre><h3>TCP Client</h3><p>tcp-client.js</p><pre>const net = require(&quot;net&quot;);<br><br>const client = net.createConnection({ port: 3000 }, () =&gt; {<br>  console.log(&quot;Connected to server!&quot;);<br>  client.write(&quot;Hello server!&quot;);<br>});<br><br>// Handle incoming messages<br>client.on(&quot;data&quot;, (data) =&gt; {<br>  console.log(&quot;Received:&quot;, data.toString());<br>});<br><br>// Graceful disconnect<br>client.on(&quot;end&quot;, () =&gt; {<br>  console.log(&quot;Disconnected from server&quot;);<br>});<br><br>// Always handle errors<br>client.on(&quot;error&quot;, (err) =&gt; {<br>  console.error(&quot;Client error:&quot;, err);<br>});</pre><h3>Run:</h3><pre>node tcp-server.js<br>node tcp-client.js</pre><h3>How it works</h3><ul><li>net.createServer creates a raw TCP server</li><li>socket is a bidirectional stream</li><li>.write() sends data</li><li>.on(&quot;data&quot;) receives data</li><li>.on(&quot;end&quot;) triggers on disconnect</li></ul><p>This is the foundation for:</p><ul><li>Redis protocol</li><li>MySQL protocol</li><li>MongoDB wire protocol</li><li>WebSocket handshake</li><li>Multiplayer game servers</li></ul><h3>4. Minimal HTTP Server (no frameworks)</h3><p>Node’s built-in http module is built <strong>on top of TCP</strong>.</p><p>server.js</p><pre>const http = require(&quot;http&quot;);<br><br>const server = http.createServer((req, res) =&gt; {<br>  console.log(&quot;Incoming:&quot;, req.method, req.url);<br><br>  // Important: recommended for modern HTTP keep-alive behavior<br>  res.setHeader(&quot;Connection&quot;, &quot;keep-alive&quot;);<br><br>  res.writeHead(200, { &quot;Content-Type&quot;: &quot;text/plain&quot; });<br>  res.end(&quot;Hello HTTP!&quot;);<br>});<br><br>server.listen(4000, () =&gt; {<br>  console.log(&quot;Server running at http://localhost:4000&quot;);<br>});</pre><p>Header over to your browser or CURL <a href="http://localhost:4000/">http://localhost:4000</a> and you will get</p><pre>Hello HTTP!</pre><h3>Explanation</h3><ul><li>req is a readable stream</li><li>res is a writable stream</li><li>Node handles header parsing &amp; connection management</li></ul><p>This is how Express/Fastify/Koa ultimately work behind the scenes.</p><h3>5. EventEmitter — The Beating Heart of Node</h3><p>Everything in Node is event-driven:</p><ul><li>Streams</li><li>Timers</li><li>Sockets</li><li>HTTP</li><li>FS operations</li><li>Child processes</li><li>Clusters</li><li>Even custom libraries</li></ul><p>Understanding EventEmitter is like having Node’s “source code decoder ring”.</p><h3>Usage First</h3><p>events-demo.js</p><pre>const EventEmitter = require(&quot;events&quot;);<br><br>class MyEmitter extends EventEmitter {}<br><br>const emitter = new MyEmitter();<br><br>// Register listener<br>emitter.on(&quot;greet&quot;, (name) =&gt; {<br>  console.log(`Hello ${name}`);<br>});<br><br>// Trigger event<br>emitter.emit(&quot;greet&quot;, &quot;Rajesh&quot;);</pre><h3>Your Own Mini EventEmitter</h3><p>mini-event-emitter.js</p><pre>class MiniEmitter {<br>  constructor() {<br>    this.events = {};<br>  }<br><br>  // Register listener<br>  on(event, listener) {<br>    if (!this.events[event]) this.events[event] = [];<br>    this.events[event].push(listener);<br>  }<br><br>  // Remove listener<br>  off(event, listener) {<br>    if (!this.events[event]) return;<br>    this.events[event] = this.events[event].filter((l) =&gt; l !== listener);<br>  }<br><br>  // Register one-time listener<br>  once(event, listener) {<br>    const wrapper = (...args) =&gt; {<br>      listener(...args);<br>      this.off(event, wrapper);<br>    };<br>    this.on(event, wrapper);<br>  }<br><br>  // Emit event<br>  emit(event, ...args) {<br>    const listeners = this.events[event] || [];<br>    for (const fn of listeners) fn(...args);<br>  }<br>}<br><br>// Usage<br>const e = new MiniEmitter();<br>e.on(&quot;ping&quot;, (msg) =&gt; console.log(&quot;Received:&quot;, msg));<br>e.emit(&quot;ping&quot;, &quot;Hello world&quot;);</pre><p>A detailed tutorial on how to code your own event emitter is posted here <br><a href="https://medium.com/unlearninglabs/how-to-code-your-own-event-emitter-in-node-js-a-step-by-step-guide-e13b7e7908e1">How to code your own event emitter in Node.js: a step-by-step guide | by Rajesh Pillai | Unlearning Labs | Medium</a></p><h3>6. Event Loop (Explained Like a Human)</h3><blockquote><em>If terms like </em>Queue<em>, </em>Microtasks<em>, </em>Timers<em>, </em>Poll Phase<em>, </em>libuv<em> scare you — relax. We’re starting from first principles.</em></blockquote><h3>Simple ASCII View</h3><pre>┌──────────────────────────────┐<br>│          Application         │<br>└───────────────┬──────────────┘<br>                │<br>        Event Loop (libuv)<br>                │<br>┌───────────────┴─────────────────────────┐<br>│ timers → I/O → idle → poll → check → close │<br>└──────────────────────────────────────────┘</pre><p>This cycle runs continuously.</p><h3>Execution Order Example</h3><pre>console.log(&quot;A&quot;);<br>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);<br>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));<br>process.nextTick(() =&gt; console.log(&quot;D&quot;));<br>console.log(&quot;E&quot;);</pre><p><strong>Output:</strong></p><pre>A<br>E<br>D<br>C<br>B</pre><p>Why?</p><ul><li>nextTick → runs before any microtask</li><li>Promise → microtask</li><li>Timeout → macrotask</li></ul><h3>7. Microtasks vs Macrotasks</h3><h3>Microtasks</h3><ul><li>Promises</li><li>process.nextTick()</li></ul><p>They run <strong>after every phase</strong>.</p><h3>Macrotasks</h3><ul><li>setTimeout</li><li>setInterval</li><li>setImmediate</li><li>I/O callbacks</li></ul><p>They run <strong>in the event loop cycle</strong>.</p><p>Analogy:</p><ul><li>Microtasks = VIP fast-lane</li><li>Macrotasks = normal queue</li></ul><h3>8. process.nextTick() vs setImmediate()</h3><h3>process.nextTick()</h3><p>Runs <em>before</em> the event loop continues.</p><h3>setImmediate()</h3><p>Runs <em>after</em> the poll phase.</p><h3>Example</h3><pre>setImmediate(() =&gt; console.log(&quot;A&quot;));<br>process.nextTick(() =&gt; console.log(&quot;B&quot;));<br>console.log(&quot;C&quot;);</pre><p>Output:</p><pre>C<br>B<br>A</pre><p>Use nextTick carefully — it can starve the event loop.</p><h3>9. Child Processes — spawn, exec, fork</h3><p>Node is single-threaded, but child processes let you run other programs or scripts.</p><h3>9.1 spawn()</h3><p>Best for streaming large output.</p><p>spawn-demo.js</p><pre>const { spawn } = require(&quot;child_process&quot;);<br>const os = require(&quot;os&quot;);<br><br>// Pick correct shell based on OS<br>const isWindows = os.platform() === &quot;win32&quot;;<br><br>const command = isWindows ? &quot;cmd.exe&quot; : &quot;sh&quot;;<br>const args = isWindows ? [&quot;/c&quot;, &quot;dir&quot;] : [&quot;-c&quot;, &quot;ls -l&quot;];<br><br>const child = spawn(command, args);<br><br>// Stream output<br>child.stdout.on(&quot;data&quot;, (data) =&gt; {<br>  console.log(&quot;OUT:&quot;, data.toString());<br>});<br><br>// Stream errors<br>child.stderr.on(&quot;data&quot;, (data) =&gt; {<br>  console.log(&quot;ERR:&quot;, data.toString());<br>});<br><br>// Handle spawn errors<br>child.on(&quot;error&quot;, (err) =&gt; {<br>  console.error(&quot;Spawn error:&quot;, err);<br>});</pre><h3>9.2 exec()</h3><p>Buffers full output (not good for huge data).</p><p>exec-demo.js</p><pre>const { exec } = require(&quot;child_process&quot;);<br>const os = require(&quot;os&quot;);<br><br>const isWindows = os.platform() === &quot;win32&quot;;<br><br>// Correct platform-specific command<br>const command = isWindows ? &quot;dir&quot; : &quot;ls -l&quot;;<br><br>exec(command, (err, stdout, stderr) =&gt; {<br>  if (err) {<br>    console.error(&quot;Error:&quot;, err);<br>    return;<br>  }<br><br>  // stdout is buffered fully (unlike spawn)<br>  console.log(&quot;Output:\n&quot;, stdout);<br><br>  if (stderr) {<br>    console.log(&quot;Errors:\n&quot;, stderr);<br>  }<br>});</pre><h4>The Difference Between spawn and exec</h4><h4>✔ spawn()</h4><p>Like watching a YouTube video <strong>stream</strong> — data comes in chunks while it plays.</p><h4>✔ exec()</h4><p>Like waiting for the entire movie to download first — then watching it.</p><h3>Memory &amp; Performance Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*ug57oksJDh9HTDKZTL8Lzw.png" /></figure><h3>When to Use What?</h3><h4>Use spawn() when:</h4><ul><li>You expect <strong>large output</strong></li><li>You need <strong>real-time output</strong></li><li>You are processing streams (logs, file reads, ffmpeg, tail -f)</li><li>Performance matters</li></ul><p>Examples:</p><ul><li>ffmpeg</li><li>git clone</li><li>tail -f /var/log/syslog</li><li>Video/audio processing</li><li>Huge directory listing</li></ul><h3>Use exec() when:</h3><ul><li>Output is small (like “version” commands)</li><li>You want shell features (pipes, redirects)</li><li>You want a simple one-time result</li></ul><p>Examples:</p><ul><li>exec(&quot;node -v&quot;)</li><li>exec(&quot;npm -v&quot;)</li><li>exec(&quot;echo hello&quot;)</li></ul><h3>9.3 fork()</h3><p>Runs another Node script &amp; communicates over IPC.</p><p>fork-demo.js</p><pre>const { fork } = require(&quot;child_process&quot;);<br>const path = require(&quot;path&quot;);<br><br>// Resolve worker.js relative to the current file<br>const child = fork(path.join(__dirname, &quot;worker.js&quot;));<br><br>child.on(&quot;message&quot;, (msg) =&gt; {<br>  console.log(&quot;From child:&quot;, msg);<br>});<br><br>child.on(&quot;error&quot;, (err) =&gt; {<br>  console.error(&quot;Child error:&quot;, err);<br>});<br><br>child.on(&quot;exit&quot;, (code) =&gt; {<br>  console.log(&quot;Child exited with code:&quot;, code);<br>});<br><br>// Send a message to child<br>child.send({ task: &quot;start&quot; });</pre><p>Let’s also create the worker.js</p><pre>// worker.js<br><br>// Listen for messages from parent<br>process.on(&quot;message&quot;, (msg) =&gt; {<br>  console.log(&quot;Child received:&quot;, msg);<br><br>  if (msg.task === &quot;start&quot;) {<br>    // Do some work...<br>    const result = { status: &quot;done&quot;, at: new Date().toISOString() };<br><br>    // Send result back to parent<br>    process.send(result);<br>  }<br>});</pre><h3>10. Clusters — Scale Node Across CPU Cores</h3><p>Node is single-threaded. Your CPU is not.<br> Cluster allows one worker per CPU core.</p><h3>cluster.js</h3><pre>const cluster = require(&quot;cluster&quot;);<br>const http = require(&quot;http&quot;);<br>const os = require(&quot;os&quot;);<br><br>if (cluster.isMaster) {<br>  const cpuCount = os.cpus().length;<br>  console.log(`Master starting ${cpuCount} workers...`);<br><br>  // Spawn workers<br>  for (let i = 0; i &lt; cpuCount; i++) {<br>    cluster.fork();<br>  }<br><br>  // Restart worker if it dies<br>  cluster.on(&quot;exit&quot;, (worker, code, signal) =&gt; {<br>    console.log(<br>      `Worker ${worker.process.pid} died (code=${code}, signal=${signal}). Restarting...`<br>    );<br>    cluster.fork();<br>  });<br><br>} else {<br>  const server = http.createServer((req, res) =&gt; {<br>    console.log(`Worker ${process.pid} handling: ${req.method} ${req.url}`);<br><br>    if (req.url === &quot;/crash&quot;) {<br>      console.log(`Worker ${process.pid} crashing on purpose...`);<br><br>      // OPTION 1: Hard exit<br>      // process.exit(1);<br><br>      // OPTION 2: Throw an error (more obvious in logs)<br>      setTimeout(() =&gt; {<br>        throw new Error(`Simulated crash in worker ${process.pid}`);<br>      }, 0);<br><br>      // We don&#39;t send a response; the connection will be broken by the crash<br>      return;<br>    }<br><br>    // Normal response<br>    res.statusCode = 200;<br>    res.setHeader(&quot;Content-Type&quot;, &quot;text/plain&quot;);<br>    res.end(`Served by worker ${process.pid}\n`);<br>  });<br><br>  server.listen(3000, () =&gt; {<br>    console.log(`Worker ${process.pid} started on port 3000`);<br>  });<br>}</pre><p>Hit the browser and go to</p><pre>http://localhost:3000</pre><p>The browser might say</p><pre>Served by worker 16936</pre><p>Refresh again you will see different ID’s.</p><p>Simulate CRASH</p><pre>http://localhost:3000/crash</pre><p>You will see the log on server</p><pre>Worker 8792 crashing on purpose..<br></pre><p>When the process crashes</p><ul><li>/crash route matched</li><li>Worker crashed</li><li>Master saw it via cluster.on(&quot;exit&quot;)</li><li>New worker started</li></ul><h3>⭐ Recap</h3><p>Today you learned:</p><ul><li>How Node handles TCP networking</li><li>How to build a TCP server and client</li><li>How HTTP servers work underneath Express</li><li>How EventEmitter works (and built your own version)</li><li>Event loop internals</li><li>Microtask vs Macrotask queues</li><li>nextTick vs setImmediate</li><li>Child processes (spawn, exec, fork)</li><li>Clusters for scaling Node applications</li></ul><p>If you’re still reading — you’re awesome 🔥<br>Most developers skip these fundamentals… and then wonder why their app behaves weirdly.</p><h3>Coming in Part 3 and Part 4</h3><ul><li>File System Deep Dive</li><li>Streams (advanced): backpressure, flow control</li><li>Build a custom Readable/Writable/Transform stream</li><li>AsyncLocalStorage</li><li>Building your own mini Express framework</li><li>Node performance tuning</li><li>Memory leaks &amp; profiling</li><li>A complete mini-project to tie everything together</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d61d3d913f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/all-about-core-nodejs-part-2-6d61d3d913f7">All about Core NodeJS — Part 2</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Frontend Code That’s Easy to Test (React + Phoenix LiveView (or HTMX or anything else)]]></title>
            <link>https://medium.com/unlearninglabs/writing-frontend-code-thats-easy-to-test-react-phoenix-liveview-or-htmx-or-anything-else-b9008f3bf4a4?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/b9008f3bf4a4</guid>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[frontend-testing]]></category>
            <category><![CDATA[cypressjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 04:58:27 GMT</pubDate>
            <atom:updated>2025-10-09T04:58:23.190Z</atom:updated>
            <content:encoded><![CDATA[<p><em>with Cypress or Playwright for E2E or whatever your preferred tool is</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*iQB8vTNKNfKPoTfaMMqMdw.png" /></figure><p>If QA automation is an afterthought, your selectors become brittle and tests flaky. Design your UI so that <strong>the DOM exposes stable, intention-revealing hooks</strong> from day one.</p><blockquote>Let’s give our QA the same stability guarantees you give your public APIs</blockquote><p>Below is a compact playbook you can drop into React or Phoenix LiveView projects (or any other UI library, components, frameworks you are using)</p><p>NOTE: This is applicable to Vue, Solid, Svelte, Preact or anything else as well.</p><h3>1) Selector Strategy (Hierarchy of Preference)</h3><p><strong>a. Accessible selectors (best):</strong> getByRole, name, labels</p><ul><li>Benefits: user-centric, resilient, improves a11y.</li><li>Example: a “Save” button → &lt;button aria-label=&quot;Save changes&quot;&gt;Save&lt;/button&gt;</li></ul><p><strong>b. Stable </strong><strong>data-* hooks (fallback):</strong> data-testid, data-qa, or data-cy</p><ul><li>Keep them <strong>semantic</strong> and <strong>stable</strong> across redesigns (don’t encode layout or CSS).</li><li>Example: &lt;div data-qa=&quot;invoice-row&quot; data-id=&quot;INV-12345&quot;&gt;…&lt;/div&gt;</li></ul><p><strong>c. Never use (brittle):</strong> CSS classes, text that changes, nth-child, auto-generated IDs.</p><blockquote><em>Tip: Pick </em><strong><em>one</em></strong><em> test attribute prefix across repos (</em><em>data-qa or </em><em>data-testid) and standardize it. This will save a lot of time.</em></blockquote><h3>2) React: Patterns &amp; Examples</h3><h3>Component</h3><pre>// ProductForm.jsx<br>export function ProductForm({ onSubmit }) {<br>  return (<br>    &lt;form aria-label=&quot;Product form&quot; data-qa=&quot;product-form&quot; onSubmit={onSubmit}&gt;<br>      &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>      &lt;input id=&quot;name&quot; name=&quot;name&quot; data-qa=&quot;product-name&quot; /&gt;&lt;label htmlFor=&quot;price&quot;&gt;Price&lt;/label&gt;<br>      &lt;input id=&quot;price&quot; name=&quot;price&quot; inputMode=&quot;numeric&quot; data-qa=&quot;product-price&quot; /&gt;<br>      &lt;button type=&quot;submit&quot; aria-label=&quot;Save product&quot; data-qa=&quot;save-product&quot;&gt;Save&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br></pre><h3>Cypress</h3><pre>// cypress/e2e/product_form.cy.js<br>it(&#39;creates a product&#39;, () =&gt; {<br>  cy.visit(&#39;/products/new&#39;);<br>  cy.findByRole(&#39;form&#39;, { name: /product form/i }).within(() =&gt; {<br>    cy.get(&#39;[data-qa=&quot;product-name&quot;]&#39;).type(&#39;Pen&#39;);<br>    cy.get(&#39;[data-qa=&quot;product-price&quot;]&#39;).type(&#39;25&#39;);<br>    cy.findByRole(&#39;button&#39;, { name: /save product/i }).click();<br>  });<br>  cy.findByRole(&#39;status&#39;, { name: /success/i }).should(&#39;exist&#39;);<br>});</pre><h3>Playwright</h3><pre>// tests/product-form.spec.ts<br>import { test, expect } from &#39;@playwright/test&#39;;<br>test(&#39;creates a product&#39;, async ({ page }) =&gt; {<br>  await page.goto(&#39;/products/new&#39;);<br>  await page.getByRole(&#39;form&#39;, { name: /product form/i }).locator(&#39;[data-qa=&quot;product-name&quot;]&#39;).fill(&#39;Pen&#39;);<br>  await page.locator(&#39;[data-qa=&quot;product-price&quot;]&#39;).fill(&#39;25&#39;);<br>  await page.getByRole(&#39;button&#39;, { name: /save product/i }).click();<br>  await expect(page.getByRole(&#39;status&#39;, { name: /success/i })).toBeVisible();<br>});</pre><p><strong>Notes for React</strong></p><ul><li>Prefer <strong>controlled inputs</strong> for determinism.</li><li>Lift side effects behind <strong>services</strong> you can stub (e.g., api.createProduct).</li><li>Render <strong>status regions</strong> with role=&quot;status&quot; or aria-live=&quot;polite&quot; for reliable assertions.</li></ul><h3>A side note</h3><h3>🧠 What aria-label Does</h3><p>aria-label provides an <strong>accessible name</strong> for screen readers and for test automation tools that support <strong>role-based querying</strong>, such as Playwright or Cypress Testing Library.</p><p>When you write:</p><pre>&lt;form aria-label=&quot;Product form&quot;&gt;</pre><p>you’re telling assistive technologies (and your tests) that:</p><blockquote><em>“This element is a form, and its accessible name is </em>‘Product form’<em>.”</em></blockquote><p>So in your test, you can do:</p><pre>cy.findByRole(&#39;form&#39;, { name: /product form/i })</pre><p>or in Playwright:</p><pre>page.getByRole(&#39;form&#39;, { name: /product form/i })</pre><p>This works because both Cypress Testing Library and Playwright’s getByRole APIs rely on the <strong>accessibility tree</strong> rather than raw CSS selectors.</p><h3>✅ Why It’s Better Than id or class</h3><ul><li>If you later change your form’s layout, color, or CSS class names, the <strong>test won’t break</strong>.</li><li>It matches how real users experience the app — by role and name — not DOM internals.</li><li>You also improve <strong>screen reader compatibility</strong>, which is a bonus for accessibility compliance.</li></ul><h3>🧩 Where to Use It</h3><p>Use aria-label (or aria-labelledby) when:</p><ul><li>An element doesn’t have a visible label (like a search icon button).</li><li>You need a <strong>stable, semantic handle</strong> for both accessibility and testing.</li></ul><p>Example:</p><pre>&lt;button aria-label=&quot;Add product&quot; data-qa=&quot;add-product&quot;&gt;➕&lt;/button&gt;</pre><h3>🔍 In Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*na5F4CV3VjuIq8cefS21lA.png" /></figure><p>So the “name: Product form” you saw in the test is just referencing the value of that aria-label. It’s not a React prop or a variable — it’s the <em>accessible name</em> used by the testing framework.</p><p>The side was just added so that the code makes sense for those who are new to using accessibility attributes.</p><h3>3) Phoenix LiveView: Patterns &amp; Examples</h3><h3>Template (HEEx)</h3><pre># lib/my_app_web/live/invoice_live/index.html.heex<br>&lt;div id=&quot;invoices&quot; data-qa=&quot;invoice-list&quot; phx-update=&quot;stream&quot;&gt;<br>  &lt;%= for invoice &lt;- @streams.invoices do %&gt;<br>    &lt;div id={invoice.dom_id} data-qa=&quot;invoice-row&quot; data-id={invoice.number}&gt;<br>      &lt;span aria-label=&quot;Invoice number&quot;&gt;&lt;%= invoice.number %&gt;&lt;/span&gt;<br>      &lt;button phx-click=&quot;pay&quot; phx-value-id={invoice.id}<br>              data-qa=&quot;pay-invoice&quot; aria-label={&quot;Pay &quot; &lt;&gt; invoice.number}&gt;<br>        Pay<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;<br>&lt;form phx-submit=&quot;create&quot; aria-label=&quot;Invoice form&quot; data-qa=&quot;invoice-form&quot;&gt;<br>  &lt;input name=&quot;customer&quot; data-qa=&quot;customer-input&quot; /&gt;<br>  &lt;button type=&quot;submit&quot; data-qa=&quot;create-invoice&quot; aria-label=&quot;Create invoice&quot;&gt;Create&lt;/button&gt;<br>&lt;/form&gt;<br></pre><p><strong>LiveView tips</strong></p><ul><li><strong>Streams</strong> (phx-update=&quot;stream&quot;) change DOM incrementally; your <strong>data-qa</strong> hooks must live inside the streamed elements for stable targeting.</li><li>Use <strong>predictable </strong><strong>ids</strong> (e.g., dom_id) for rows; add a <strong>domain ID</strong> as data-id for assertions not tied to HTML structure.</li><li>Hooks? Keep them <strong>idempotent</strong> and expose <strong>data-qa</strong> on the root node a hook manipulates.</li></ul><h3>E2E (Cypress/Playwright) against LiveView</h3><ul><li>You can test LiveView apps purely via browser like any SPA; no special client needed.</li><li>Wait for <strong>LiveView settled state</strong> by asserting on <strong>visible</strong> elements or <strong>status roles</strong>, not arbitrary timeouts.</li></ul><h3>4) Cross-Cutting Conventions</h3><ul><li><strong>Name things by intent, not style:</strong> data-qa=&quot;cart-counter&quot; ✅ vs data-qa=&quot;badge-pill&quot; ❌</li><li><strong>Expose domain identifiers:</strong> add data-id, data-slug, or data-key on list rows and actions.</li><li><strong>Accessible by default:</strong> using roles/labels makes both UX and tests better.</li><li><strong>Deterministic async:</strong> show explicit loading states (aria-busy, data-qa=&quot;loading&quot;) so tests can wait on state, not sleeps.</li><li><strong>Feature flags:</strong> gate experimental UI behind flags and <strong>keep test hooks stable</strong> across flag flips.</li><li><strong>Network discipline:</strong></li><li>Local E2E: seed DB to known state; prefer <strong>API fixtures</strong> over random data.</li><li>For UI-only checks, <strong>stub</strong> network (cy.intercept, Playwright route) and assert payloads + UI.</li><li><strong>Time &amp; randomness:</strong> freeze the clock (cy.clock(), Playwright’s useFakeTimers) and inject seeded RNG where needed.</li></ul><h3>5) Table &amp; Dropdowns (common pain point)</h3><ul><li>Give the <strong>table</strong> a role/name: &lt;table role=&quot;table&quot; aria-label=&quot;Users&quot; data-qa=&quot;users-table&quot;&gt;</li><li>For dropdowns/comboboxes:<br>- Use native &lt;select&gt; when possible: it’s inherently accessible/testable.<br>- For custom combos, wire ARIA: role=&quot;combobox&quot;, aria-expanded, aria-controls, options as role=&quot;option&quot;, and attach <strong>data-qa</strong> to trigger and panel.</li></ul><pre>&lt;button role=&quot;combobox&quot; aria-expanded=&quot;false&quot;<br>        aria-controls=&quot;country-list&quot; data-qa=&quot;country-combobox&quot;&gt;Select country&lt;/button&gt;<br>&lt;ul id=&quot;country-list&quot; role=&quot;listbox&quot; data-qa=&quot;country-options&quot;&gt;<br>  &lt;li role=&quot;option&quot; data-qa=&quot;country-option&quot; data-id=&quot;IN&quot;&gt;India&lt;/li&gt;<br>  &lt;li role=&quot;option&quot; data-qa=&quot;country-option&quot; data-id=&quot;US&quot;&gt;United States&lt;/li&gt;<br>&lt;/ul&gt;</pre><ul><li>Test by <strong>role + name</strong> where possible; fall back to data-qa:</li></ul><pre>await page.getByRole(&#39;combobox&#39;, { name: /country/i }).click();<br>await page.locator(&#39;[data-qa=&quot;country-option&quot;][data-id=&quot;IN&quot;]&#39;).click();</pre><h3>6) Minimal Checklist (Expand this as needed)</h3><ul><li>All interactive elements have <strong>role</strong>/<strong>name</strong> or label.</li><li>Every critical widget exposes <strong>`data-qa=”…”``</strong> hooks (stable names).</li><li>Lists/rows include <strong>domain IDs</strong> via data-id (or slug).</li><li>Explicit <strong>loading/empty/error</strong> states with identifiable hooks.</li><li>E2E fixtures seeded; network calls stubbed where UI-only.</li><li>No selectors rely on CSS classes or nth-child.</li><li>LiveView streams: hooks &amp; IDs are stable across re-renders.</li></ul><h3>Final Thought</h3><p>Designing for testability isn’t extra work — it’s <strong>API design for your DOM</strong>.</p><p>Give QA the same stability guarantees you give your public APIs, and Cypress/Playwright will reward you with fast, reliable end-to-end confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9008f3bf4a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/writing-frontend-code-thats-easy-to-test-react-phoenix-liveview-or-htmx-or-anything-else-b9008f3bf4a4">Writing Frontend Code That’s Easy to Test (React + Phoenix LiveView (or HTMX or anything else)</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Tips to Work Effectively with LLMs (Large Language Models)]]></title>
            <link>https://medium.com/unlearninglabs/tips-to-work-effectively-with-llms-large-language-models-cad1354e6782?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/cad1354e6782</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[github-copilot]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 08:32:10 GMT</pubDate>
            <atom:updated>2025-07-22T09:12:25.110Z</atom:updated>
            <content:encoded><![CDATA[<h4>We’re all excited about AI tools like GitHub Copilot, Claude, Gemini, and others. But to get <em>consistent</em>, <em>high-quality</em>, and <em>usable</em> output from them — you need to work <strong>with</strong> the LLM, not just <em>ask it stuff</em>.</h4><p>Here’s a battle-tested guide to getting the most out of your AI coding companion:</p><h3>🔑 1. Context Is King</h3><p>LLMs don’t read your mind — they act on the context you provide. The <em>richer</em> and <em>clearer</em> your instructions, the <em>better</em> the results.</p><h3>📁 2. Use Instruction Files for Each Tool</h3><p>Each LLM benefits from having a custom instruction file:</p><ul><li>🧭 <strong>GitHub Copilot</strong> → <a href="https://copilot-instructions.md/">https://copilot-instructions.md/</a></li><li>🧠 <strong>Claude</strong> → CLAUDE.md</li><li>🤖 <strong>Gemini CLI</strong> → GEMINI.md</li></ul><p>These files tell your AI exactly what it needs to know about your project: naming, stack, conventions, tone, and more. Treat it like onboarding a new team member.</p><h3>🧾 3. Use Small Prompts with Detailed Instructions</h3><p>Instead of asking vague questions, break your prompt down:</p><ul><li>What you’re building</li><li>The stack you’re using</li><li>The tone/format you want in the output</li><li>Patterns or templates to follow</li><li>Any constraints (e.g. “No third-party libs”, “Tailwind only”, etc.)</li></ul><p><strong>Instructions create context.</strong> That’s your leverage.</p><h3>🧩 4. Tell It to Use Your Pattern</h3><p>Want reusable code? Just say:</p><blockquote><em>“Use this exact pattern.”</em></blockquote><p>LLMs excel at cloning structure. Once it learns your boilerplate, it’ll stick to it with near surgical precision.</p><h3>📂 5. Point to File Paths for Better Alignment</h3><p>If you’re migrating or extending code, reference existing files or paths in your prompt or instruction doc.<br> Example:</p><blockquote><em>“Refer to </em><em>/services/utils/helpers.ts for format.”</em></blockquote><p>This grounds the LLM in <em>your</em> world — not a generic one.</p><h3>🔁 6. Repeat and Refine Your Prompting Style</h3><p>Consistency is your best friend. Create a prompting style and refine it over time. Eventually, your instructions become a part of your team’s development culture.</p><h3>🧪 7. Test the Prompt, Not Just the Output</h3><p>Got bad code? Don’t just regenerate.<br> 👉 <em>Debug the prompt.</em><br> Try splitting your instruction. Change the order. Reword ambiguities. You’ll be amazed at what a simple tweak can do.</p><h3>🧱 8. Think Modular — Build Prompt Snippets</h3><p>Maintain a library of reusable prompt components:</p><ul><li>REST API templates</li><li>Unit test generation</li><li>Type conversions</li><li>Error handling format</li><li>Commenting &amp; docstrings</li></ul><p>Copy-paste, customize, repeat. It scales <em>you</em>.</p><h3>🧰 9. Use AI for the Right Things</h3><p>LLMs are great at:</p><ul><li>Boilerplate generation</li><li>Code migrations (e.g., JS ➝ TS)</li><li>Writing docstrings/tests</li><li>Explaining code</li><li>Regex and DSLs<br> But don’t expect it to architect your system. <strong>That’s your superpower.</strong></li></ul><h3>🔒 10. Be Security-Smart</h3><p>Don’t feed private or sensitive code to public LLMs.</p><ul><li>Sanitize instructions</li><li>Know your org’s LLM usage policy</li><li>Avoid sending client data or credentials in context</li></ul><p>AI is helpful, but <strong>you</strong> are still accountable.</p><h3>✨ Bonus</h3><p>You can even train your AI to respond in your brand’s tone or write commit messages in a specific format. Just tell it in the instruction file.</p><p>And remember:</p><blockquote><strong><em>Don’t let AI </em>own<em> your code.</em></strong><em><br> </em>Review every single line before it hits production.</blockquote><p><strong>PS:</strong> This post was styled with LLM and not generated by AI 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad1354e6782" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/tips-to-work-effectively-with-llms-large-language-models-cad1354e6782">🧠 Tips to Work Effectively with LLMs (Large Language Models)</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI For All — Python Session 2— Conditionals and Loops]]></title>
            <link>https://medium.com/unlearninglabs/ai-for-all-python-session-2-conditionals-and-loops-0d7f4bcc9793?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/0d7f4bcc9793</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-scienc]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 07:42:11 GMT</pubDate>
            <atom:updated>2024-12-14T07:53:58.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI For All — Python Session 2— Conditionals and Loops</h3><p>The session two focused on conditionals and loops. A bit of functions may be used but functions, exception handlings etc. will be covered in greater depth in subsequent sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*LUFAGPNDv2yAdIi-DIKe8g.png" /></figure><h3>1. Conditionals in Python</h3><p>Conditionals allow the program to make decisions based on conditions.</p><h3>1.1 Basic if Statement</h3><pre>x = 10<br>if x &gt; 5:<br>    print(&quot;x is greater than 5&quot;)</pre><p><strong>Output</strong></p><pre>x is greater than 5</pre><h3>1.2 if-else Statement</h3><pre>x = 3<br>if x &gt; 5:<br>    print(&quot;x is greater than 5&quot;)<br>else:<br>    print(&quot;x is less than or equal to 5&quot;)</pre><p><strong>Output</strong>:</p><pre>x is less than or equal to 5</pre><h3>1.3 if-elif-else Statement</h3><pre>x = 5<br>if x &gt; 5:<br>    print(&quot;x is greater than 5&quot;)<br>elif x == 5:<br>    print(&quot;x is equal to 5&quot;)<br>else:<br>    print(&quot;x is less than 5&quot;)</pre><p><strong>Output</strong>:</p><pre>x is equal to 5</pre><h3>1.4 Nested Conditionals</h3><pre>x = 10<br>if x &gt; 5:<br>    if x &lt; 15:<br>        print(&quot;x is between 5 and 15&quot;)</pre><p><strong>Output</strong>:</p><pre>x is between 5 and 15</pre><h3>1.5 Logical Operators</h3><h4>Using and Operator</h4><pre>x = 7<br>if x &gt; 5 and x &lt; 10:<br>    print(&quot;x is between 5 and 10&quot;)</pre><p><strong>Output</strong>:</p><pre>x is between 5 and 10</pre><h4>Using or Operator</h4><pre>x = 3<br>if x &gt; 5 or x == 3:<br>    print(&quot;At least one condition is true&quot;)</pre><p><strong>Output</strong>:</p><pre>At least one condition is true</pre><h4>Using not Operator</h4><pre>x = False<br>if not x:<br>    print(&quot;x is False&quot;)</pre><p><strong>Output</strong>:</p><pre>x is False</pre><h3>1.6 Parentheses in Conditionals</h3><pre>x = 10<br>y = 20<br>if (x &gt; 5 and y &lt; 25) or (x == 10):<br>    print(&quot;Condition is True&quot;)</pre><p><strong>Output</strong>:</p><pre>Condition is True</pre><h3>1.7 Ternary Operator</h3><pre>x = 4<br>result = &quot;Even&quot; if x % 2 == 0 else &quot;Odd&quot;<br>print(result)</pre><p><strong>Output</strong>:</p><pre>Even</pre><h3>2. Loops in Python</h3><p>Loops are used to repeat code blocks.</p><h3>2.1 while Loop</h3><pre>n = 5<br>i = 1<br>while i &lt;= 12:<br>    print(f&quot;{n} x {i} = {n * i}&quot;)<br>    i += 1</pre><p><strong>Output</strong>:<br>Times table for 5 up to 12.</p><h3>2.2 for Loop</h3><pre>n = 7<br>for i in range(1, 13):<br>    print(f&quot;{n} x {i} = {n * i}&quot;)</pre><p><strong>Output</strong>:<br>Times table for 7 up to 12.</p><h3>2.3 break Statement</h3><pre>for i in range(1, 10):<br>    if i == 5:<br>        break<br>    print(i)</pre><p><strong>Output</strong>:</p><pre>1  <br>2  <br>3  <br>4</pre><h3>2.4 continue Statement</h3><pre>for i in range(1, 6):<br>    if i == 3:<br>        continue<br>    print(i)</pre><p><strong>Output</strong>:</p><pre>1  <br>2  <br>4  <br>5</pre><h3>3. Functions in Python</h3><p>Functions encapsulate logic for reusability.</p><h3>3.1 Function for Times Table</h3><pre>def print_times_table(n):<br>    for i in range(1, 13):<br>        print(f&quot;{n} x {i} = {n * i}&quot;)</pre><pre>print_times_table(5)</pre><p><strong>Output</strong>:<br>Times table of 5.</p><h3>3.2 Function with Input Validation</h3><pre>def get_number():<br>    while True:<br>        try:<br>            return int(input(&quot;Enter a number (0 to quit): &quot;))<br>        except ValueError:<br>            print(&quot;Invalid input. Try again.&quot;)</pre><pre>number = get_number()<br>print(&quot;You entered:&quot;, number)</pre><h3>4. Iterables and Iterators</h3><h3>4.1 Checking If a Variable is Iterable</h3><pre>from collections.abc import Iterable</pre><pre>x = [1, 2, 3]<br>if isinstance(x, Iterable):<br>    print(&quot;x is iterable&quot;)</pre><p><strong>Output</strong>:</p><pre>x is iterable</pre><h3>4.2 Using iter()</h3><pre>try:<br>    iter(123)<br>except TypeError:<br>    print(&quot;Not iterable&quot;)</pre><p><strong>Output</strong>:</p><pre>Not iterable</pre><h3>5. Swapping Variables</h3><h3>5.1 Swapping Using Temporary Variable</h3><pre>a, b = 5, 10<br>temp = a<br>a = b<br>b = temp<br>print(a, b)</pre><p><strong>Output</strong>:</p><pre>10 5</pre><h3>5.2 Swapping Without Temporary Variable (Pythonic Way)</h3><pre>a, b = 5, 10<br>a, b = b, a<br>print(a, b)</pre><p><strong>Output</strong>:</p><pre>10 5</pre><h3>6. Exception Handling</h3><h3>6.1 Handling Invalid Input</h3><pre>try:<br>    x = int(input(&quot;Enter a number: &quot;))<br>    print(&quot;You entered:&quot;, x)<br>except ValueError:<br>    print(&quot;Invalid input&quot;)</pre><h3>7. Final Program: User Input and Times Table</h3><p>Here’s the final complete program that combines all the concepts:</p><pre>def print_times_table(n):<br>    for i in range(1, 13):<br>        print(f&quot;{n} x {i} = {n * i}&quot;)<br>    while True:<br>        try:<br>            number = int(input(&quot;Enter a number for its times table (0 to quit): &quot;))<br>            if number == 0:<br>                print(&quot;Goodbye!&quot;)<br>                break<br>            print_times_table(number)<br>        except ValueError:<br>            print(&quot;Invalid input. Please enter a valid number.&quot;)</pre><p><strong>Output</strong>:</p><ul><li>If 5 is entered, it prints the times table of 5.</li><li>If 0 is entered, it exits the program.</li></ul><h3>Assignments</h3><h3>Assignment 1: Check Odd or Even</h3><p>Write a program to check whether a number is odd or even.</p><p><strong>Input</strong>:</p><pre>Enter a number: 4</pre><p><strong>Expected Output</strong>:</p><pre>4 is Even</pre><h3>Assignment 2: Largest of Three Numbers</h3><p>Write a program to find the largest of three numbers using conditionals.</p><p><strong>Input</strong>:</p><pre>Enter first number: 10  <br>Enter second number: 25  <br>Enter third number: 15</pre><p><strong>Expected Output</strong>:</p><pre>The largest number is 25</pre><h3>Assignment 3: Times Table Using for Loop</h3><p>Write a program to print the times table of a given number up to 12.</p><p><strong>Input</strong>:</p><pre>Enter a number: 6</pre><p><strong>Expected Output</strong>:</p><pre>6 x 1 = 6  <br>6 x 2 = 12  <br>...  <br>6 x 12 = 72</pre><h3>Assignment 4: Print Numbers in Range</h3><p>Write a program to print all numbers between two given numbers (inclusive) using a for loop.</p><p><strong>Input</strong>:</p><pre>Enter the starting number: 3  <br>Enter the ending number: 7</pre><p><strong>Expected Output</strong>:</p><pre>3  <br>4  <br>5  <br>6  <br>7</pre><h3>Assignment 5: Check Divisibility</h3><p>Write a program to check if a number is divisible by <strong>3 and 5</strong>.</p><p><strong>Input</strong>:</p><pre>Enter a number: 15</pre><p><strong>Expected Output</strong>:</p><pre>15 is divisible by both 3 and 5</pre><h3>Assignment 6: Sum of First N Natural Numbers</h3><p>Write a program to calculate the sum of the first N natural numbers using a while loop.</p><p><strong>Input</strong>:</p><pre>Enter a number: 5</pre><p><strong>Expected Output</strong>:</p><pre>The sum of first 5 natural numbers is 15</pre><h3>Assignment 7: Count Digits in a Number</h3><p>Write a program to count the number of digits in a given number using a while loop.</p><p><strong>Input</strong>:</p><pre>Enter a number: 12345</pre><pre>Number of digits: 5</pre><h3>Assignment 8: FizzBuzz</h3><p>Write a program to print numbers from 1 to n.</p><ul><li>Print <strong>“Fizz”</strong> if the number is divisible by 3.</li><li>Print <strong>“Buzz”</strong> if the number is divisible by 5.</li><li>Print <strong>“FizzBuzz”</strong> if divisible by both.</li></ul><p><strong>Input</strong>:</p><pre>Enter a number: 15</pre><p><strong>Expected Output</strong>:</p><pre>1  <br>2  <br>Fizz  <br>4  <br>Buzz  <br>Fizz  <br>7  <br>8  <br>Fizz  <br>Buzz  <br>11  <br>Fizz  <br>13  <br>14  <br>FizzBuzz</pre><h3>Assignment 9: Reverse a Number</h3><p>Write a program to reverse a given number using a while loop.</p><p><strong>Input</strong>:</p><pre>Enter a number: 1234</pre><p><strong>Expected Output</strong>:</p><pre>Reversed number: 4321</pre><h3>Assignment 10: Print Even Numbers</h3><p>Write a program to print all even numbers between 1 and a given number.</p><p><strong>Input</strong>:</p><pre>Enter a number: 10</pre><p><strong>Expected Output</strong>:</p><pre>2  <br>4  <br>6  <br>8  <br>10</pre><h3>Assignment 11: Factorial of a Number</h3><p>Write a program to calculate the factorial of a given number using a for loop.</p><p><strong>Input</strong>:</p><pre>Enter a number: 5</pre><p><strong>Expected Output</strong>:</p><pre>Factorial of 5 is 120</pre><h3>Assignment 12: Check Palindrome Number</h3><p>Write a program to check if a given number is a palindrome.</p><p><strong>Input</strong>:</p><pre>Enter a number: 121</pre><p><strong>Expected Output</strong>:</p><pre>121 is a palindrome</pre><h3>Assignment 13: Find Prime Numbers</h3><p>Write a program to print all prime numbers between 1 and a given number.</p><p><strong>Input</strong>:</p><pre>Enter a number: 10</pre><p><strong>Expected Output</strong>:</p><pre>2  <br>3  <br>5  <br>7</pre><h3>Assignment 14: Sum of Digits</h3><p>Write a program to calculate the sum of the digits of a given number.</p><p><strong>Input</strong></p><pre>Enter a number: 123</pre><p><strong>Expected Output</strong>:</p><pre>Sum of digits: 6</pre><h3>Assignment 15: Simple Number Guessing Game</h3><p>Write a program to let the user guess a number between 1 and 10. The program should stop if the correct number is guessed.</p><p><strong>Input</strong> (Example Run):</p><pre>Guess the number (1-10): 5  <br>Wrong! Try again.  <br>Guess the number (1-10): 7  <br>Correct! You guessed it.</pre><p><strong>Expected Output</strong>:</p><pre>Correct! You guessed it.</pre><h3>Summary</h3><p>This article covered:</p><ol><li><strong>Conditionals</strong>: if, if-else, if-elif-else, logical operators, and the ternary operator.</li><li><strong>Loops</strong>: while, for, break, and continue.</li><li><strong>Functions</strong>: Creating reusable logic.</li><li><strong>Iterables</strong>: Checking and handling iterable objects.</li><li><strong>Variable Swapping</strong>: Temporary variable vs. tuple unpacking.</li><li><strong>Exception Handling</strong>: Ensuring robust input validation</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7f4bcc9793" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/ai-for-all-python-session-2-conditionals-and-loops-0d7f4bcc9793">AI For All — Python Session 2— Conditionals and Loops</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI For All — Python Session 1 — Introduction]]></title>
            <link>https://medium.com/unlearninglabs/ai-for-all-python-session-1-introduction-0fca3d927d6b?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/0fca3d927d6b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 06:11:22 GMT</pubDate>
            <atom:updated>2024-12-14T07:45:34.644Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI For All — Python Session 1 — Introduction</h3><p>These are notes from my live sessions for Algorisys Employees. Putting here for everyone who might find this useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*DlcCkBG3XReIBoL1gIWCIw.png" /></figure><h3>1. Python Basics</h3><h3>The print() Function</h3><ul><li><strong>Purpose</strong>: Used to display data, strings, or variables on the console.</li><li>It can print multiple arguments separated by a space.</li></ul><p><strong>Examples</strong></p><pre>print(&quot;Hello, World!&quot;)  # Prints a string<br>print(&quot;Python&quot;, 3.9, &quot;is awesome!&quot;)  # Prints multiple values separated by a space</pre><h3>Variables</h3><ul><li>Variables store values and are assigned using the = operator.</li><li>Python is <strong>dynamically typed</strong>, meaning the variable type is inferred at runtime.</li></ul><p><strong>Examples</strong></p><pre>name = &quot;Python&quot;  # String variable<br>age = 30         # Integer<br>salary = 100.5   # Float<br>success = True   # Boolean</pre><h3>2. String Operations</h3><h3>String Concatenation</h3><ul><li>Combine strings using the + operator.</li></ul><pre>name = &quot;Tom&quot;<br>print(&quot;Hello, &quot; + name)  # Outputs: Hello, Tom</pre><h3>String Formatting</h3><ol><li><strong>Using f-strings</strong>:</li></ol><ul><li>The most efficient way to embed variables into strings.</li></ul><pre>name = &quot;Tom&quot;<br>age = 30<br>print(f&quot;{name} is {age} years old&quot;)  # Outputs: Tom is 30 years old</pre><ol><li><strong>Debugging with </strong><strong>name=</strong>:</li></ol><ul><li>Helps print the variable name and its value.</li></ul><pre>print(f&quot;{name=}&quot;)  # Outputs: name=&#39;Tom&#39;</pre><ol><li><strong>Decimal Precision</strong>:</li></ol><ul><li>Control floating-point precision with :.2f.</li></ul><pre>salary = 100.503343<br>print(f&quot;{salary:.2f}&quot;)  # Outputs: 100.50</pre><h3>Alignment in Strings</h3><ul><li>Align strings to the left, right, or center with padding.</li></ul><pre>text = &quot;Hello&quot;<br>print(f&quot;{text:*&gt;10}&quot;)  # Right-aligned with &#39;*&#39; padding<br>print(f&quot;{text:*&lt;10}&quot;)  # Left-aligned with &#39;*&#39; padding</pre><h3>3. Date and Time</h3><h3>Using datetime</h3><ul><li>Import the datetime module to display and format current date and time.</li></ul><pre>from datetime import datetime<br>now = datetime.now()<br>print(f&quot;Current time: {now:%H:%M:%S}&quot;)  # Outputs time in HH:MM:SS format</pre><h3>4. List Operations</h3><h3>List Basics</h3><ul><li>Lists are <strong>mutable</strong> collections that store multiple items.</li></ul><p><strong>Examples</strong>:</p><pre>fruits = [&quot;apple&quot;, &quot;orange&quot;, &quot;grape&quot;]<br>print(fruits[0])  # Access first element<br>print(fruits[-1]) # Access last element</pre><h3>List Slicing</h3><ul><li>Extract sublists using slicing: list[start:end:step].</li></ul><pre>nums = [0, 1, 2, 3, 4, 5, 6]<br>print(nums[2:5])      # Outputs: [2, 3, 4]<br>print(nums[::2])      # Every second element<br>print(nums[::-1])     # Reverse the list</pre><h3>List Methods</h3><h3>1. append()</h3><ul><li>Adds an element to the end of the list.</li></ul><pre>nums = [1, 2, 3]<br>nums.append(4)<br>print(nums)  # Outputs: [1, 2, 3, 4]</pre><h3>2. insert()</h3><ul><li>Inserts an element at a specific index.</li></ul><pre>nums.insert(1, 99)  # Insert 99 at index 1<br>print(nums)  # Outputs: [1, 99, 2, 3, 4]</pre><h3>3. pop()</h3><ul><li>Removes and returns an element by index (default: last).</li></ul><pre>nums.pop()   # Removes last element<br>nums.pop(1)  # Removes element at index 1</pre><h3>4. remove()</h3><ul><li>Removes the first occurrence of a specific value.</li></ul><pre>nums.remove(99)<br>print(nums)  # Removes 99</pre><h3>5. index()</h3><ul><li>Returns the index of the first occurrence of a value.</li></ul><pre>print(nums.index(4))  # Returns index of 4</pre><h3>6. count()</h3><ul><li>Counts occurrences of a value in the list.</li></ul><pre>print(nums.count(2))  # Outputs: 1</pre><h3>7. sort()</h3><ul><li>Sorts the list (ascending by default).</li></ul><pre>nums.sort()  # Ascending order<br>nums.sort(reverse=True)  # Descending order</pre><h3>Nesting Lists</h3><ul><li>Lists can contain other lists, enabling multi-dimensional data storage.</li></ul><p><strong>Examples</strong>:</p><pre>nested_list = [[1, 2], [3, 4], [5, 6]]<br>print(nested_list[0])       # Outputs: [1, 2]<br>print(nested_list[1][1])    # Access element 4</pre><h3>List Comprehension</h3><p>A concise way to create or modify lists using a single line of code. But technically comprehensions are an easy way to create new iterables from other iterables (we will cover this in subsequent sessions).</p><p>It’s like a using a loop, but easier and more concise syntax. It works best for simple cases and might quickly become unreadable.</p><p>Different types of comprehensions</p><ul><li>lists (this session)</li><li>dictionaries</li><li>sets</li><li>generators</li></ul><h3>Basic Syntax</h3><pre>new_list = [expression for item in iterable if condition]</pre><h3>Examples:</h3><ol><li><strong>Generate Numbers</strong>:</li></ol><pre>nums = [x for x in range(5)]  # Outputs: [0, 1, 2, 3, 4]<br><br>NOTE: The [ ] indicates we are creating a list</pre><p><strong>2. Square of Numbers</strong>:</p><pre>nums = [1,2,3,4,5]<br>squared = [x**2 for x in nums]<br>print(squared)  # Outputs: [0, 1, 4, 9, 16, 25]<br><br>&quot;&quot;&quot;<br>Without comprehension the above code will look like<br>squared = []<br>for x in nums:<br>  squared.append(x ** 2)<br>&quot;&quot;&quot;<br></pre><p><strong>3. Flatten a Nested List</strong>:</p><pre>nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]<br>flattened = [item for sublist in nested_list for item in sublist]<br><br>print(flattened)  # Outputs: [1, 2, 3, 4, 5, 6, 7, 8]</pre><h4>How does the above flattening code works?</h4><p>Read from Left to Right:</p><pre>1. for sublist in nested_list:<br>  - The outer loop looks at each smaller list in the nested_list.<br>  - For example, first it looks at [1, 2, 3], then [4, 5, 6], and finally [7, 8, 9].<br>2. for item in sublist:<br>  - The inner loop goes through each number in the smaller list.<br>3. item:<br>  - This is the number that gets added to the new list.</pre><p><strong>4. Conditional Comprehension</strong>:</p><pre>even_numbers = [x for x in range(10) if x % 2 == 0]<br>print(even_numbers)  # Outputs: [0, 2, 4, 6, 8]</pre><h3>Type Checking</h3><p>Use the type() function to check the type of a variable.</p><p><strong>Examples</strong>:</p><pre>print(type(1))         # Outputs: &lt;class &#39;int&#39;&gt;<br>print(type(True))      # Outputs: &lt;class &#39;bool&#39;&gt;<br>print(type([1, 2, 3])) # Outputs: &lt;class &#39;list&#39;&gt;</pre><h3>Additional Concepts</h3><h3>Range Function</h3><ul><li>Generates sequences of numbers.</li></ul><p><strong>Examples</strong>:</p><pre>print(range(5))  # Outputs: range(0, 5)<br><br>nums = [x for x in range(5)]  # List comprehension<br>print(nums)  # Outputs: [0, 1, 2, 3, 4]</pre><h3>Key Notes</h3><ul><li>Lists are <strong>mutable</strong> (changeable), unlike strings which are <strong>immutable</strong>.</li><li>List comprehensions provide a compact alternative to loops for creating lists.</li><li>Use f-strings for clean, efficient string formatting.</li></ul><h3>Python Assignment — Session 1</h3><p><strong>Variable Assignment</strong></p><ul><li>Create variables for your name, age, favorite programming language, and a boolean indicating if you enjoy coding.</li><li>Print all variables in one line.</li></ul><p><strong>String Operations</strong></p><ul><li>Use string concatenation (+) to print:<br>&quot;Hello, my name is [name] and I am [age] years old.&quot;</li><li>Repeat the above task using <strong>f-strings</strong>.</li><li>Format salary = 1234.56789 to <strong>two decimal places</strong>.</li><li>Align the string &quot;Python&quot;:</li><li>Right-align in 15 width with *.</li><li>Left-align in 15 width with -.</li></ul><p><strong>Date and Time</strong></p><ul><li>Display the current date and time as:<br>&quot;Current Date and Time: YYYY-MM-DD HH:MM:SS&quot;</li><li>Extract and print only the hour, minute, and second.</li></ul><p><strong>List Operations</strong></p><ul><li>Create a list of 5 favorite fruits.</li></ul><p>Print:</p><p>— First fruit</p><p>— Last fruit using <strong>negative indexing</strong></p><p>— First 3 fruits using slicing.</p><p>— Create a list with mixed data types and print it.</p><p><strong>List Methods</strong></p><ul><li>Given: nums = [1, 2, 3, 4, 5]:</li><li>Append 6.</li><li>Insert 99 at index 2.</li><li>Remove the last element using pop().</li><li>Remove 3 using remove().</li><li>Replace value at index 1 with &quot;Python&quot;.</li><li>Print the list after each operation.</li></ul><p><strong>Sorting and Searching</strong></p><ul><li>Sort [10, 5, 8, 2, 7, 9]:</li><li>In ascending order.</li><li>In descending order.</li><li>Add &quot;hello&quot; to the list and sort using key=str.</li></ul><p><strong>List Comprehension</strong></p><ul><li>Generate a list of numbers from <strong>0 to 10</strong>.</li><li>Create a list of squares of numbers <strong>0 to 10</strong>.</li><li>Generate a list of <strong>even numbers</strong> between 0 and 20.</li><li>Generate numbers divisible by both 2 and 3 from 1 to 30.</li></ul><p><strong>Nested Lists</strong></p><ul><li>Print each sublist of [[1, 2, 3], [4, 5, 6], [7, 8, 9]].</li><li>Flatten the list using <strong>list comprehension</strong>.</li></ul><p><strong>Logic Building</strong></p><p>Write a program to:</p><p>Largest and smallest</p><ul><li>Take a list of numbers as input.</li><li>Print the sum, largest, and smallest numbers.</li></ul><p>Check if a given string is a <strong>palindrome</strong>.</p><ul><li>Remove duplicates from [1, 2, 2, 3, 4, 4, 5, 6, 6] and print the list with unique elements.</li></ul><h3>Summary</h3><p>This extended explanation covers:</p><ol><li><strong>Basic Syntax</strong>: Printing, variables, strings.</li><li><strong>List Operations</strong>: Accessing, slicing, mutating lists.</li><li><strong>String Formatting</strong>: Concatenation, f-strings, alignment.</li><li><strong>List Comprehensions</strong>: Advanced and efficient ways to work with lists.</li><li><strong>Nested Lists</strong>: Multi-dimensional data handling.</li><li><strong>Type Checking</strong>: Identifying types of variables.</li></ol><p>I am hoping by mastering these topics, you build a strong foundation for Python programming and prepare for more advanced concepts! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fca3d927d6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/ai-for-all-python-session-1-introduction-0fca3d927d6b">AI For All — Python Session 1 — Introduction</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Space Invasion Game in C# with Raylib and Design Patterns on Ubuntu]]></title>
            <link>https://medium.com/unlearninglabs/building-a-simple-space-invasion-game-in-c-with-raylib-and-design-patterns-on-ubuntu-9bdde6f551e6?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/9bdde6f551e6</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[game-programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 15:59:49 GMT</pubDate>
            <atom:updated>2026-06-12T04:47:43.223Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll create a Space Invasion game with C# using Raylib. Along the way, we’ll use several design patterns to make our code more modular and flexible, including <strong>Factory</strong>, <strong>Strategy</strong>, and <strong>Decorator</strong> patterns.</p><p><strong>NOTE</strong>: This is a early draft of the tutorial. So some redundancy you might find in code along with some not so good practice. If you observe kindly comment and share feedback as I will update it in the next revision.</p><p>The game graphics is kept simple as that is not the core of this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7yjNt-ufcWVgtG1CZgJpQ.gif" /></figure><h3>Prerequisites</h3><ul><li>Basic knowledge of C#</li><li>Install .NET SDK</li><li>Install Raylib: Follow instructions at <a href="https://www.raylib.com/">Raylib</a></li></ul><h3>Game Overview</h3><p>In this game, the player controls a spaceship that can move left or right and shoot bullets to destroy incoming enemies. The enemies move in different patterns, and the player can gain a temporary shield to block hits.</p><h3>Step 1: Setting Up the Project</h3><ol><li>Create a new console project in C#:</li></ol><pre>dotnet new console -o SpaceInvasionGame<br>cd SpaceInvasionGame</pre><p>2. Add Raylib as a dependency. You can do this by editing your .csproj file to include:</p><pre>dotnet add package Raylib-cs</pre><p>The .csproj file will be updated as below.</p><p>RayLib C# binding github link <a href="https://github.com/chrisdill/raylib-cs/tree/master">https://github.com/chrisdill/raylib-cs/tree/master</a></p><pre>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Raylib-cs&quot; Version=&quot;6.1.1&quot; /&gt;<br>  &lt;/ItemGroup&gt;</pre><p>3. Restore Dependencies</p><pre>dotnet restore</pre><h3>Step 2: Basic Game Window Setup</h3><ol><li><strong>Create </strong><strong>Program.cs</strong>. This file will set up the main game window and manage game updates.</li></ol><pre>using System;<br>using Raylib_cs;<br><br>namespace SpaceInvasionGame<br>{<br>    public class Program<br>    {<br>        private const int WindowWidth = 800;<br>        private const int WindowHeight = 600;<br><br>        public static void Main()<br>        {<br>            Raylib.InitWindow(WindowWidth, WindowHeight, &quot;Space Invasion&quot;);<br>            Raylib.SetTargetFPS(60);<br><br>            while (!Raylib.WindowShouldClose())<br>            {<br>                Raylib.BeginDrawing();<br>                Raylib.ClearBackground(Color.BLACK);<br>                Raylib.DrawText(&quot;Space Invasion Game&quot;, 10, 10, 20, Color.WHITE);<br>                Raylib.EndDrawing();<br>            }<br><br>            Raylib.CloseWindow();<br>        }<br>    }<br>}</pre><p>2. <strong>Run the game</strong>: Use dotnet run to test that the window opens.</p><h3>Step 3: Creating the Game Entities</h3><p>We’ll start by setting up basic game elements: Player, Enemy, and Bullet. All of these will inherit from a common GameEntity class.</p><h3>3.1 Setting Up the GameEntity Base Class</h3><p>To avoid duplicating code, we’ll define a base class, GameEntity, which holds properties and methods common to all entities, like position (X, Y) and drawing the texture.</p><h4>GameEntity.cs</h4><p>Create a folder called Entity to organize the files. Then, add GameEntity.cs:</p><pre>namespace SpaceInvasionGame.Entity<br>{<br>    using Raylib_cs;<br><br>    public abstract class GameEntity<br>    {<br>        public int X { get; set; }<br>        public int Y { get; set; }<br>        public Texture2D Texture { get; protected set; }<br><br>        public GameEntity(int x, int y, Texture2D texture)<br>        {<br>            X = x;<br>            Y = y;<br>            Texture = texture;<br>        }<br><br>        // Abstract method for moving, to be implemented by derived classes<br>        public abstract void Move();<br><br>        // Draws the entity on the screen<br>        public virtual void Draw()<br>        {<br>            Raylib.DrawTexture(Texture, X, Y, Color.White);<br>        }<br>    }<br>}</pre><h3>3.2 Creating the Player Interface</h3><p>Since the player has unique actions, such as shooting bullets, let’s define an IPlayer interface. This allows us to modify the player’s behavior using the <strong>Decorator Pattern</strong> (such as adding a shield) without changing the core Player class.</p><h4>IPlayer.cs</h4><p>Create IPlayer.cs in the Entity folder:</p><pre>using Raylib_cs;<br>using System.Collections.Generic;<br><br>namespace SpaceInvasionGame.Entity<br>{<br>    public interface IPlayer<br>    {<br>        int X { get; }<br>        int Y { get; }<br>        void Move();<br>        void Draw();<br>        void Shoot(List&lt;Bullet&gt; bullets, Texture2D bulletTexture);<br>    }<br>}</pre><h3>3.3 Implementing the Player Class</h3><p>Now we’ll create the Player class that implements IPlayer and inherits basic properties and methods from GameEntity. The Player class will manage movement and shooting.</p><h4>Player.cs</h4><p>Create Player.cs in the Entity folder:</p><pre>using Raylib_cs;<br>using System.Collections.Generic;<br><br>namespace SpaceInvasionGame.Entity<br>{<br>    public class Player : IPlayer<br>    {<br>        public int X { get; private set; }<br>        public int Y { get; private set; }<br>        private int speed;<br>        private Texture2D texture;<br><br>        public Player(int x, int y, int speed, Texture2D texture)<br>        {<br>            X = x;<br>            Y = y;<br>            this.speed = speed;<br>            this.texture = texture;<br>        }<br><br>        public void Move()<br>        {<br>            if (Raylib.IsKeyDown(KeyboardKey.Left)) X -= speed;<br>            if (Raylib.IsKeyDown(KeyboardKey.Right)) X += speed;<br><br>            if (X &lt; 0) X = 0;<br>            if (X &gt; 736) X = 736;<br>        }<br><br>        public void Draw()<br>        {<br>            Raylib.DrawTexture(texture, X, Y, Color.White);<br>        }<br><br>        public void Shoot(List&lt;Bullet&gt; bullets, Texture2D bulletTexture)<br>        {<br>            bullets.Add(new Bullet(X + 28, Y, bulletTexture));<br>        }<br>    }<br>}</pre><h3>Explanation:</h3><ul><li><strong>Move Method</strong>: Handles left and right movement within screen boundaries.</li><li><strong>Shoot Method</strong>: Adds a bullet to a list when fired, allowing the game to track and render bullets.</li></ul><h3>3.4 Creating the Bullet Class</h3><p>Bullets move upwards and disappear when they go off-screen.</p><h4>Bullet.cs</h4><p>Create Bullet.cs in the Entity folder:</p><pre>namespace SpaceInvasionGame.Entity<br>{<br>    using Raylib_cs;<br><br>    public class Bullet<br>    {<br>        public int X { get; private set; }<br>        public int Y { get; private set; }<br>        private int speedY = 6;<br>        public Texture2D Texture { get; private set; }<br><br>        public Bullet(int x, int y, Texture2D texture)<br>        {<br>            X = x;<br>            Y = y;<br>            Texture = texture;<br>        }<br><br>        public void Move()<br>        {<br>            Y -= speedY;<br>        }<br><br>        public void Draw()<br>        {<br>            Raylib.DrawTexture(Texture, X, Y, Color.White);<br>        }<br>    }<br>}</pre><blockquote>NOTE: Can Bullet be derived from GameEntity?</blockquote><h3>Explanation:</h3><ul><li><strong>Move Method</strong>: Moves bullets upwards.</li><li><strong>Draw Method</strong>: Renders the bullet on the screen.</li></ul><h4><strong>3.5 The `Enemy` Class</strong></h4><p>The `Enemy` is the third entity. It <strong>**inherits from `GameEntity`**</strong> and delegates its movement to a pluggable strategy object (defined in Step 5). It also handles collision detection against bullets.</p><p>Create `Entity/Enemy.cs`:</p><pre>namespace SpaceInvasionGame.Entity<br>{<br>  using Raylib_cs;<br>  public class Enemy : GameEntity<br>  {<br>    public int SpeedX { get; set; }<br>    public int SpeedY { get; set; }<br>    public bool MovingRight { get; set; } = true;<br>    private IMovementStrategy movementStrategy;<br><br>    public Enemy(int x, int y, int speedX, int speedY, Texture2D texture, IMovementStrategy strategy)<br>    : base(x, y, texture)<br>    {<br>      SpeedX = speedX;<br>      SpeedY = speedY;<br>      movementStrategy = strategy;<br>    }<br><br>    public override void Move()<br>    {<br>      movementStrategy.Move(this);<br>    }<br><br>    // Collision detection between this enemy and a bullet<br>    public bool Intersects(Bullet bullet)<br>    {<br>      Rectangle enemyRect = new Rectangle(X, Y, Texture.Width, Texture.Height);<br>      Rectangle bulletRect = new Rectangle(bullet.X, bullet.Y, bullet.Texture.Width, bullet.Texture.Height);<br>      return Raylib.CheckCollisionRecs(enemyRect, bulletRect);<br>    }<br>  }<br>}</pre><p><strong>Explanation</strong></p><p><strong>Constructor: </strong>passes `x`, `y`, and `texture` up to the `GameEntity` base, and stores its speeds plus a movement strategy. `MovingRight` tracks the current horizontal direction.</p><p><strong>Move: </strong>instead of containing movement logic itself, the enemy hands `this` to its `IMovementStrategy`. Swapping the strategy changes how the enemy behaves, that’s the Strategy Pattern in action (Step 5).</p><p><strong>Intersects: </strong>builds a rectangle for the enemy and for the bullet and uses Raylib’s `CheckCollisionRecs` for axis-aligned bounding-box collision detection.</p><h3>Step 4: Using the Factory Pattern for Enemy Creation</h3><p>The <strong>Factory Pattern</strong> allows us to create objects without specifying exact details. Here, EnemyFactory will simplify enemy creation and allow easy adjustments for different types of enemies.</p><ol><li><strong>Create </strong><strong>IEntityFactory.cs</strong>:</li></ol><pre>namespace SpaceInvasionGame.Entity<br>{<br>    public interface IEntityFactory<br>    {<br>        GameEntity Create();<br>    }<br>}</pre><p><strong>2. Create </strong><strong>EnemyFactory.cs</strong>:</p><pre>namespace SpaceInvasionGame.Entity<br>{<br>    using Raylib_cs;<br>    using System;<br><br>    public class EnemyFactory : IEntityFactory<br>    {<br>        private Texture2D enemyTexture;<br>        private Random random;<br><br>        public EnemyFactory(Texture2D texture, Random random)<br>        {<br>            enemyTexture = texture;<br>            this.random = random;<br>        }<br><br>        public GameEntity Create()<br>        {<br>            return new Enemy(random.Next(0, 736), random.Next(50, 150), 2, 40, enemyTexture, new ZigZagMovement());<br>        }<br>    }<br>}</pre><h3>Explanation:</h3><ul><li><strong>EnemyFactory</strong>: Uses random values to spawn enemies at different positions.</li></ul><h3>Step 5: Adding Movement Patterns (Strategy Pattern)</h3><p>The <strong>Strategy Pattern</strong> allows different movement behaviors for enemies, making it easy to add new patterns without modifying the enemy class directly.</p><ol><li><strong>Create </strong><strong>IMovementStrategy.cs</strong>:</li></ol><pre>namespace SpaceInvasionGame.Entity<br>{<br>    public interface IMovementStrategy<br>    {<br>        void Move(Enemy enemy);<br>    }<br>}</pre><p><strong>2. Create </strong><strong>ZigZagMovement.cs</strong>:</p><pre>namespace SpaceInvasionGame.Entity<br>{<br>    public class ZigZagMovement : IMovementStrategy<br>    {<br>        public void Move(Enemy enemy)<br>        {<br>            enemy.X += enemy.MovingRight ? enemy.SpeedX : -enemy.SpeedX;<br>            if (enemy.X &lt;= 0 || enemy.X &gt;= 736)<br>            {<br>                enemy.MovingRight = !enemy.MovingRight;<br>                enemy.Y += enemy.SpeedY;<br>            }<br>        }<br>    }<br>}</pre><h3>Explanation:</h3><ul><li><strong>ZigZagMovement</strong>: Changes direction when reaching screen edges, creating a zigzag effect.</li></ul><h3>Step 6: Adding a Shield (Decorator Pattern)</h3><p>The <strong>Decorator Pattern</strong> lets us dynamically add functionality. We’ll use it to add a temporary shield to the player.</p><h4>ShieldDecorator.cs</h4><p>Create ShieldDecorator.cs in the Entity folder:</p><pre>using Raylib_cs;<br>using System;<br>using System.Collections.Generic;<br><br>namespace SpaceInvasionGame.Entity<br>{<br>    public class ShieldDecorator : IPlayer<br>    {<br>        private IPlayer player;<br>        private Texture2D shieldTexture;<br>        private bool shieldActive;<br>        private float shieldDuration;<br>        private DateTime shieldActivatedTime;<br><br>        public int X =&gt; player.X;<br>        public int Y =&gt; player.Y;<br><br>        public ShieldDecorator(IPlayer player, Texture2D shieldTexture, float duration = 5.0f)<br>        {<br>            this.player = player;<br>            this.shieldTexture = shieldTexture;<br>            this.shieldDuration = duration;<br>            shieldActive = false;<br>        }<br><br>        public void ActivateShield()<br>        {<br>            shieldActive = true;<br>            shieldActivatedTime = DateTime.Now;<br>        }<br><br>        private void CheckShieldStatus()<br>        {<br>            if (shieldActive &amp;&amp; (DateTime.Now - shieldActivatedTime).TotalSeconds &gt;= shieldDuration)<br>            {<br>                shieldActive = false;<br>            }<br>        }<br><br>        public void Move() =&gt; player.Move();<br><br>        public void Draw()<br>        {<br>            player.Draw();<br>            CheckShieldStatus();<br><br>            if (shieldActive)<br>            {<br>                Raylib.DrawTexture(shieldTexture, X - 10, Y - 10, Color.White);<br>            }<br>        }<br><br>        public void Shoot(List&lt;Bullet&gt; bullets, Texture2D bulletTexture)<br>        {<br>            player.Shoot(bullets, bulletTexture);<br>        }<br>    }<br>}</pre><h3>Explanation:</h3><ul><li><strong>ActivateShield Method</strong>: Activates a shield around the player for a limited time.</li><li><strong>CheckShieldStatus</strong>: Automatically deactivates the shield after a set duration.</li></ul><h3>Final Step: Integrating Everything in Program.cs</h3><p>Now that we have all the components, let’s integrate them in Program.cs to create the main game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v88wmmnTiM_Fot6du9y1gA.png" /></figure><h4>Program.cs</h4><pre>using System;<br>using System.Collections.Generic;<br>using Raylib_cs;<br>using SpaceInvasionGame.Entity;<br><br>namespace SpaceInvasionGame {<br>    public class SpaceInvasionGame<br>    {<br>        private const int WindowWidth = 800;<br>        private const int WindowHeight = 600;<br>        private IPlayer player;<br>        private List&lt;Enemy&gt; enemies;<br>        private List&lt;Bullet&gt; bullets;<br>        private Random random;<br>        private int score;<br>        private bool gameOver;<br><br>        // Load textures<br>        private Texture2D background;<br>        private Texture2D enemyTexture;<br>        private Texture2D bulletTexture;<br>        private Texture2D shieldTexture;<br><br>        public SpaceInvasionGame()<br>        {<br>            Raylib.InitWindow(WindowWidth, WindowHeight, &quot;Space Invasion&quot;);<br>            Raylib.SetTargetFPS(60);<br><br>            // Load assets<br>            background = Raylib.LoadTexture(&quot;images/background.jpg&quot;);<br>            Texture2D playerTexture = Raylib.LoadTexture(&quot;images/player.png&quot;);<br>            enemyTexture = Raylib.LoadTexture(&quot;images/enemy.png&quot;);<br>            bulletTexture = Raylib.LoadTexture(&quot;images/bullet.png&quot;);<br>            shieldTexture = Raylib.LoadTexture(&quot;images/shield.png&quot;);<br><br>            player = new Player(370, 480, 3, playerTexture);<br>            // Add shield to player with Decorator pattern<br>            player = new ShieldDecorator(player, shieldTexture);<br><br>            enemies = new List&lt;Enemy&gt;();<br>            bullets = new List&lt;Bullet&gt;();<br>            random = new Random();<br>            score = 0;<br>            gameOver = false;<br><br>            IEntityFactory enemyFactory = new EnemyFactory(enemyTexture, random);<br>            for (int i = 0; i &lt; 6; i++)<br>            {<br>                enemies.Add((Enemy)enemyFactory.Create());<br>            }<br>        }<br><br>        public void Run()<br>        {<br>            while (!Raylib.WindowShouldClose())<br>            {<br>                HandleEvents();<br>                UpdateGame();<br>                Render();<br>            }<br><br>            Raylib.UnloadTexture(background);<br>            Raylib.UnloadTexture(enemyTexture);<br>            Raylib.UnloadTexture(bulletTexture);<br>            Raylib.UnloadTexture(shieldTexture);<br>            Raylib.CloseWindow();<br>        }<br><br>        private void HandleEvents()<br>        {<br>            player.Move();<br><br>            if (Raylib.IsKeyPressed(KeyboardKey.Space) &amp;&amp; !gameOver)<br>            {<br>                bullets.Add(new Bullet(player.X + 28, player.Y, bulletTexture));<br>            }<br>        }<br><br>        private void UpdateGame()<br>        {<br>            if (gameOver) return;<br><br>            foreach (Bullet bullet in bullets)<br>            {<br>                bullet.Move();<br>            }<br>            bullets.RemoveAll(b =&gt; b.Y &lt; 0);<br><br>            foreach (Enemy enemy in enemies)<br>            {<br>                enemy.Move();<br>                if (enemy.Y &gt; 440)<br>                {<br>                    gameOver = true;<br>                }<br>            }<br><br>            for (int i = enemies.Count - 1; i &gt;= 0; i--)<br>            {<br>                for (int j = bullets.Count - 1; j &gt;= 0; j--)<br>                {<br>                    if (enemies[i].Intersects(bullets[j]))<br>                    {<br>                        enemies.RemoveAt(i);<br>                        bullets.RemoveAt(j);<br>                        score++;<br>                        enemies.Add(new Enemy(random.Next(0, 736), random.Next(50, 150), 2, 40, enemyTexture, new ZigZagMovement()));<br><br>                        break;<br>                    }<br>                }<br>            }<br>        }<br><br>        private void Render()<br>        {<br>            Raylib.BeginDrawing();<br>            Raylib.ClearBackground(Color.Black);<br><br>            Raylib.DrawTexture(background, 0, 0, Color.White);<br>            player.Draw();<br><br>            foreach (Enemy enemy in enemies)<br>            {<br>                enemy.Draw();<br>            }<br><br>            foreach (Bullet bullet in bullets)<br>            {<br>                bullet.Draw();<br>            }<br><br>            Raylib.DrawText($&quot;Score: {score}&quot;, 10, 10, 20, Color.White);<br><br>            if (gameOver)<br>            {<br>                Raylib.DrawText(&quot;GAME OVER&quot;, 250, 250, 32, Color.White);<br>            }<br><br>            Raylib.EndDrawing();<br>        }<br><br>        public static void Main()<br>        {<br>            var game = new SpaceInvasionGame();<br>            game.Run();<br>        }<br>    }<br>}</pre><h4><strong>Suggested next steps / exercises</strong></h4><p>1. Make `Player` and `Bullet` derive from `GameEntity` to remove duplicated `X`/`Y`/texture code.</p><p>2. Wire a key to `ShieldDecorator.ActivateShield()` and make the shield actually absorb a hit.</p><p>3. Add a second `IMovementStrategy` (e.g. straight dive or sine wave) and have the factory pick one at random.</p><p>4. Spawn replacement enemies through `EnemyFactory.Create()` instead of `new Enemy(…)`.</p><p>This concludes the tutorial and it provides you with a fully functioning simple version of Space Invasion game in C#. By using design patterns, we make the code more flexible, organized, and easier to extend with new features like different enemy types, movement patterns, and player abilities.</p><p>The experimental code is at <a href="https://github.com/rajeshpillai/csharp-raylib-spaceinvasion/tree/feat-design-patterns-1">https://github.com/rajeshpillai/csharp-raylib-spaceinvasion/tree/feat-design-patterns-1</a></p><p>The updated code with more features is in feat-enhancements branch</p><p><a href="https://github.com/rajeshpillai/csharp-raylib-spaceinvasion/tree/feat-enhancements">https://github.com/rajeshpillai/csharp-raylib-spaceinvasion/tree/feat-enhancements</a></p><blockquote>NOTE: There are some code fixes that can be done. I have intentionally kept it for the first version to see the raw format of code. This will be refactored. Readers are encouraged to identify bad patterns and recommend changes as well as that will help others create an active learning habit.</blockquote><h4>History</h4><ul><li>12-June-2026 -&gt; Add link to feat-enhancements branch</li><li>5-Nov-2024 -&gt; First Draft</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bdde6f551e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unlearninglabs/building-a-simple-space-invasion-game-in-c-with-raylib-and-design-patterns-on-ubuntu-9bdde6f551e6">Building a Simple Space Invasion Game in C# with Raylib and Design Patterns on Ubuntu</a> was originally published in <a href="https://medium.com/unlearninglabs">Unlearning Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns and Applications in JavaScript/TypeScript]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">This story serves as a friendly index of all the design pattern related articles published by me.</p><p class="medium-feed-link"><a href="https://medium.com/unlearninglabs/design-patterns-and-applications-in-javascript-typescript-ad52bb5d17db?source=rss----3459ef45b2a0---4">Continue reading on Unlearning Labs »</a></p></div>]]></description>
            <link>https://medium.com/unlearninglabs/design-patterns-and-applications-in-javascript-typescript-ad52bb5d17db?source=rss----3459ef45b2a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad52bb5d17db</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rajesh Pillai]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 15:23:27 GMT</pubDate>
            <atom:updated>2024-10-31T14:53:37.332Z</atom:updated>
        </item>
    </channel>
</rss>