<?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 Nagasai on Medium]]></title>
        <description><![CDATA[Stories by Nagasai on Medium]]></description>
        <link>https://medium.com/@nagasai317?source=rss-ed735a6a5dfb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8wF8ba8jyc17l6BA</url>
            <title>Stories by Nagasai on Medium</title>
            <link>https://medium.com/@nagasai317?source=rss-ed735a6a5dfb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:37:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nagasai317/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[Understanding --max-old-space-size in Node.js: A Deep Dive into Memory Management]]></title>
            <link>https://medium.com/@nagasai317/understanding-max-old-space-size-in-node-js-a-deep-dive-into-memory-management-7955e9d79ad0?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7955e9d79ad0</guid>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 07:43:39 GMT</pubDate>
            <atom:updated>2025-02-24T11:45:53.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rFyX7OWU_9ZTLARG" /></figure><h3>Introduction</h3><p>In Node.js, memory management is <strong>handled by the V8 engine</strong>, which is responsible for allocating and reclaiming memory efficiently. However, when applications process <strong>large datasets, perform intensive computations, or handle numerous concurrent requests</strong>, they may exceed <strong>the default heap memory limit</strong>, leading to an <strong>“Out of Memory”</strong> error.</p><p>To address this, Node.js provides the --max-old-space-size flag, allowing developers to <strong>manually increase the heap memory limit</strong>. But what exactly does this mean, and why is it needed?</p><p>This article will break down:</p><ul><li><strong>What </strong><strong>--max-old-space-size does</strong></li><li><strong>How V8 manages memory (Heap vs Stack)</strong></li><li><strong>How the Garbage Collector reclaims memory</strong></li></ul><h4>1. What is --max-old-space-size in Node.js?</h4><p>--max-old-space-size is a <strong>command-line flag</strong> that sets the maximum heap memory available to <strong>V8&#39;s garbage collector</strong>.</p><pre>node --max-old-space-size=4096 app.js</pre><p>Here, 4096 represents the heap size in <strong>megabytes (MB)</strong>, allocating <strong>4GB of memory</strong> for the application.</p><p>Default Heap Size in Node.js</p><ul><li><strong>64-bit systems</strong> → <strong>~2GB</strong></li><li><strong>32-bit systems</strong> → <strong>~700MB</strong></li></ul><p>If your application <strong>requires more memory</strong>, increasing this value prevents <strong>crashes</strong> due to insufficient heap space.</p><h4>2. Why Does This Flag Exist?</h4><p>Node.js is built on <strong>Google’s V8 JavaScript Engine</strong>, which allocates memory in two main areas:</p><ol><li><strong>Stack Memory</strong> (For Primitives &amp; Function Execution)</li><li><strong>Heap Memory</strong> (For Objects &amp; Dynamic Data)</li></ol><p>Each of these plays a role in how <strong>Node.js stores and processes data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*9pjKTnPFVxRP2zggxW3TrQ.png" /></figure><pre>function example() {<br>  let x = 10;  // Stored in Stack<br>  let obj = { name: &quot;Alice&quot; };  // Stored in Heap, reference in Stack<br>}</pre><p>📌 Stack memory is automatically cleared when example() completes<br>📌 Heap memory remains allocated until garbage collection removes obj</p><h4>3. Garbage Collection: How V8 Manages Memory</h4><p>Unlike <strong>C++ or Rust</strong>, where developers manually allocate and free memory, JavaScript relies on <strong>automatic garbage collection</strong> to remove <strong>unreachable objects</strong>.</p><h4>How the Garbage Collector (GC) Works</h4><p>V8’s GC <strong>scans memory</strong>, marks <strong>unreachable objects</strong>, and <strong>frees space</strong> to prevent memory leaks. It uses <strong>Generational Garbage Collection</strong>, dividing memory into:</p><ul><li><strong>Young Generation (Short-lived objects)</strong> → Fast cleanup using <strong>Scavenge Algorithm</strong>.</li><li><strong>Old Generation (Long-lived objects)</strong> → Stores persistent data using <strong>Mark-and-Sweep Algorithm</strong>.</li></ul><p>If <strong>heap memory gets too full</strong>, GC pauses execution, causing performance issues.</p><p><strong>What Happens If Heap is Too Small?</strong></p><p>If V8 <strong>exceeds its heap limit</strong>, Node.js <strong>crashes</strong> with following error</p><pre>FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory</pre><h4>What is a Memory Leak in Node.js?</h4><p>A <strong>memory leak</strong> occurs when an application <strong>keeps using more and more memory</strong> without releasing it, eventually leading to <strong>high RAM usage</strong> and <strong>performance degradation</strong>.</p><p>📌 <strong>In Node.js, memory leaks happen when objects are no longer needed but are still being referenced in the heap, preventing garbage collection from reclaiming the space.</strong></p><h4>What Causes Memory Leaks?</h4><p><strong>🚨 1. Global Variables Holding References</strong></p><ul><li>Objects stored in a global variable <strong>never get garbage collected</strong>.</li></ul><p>❌ <strong>Bad Code (Memory Leak)</strong></p><pre>let users = [];<br><br>function addUser(name) {<br>  users.push({ name });<br>}<br><br>setInterval(() =&gt; addUser(&quot;John&quot;), 1000); // Keeps adding users indefinitely!</pre><p><strong>Problem:</strong> users <strong>grows continuously</strong>, consuming more <strong>RAM</strong>.</p><p>✅ <strong>Fix:</strong> Remove unnecessary references.</p><pre>setInterval(() =&gt; {<br>  if (users.length &gt; 100) users = users.slice(-50); // Keep only last 50 users<br>}, 5000);</pre><h4>🚨 2. Unclosed Event Listeners</h4><p>Event listeners keep objects <strong>in memory</strong>, even if they’re no longer needed.</p><ul><li><strong>Events</strong>: Signals that something has happened (e.g., a user logged in, a file was read).</li><li><strong>Event Listeners</strong>: Functions that execute when an event occurs.</li></ul><p>❌ <strong>Bad Code (Memory Leak)</strong></p><pre>const express = require(&quot;express&quot;);<br>const EventEmitter = require(&quot;events&quot;);<br><br>const app = express();<br>const emitter = new EventEmitter();<br><br>app.get(&quot;/login&quot;, (req, res) =&gt; {<br>  const username = req.query.username || &quot;Guest&quot;;<br><br>  emitter.on(&quot;user_logged_in&quot;, () =&gt; {<br>    console.log(`${username} logged in`); // listeners<br>  });<br><br>  emitter.emit(&quot;user_logged_in&quot;); // Trigger event immediately<br><br>  res.send(`${username} login event registered.`);<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><p>🚨 Why Is this a Memory Leak?</p><ul><li>Every time /login is accessed, <strong>a new </strong><strong>on(&quot;user_logged_in&quot;) listener is added</strong>.</li><li><strong>Event listeners keep increasing indefinitely</strong> (even after the response is sent).</li><li>After <strong>thousands of requests</strong>, <strong>RAM usage spikes</strong>, potentially <strong>crashing the server</strong>.</li></ul><h4>✅ Solution: Use .once() or Remove Old Listeners</h4><pre>// Fix 1: Use .once() to Auto-Clear Listeners<br>app.get(&quot;/login&quot;, (req, res) =&gt; {<br>  const username = req.query.username || &quot;Guest&quot;;<br><br>  emitter.once(&quot;user_logged_in&quot;, () =&gt; {<br>    console.log(`${username} logged in`);<br>  });<br><br>  emitter.emit(&quot;user_logged_in&quot;);<br><br>  res.send(`${username} login event registered.`);<br>});<br>// Now, only one listener is active at a time. Once executed, it&#39;s removed.<br><br>// ✔️ Fix 2: Remove Old Listeners Manually<br>app.get(&quot;/login&quot;, (req, res) =&gt; {<br>  const username = req.query.username || &quot;Guest&quot;;<br><br>  const loginHandler = () =&gt; {<br>    console.log(`${username} logged in`);<br>  };<br><br>  emitter.on(&quot;user_logged_in&quot;, loginHandler);<br><br>  emitter.emit(&quot;user_logged_in&quot;);<br><br>  emitter.removeListener(&quot;user_logged_in&quot;, loginHandler); // Remove listener after execution<br><br>  res.send(`${username} login event handled.`);<br>});<br>// This prevents listeners from accumulating over time.</pre><h4><strong>🚨 </strong>3.WebSocket Memory Leak</h4><p>famous library we use is socket.io. When a client connects to a <strong>Socket.IO server</strong>, an event listener is added for that connection.<br>If we do <strong>not remove old listeners</strong> when the client disconnects, <strong>unused event listeners accumulate</strong>, causing a <strong>memory leak</strong>.</p><h4>❌ Bad Code (Memory Leak in socket.io)</h4><pre>const express = require(&quot;express&quot;);<br>const http = require(&quot;http&quot;);<br>const { Server } = require(&quot;socket.io&quot;);<br><br>const app = express();<br>const server = http.createServer(app);<br>const io = new Server(server);<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  console.log(&quot;Client connected:&quot;, socket.id);<br><br>  // 🚨 Every client reconnect adds a new listener (potential memory leak)<br>  socket.on(&quot;message&quot;, (data) =&gt; {<br>    console.log(&quot;Received:&quot;, data);<br>  });<br><br>  // No cleanup on disconnect<br>});<br><br>server.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><p><strong>📌 What’s Wrong Here?</strong></p><ol><li>Each new connection adds a message event listener.</li><li>If a client disconnects and reconnects, the old listener remains.</li><li>Over time, event listeners keep stacking up.</li><li>Memory usage increases indefinitely, leading to performance issues.</li></ol><h4>✅ Solution: Remove Listeners on Disconnect</h4><pre>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  console.log(&quot;Client connected:&quot;, socket.id);<br><br>  // Define the listener separately so it can be removed later<br>  const messageHandler = (data) =&gt; {<br>    console.log(`Client ${socket.id} says:`, data);<br>  };<br><br>  // Register the event listener<br>  socket.on(&quot;message&quot;, messageHandler);<br><br>  // ✅ Cleanup event listeners on disconnect<br>  socket.on(&quot;disconnect&quot;, () =&gt; {<br>    console.log(`Client disconnected: ${socket.id}`);<br>    socket.removeListener(&quot;message&quot;, messageHandler); // Remove listener<br>  });<br>});<br><br>// or if single connection of client creats multiple listners<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  console.log(&quot;Client connected:&quot;, socket.id);<br><br>  socket.on(&quot;message&quot;, (data) =&gt; {<br>    console.log(`Received message from ${socket.id}:`, data);<br>  });<br><br>  socket.on(&quot;typing&quot;, () =&gt; {<br>    console.log(`User ${socket.id} is typing...`);<br>  });<br><br>  // ✅ Remove all event listeners when a client disconnects<br>  socket.on(&quot;disconnect&quot;, () =&gt; {<br>    console.log(`Client ${socket.id} disconnected`);<br>    socket.removeAllListeners(); // Removes all listeners for this socket<br>  });<br>});</pre><p><strong>📌 Why This Fix Works?</strong></p><ol><li>Each client has a single message listener.</li><li>When the client disconnects, we remove the listener with socket.removeListener().</li><li>No unnecessary memory usage after a client disconnects.</li></ol><h4>🚨4. Creating Intervals Without Clearing Them</h4><p>❌ BAD</p><pre>function startLeakyTimer() {<br>  setInterval(() =&gt; {<br>    let hugeArray = new Array(1e6).fill(&quot;*&quot;); // Large object allocated<br>    console.log(&quot;Interval running...&quot;);<br>  }, 1000);<br>}<br><br>startLeakyTimer();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7955e9d79ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js | Revison]]></title>
            <link>https://medium.com/@nagasai317/node-js-revison-834d43c57194?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/834d43c57194</guid>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 17:42:31 GMT</pubDate>
            <atom:updated>2025-02-24T11:47:51.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ES27pKYZOx7FE1C6" /></figure><p>Node.js is an <strong><em>open-source</em></strong>, <strong><em>cross-platform</em></strong> JavaScript <strong><em>runtime environment</em></strong> that executes JavaScript code outside of a web browser.</p><p>Node.js is built on Google Chrome’s V8 engine and provides everything you need to run JavaScript outside the browser.</p><p>Node.js is single threaded and handles asynchronous requests. it has good support and its has many packages ( npm ) which improves code reusability over writing code for required feature from scratch</p><p>In Node.js, the underlying APIs are implemented in C++, and threading is abstracted from developers. If you’ve worked with threads before, you know how challenging it can be to manage issues like deadlocks and race conditions. By handling these complexities internally, Node.js simplifies concurrency management, making development more efficient and error-free.</p><p>Event loop solves the problem of multi-threading.</p><h4>What is I/O in Node.js?</h4><ul><li><strong>I/O (Input/Output) refers to operations that interact with the system’s disk or network.</strong></li><li>Node.js handles I/O operations <strong>asynchronously</strong> using <strong>libuv</strong>, a C++ library that provides an <strong>event-driven, non-blocking I/O model</strong>.</li><li>Common I/O operations in Node.js:</li><li><strong>Reading/writing files (</strong><strong>fs.readFile, </strong><strong>fs.writeFile)</strong></li><li><strong>Making HTTP requests (</strong><strong>http.request, </strong><strong>fetch)</strong></li><li><strong>Database queries (</strong><strong>mysql.query, </strong><strong>mongodb.find)</strong></li></ul><h4>What is blocking ?</h4><p>A <strong>blocking operation</strong> in Node.js means that <strong>JavaScript execution must wait</strong> until a <strong>non-JavaScript operation (I/O)</strong> completes.</p><h4>How Does Blocking Work?</h4><ul><li>The <strong>event loop stops</strong> and waits for the operation to finish.</li><li><strong>No other JavaScript code can execute</strong> during this time.</li><li>This can cause <strong>performance issues</strong>, especially if multiple users are waiting for requests.</li></ul><p><strong>Blocking code</strong></p><pre>const fs = require(&quot;fs&quot;);<br><br>console.log(&quot;Start&quot;);<br><br>// Blocking (Synchronous) file read<br>const data = fs.readFileSync(&quot;file.txt&quot;, &quot;utf8&quot;); // Execution stops here<br>console.log(data);<br><br>console.log(&quot;End&quot;);</pre><pre>Start<br>(File is read completely)<br>(File content is printed)<br>End<br><br>// While fs.readFileSync() is running, nothing else can execute.</pre><h4>What is Non-Blocking?</h4><p>A <strong>non-blocking operation</strong> allows JavaScript to <strong>continue executing</strong> while waiting for an I/O operation to complete.</p><h4>How Does Non-Blocking Work?</h4><ul><li><strong>The event loop keeps running.</strong></li><li><strong>I/O tasks are offloaded to libuv’s worker pool (if needed).</strong></li><li><strong>When the task completes, the event loop executes the callback.</strong></li></ul><pre>const fs = require(&quot;fs&quot;);<br><br>console.log(&quot;Start&quot;);<br><br>// Non-blocking (Asynchronous) file read<br>fs.readFile(&quot;file.txt&quot;, &quot;utf8&quot;, (err, data) =&gt; {<br>  console.log(data);<br>});<br><br>console.log(&quot;End&quot;);</pre><pre>Start<br>End<br>(File is read asynchronously)<br>(File content is printed)<br><br>// Benefit: JavaScript does not wait for fs.readFile(), allowing &quot;End&quot; to print before the file is read.</pre><h4>4. CPU-Intensive Tasks vs I/O Blocking</h4><p>The term <strong>blocking</strong> is typically used for <strong>I/O operations that stop JavaScript execution</strong>.</p><p>However, CPU-intensive tasks (e.g., complex calculations, loops) can also block performance but are not considered “blocking” in the Node.js I/O sense.</p><pre>console.log(&quot;Start&quot;);<br><br>for (let i = 0; i &lt; 1e9; i++) {} // Heavy CPU computation<br><br>console.log(&quot;End&quot;);<br><br>// This blocks JavaScript execution without any I/O.<br><br>// What Happens?<br>// &quot;Start&quot; is printed.<br>// The for-loop runs synchronously in the main thread (event loop).<br>// No other JavaScript code can execute until the loop finishes.<br>// &quot;End&quot; is printed after the entire loop completes.</pre><h3>How the Event Loop Works:</h3><p>Instead of executing tasks sequentially (like in synchronous programming), Node.js uses the event loop to manage asynchronous tasks efficiently. It ensures that blocking operations like file I/O, network requests, and timers do not stop the execution of other tasks.</p><p>The event loop executes <strong>six distinct phases</strong> in a <strong>strict sequential order</strong>, and each phase has a <strong>specific role</strong> in managing callbacks.</p><h4>🔁 Order of Execution in the Event Loop</h4><p>1️⃣ <strong>Timers Phase</strong><br>2️⃣ <strong>Pending I/O Callbacks Phase</strong><br>3️⃣ <strong>Idle, Prepare Phase (Internal Use Only)</strong><br>4️⃣ <strong>Poll Phase (One of the most important phases)</strong><br>5️⃣ <strong>Check Phase (Executes </strong><strong>setImmediate() callbacks)</strong><br>6️⃣ <strong>Close Callbacks Phase (Handles cleanup tasks)</strong><br><strong>🔄 Repeats continuously while there are pending operations.</strong></p><p>Each phase has a FIFO queue of callbacks to execute. While each phase is special in its own way, generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase’s queue until the queue has been exhausted or the maximum number of callbacks has executed. When the queue has been exhausted or the callback limit is reached, the event loop will move to the next phase, and so on.</p><h3>Key Phases of the Event Loop:</h3><h4>1️⃣ Timers Phase ⏳</h4><ul><li>Executes callbacks scheduled by setTimeout() and setInterval().</li><li>If there are <strong>expired timers</strong>, their respective callbacks are pushed to the <strong>callback queue</strong> and executed.</li><li>Timers do <strong>not</strong> guarantee precise execution timing due to the event loop’s queueing nature.</li></ul><pre>setTimeout(() =&gt; console.log(&quot;Timer Executed&quot;), 1000);<br>console.log(&quot;Hello, World!&quot;);</pre><p>setTimeout(fn, 1000) guarantees <strong>a minimum delay of 1000ms</strong>, but it might take longer.<br>✅ If the event loop is <strong>blocked</strong>, the timer callback will have to <strong>wait</strong>.<br>✅ <strong>Microtasks (Promises) always execute before timers</strong>.</p><pre>setTimeout(() =&gt; console.log(&quot;Timer Executed&quot;), 1000);<br><br>const start = Date.now();<br>while (Date.now() - start &lt; 2000) {} // Blocking the event loop for 2 seconds<br><br>console.log(&quot;Done&quot;);</pre><p>if synchronous code blocks event loops for 2s , timer callback will be executed after 2s only not 1s ( means that atleast one second ). but after 2s this timer will be considered as expired timer and put back in queue and will be executed again once event loops enters timers phase</p><h4>⏳ 2️⃣ Pending I/O Callbacks Phase</h4><ul><li>Executes <strong>I/O callbacks</strong> that were <strong>deferred in the previous loop cycle</strong>.</li><li>Handles <strong>system-level I/O operations</strong> like:</li><li>— Reading files (fs.readFile) ,Handling network requests, Performing database queries</li></ul><pre>const fs = require(&quot;fs&quot;);<br>fs.readFile(&quot;file.txt&quot;, () =&gt; console.log(&quot;File Read Completed&quot;));<br>console.log(&quot;Reading File...&quot;);</pre><pre>Reading File...<br>File Read Completed</pre><p>Key Point: Does not handle timers or setImmediate() callbacks.</p><h4>⚙️ 3️⃣ Idle, Prepare Phase (Internal Use Only)</h4><ul><li>This phase is used <strong>internally by Node.js</strong> for:</li><li>Optimizations, Internal scheduling</li><li><strong>No user-defined JavaScript code runs here.</strong></li></ul><p><strong>🔹 Key Point:</strong> You <strong>cannot hook into this phase</strong>.</p><h4>📥 4️⃣ Poll Phase (Most Critical)</h4><ul><li>Retrieves <strong>new I/O events</strong> and executes their callbacks.</li><li>If <strong>no timers are waiting</strong>, this phase <strong>pauses and waits</strong> for I/O events.</li><li>The <strong>longest phase</strong> in the event loop.</li></ul><pre>const fs = require(&quot;fs&quot;);<br><br>fs.readFile(&quot;data.txt&quot;, () =&gt; {<br>  console.log(&quot;File Read&quot;);<br>});<br><br>setImmediate(() =&gt; console.log(&quot;setImmediate Executed&quot;));<br><br>console.log(&quot;Executing Poll Phase...&quot;);</pre><pre>Executing Poll Phase...<br>File Read<br>setImmediate Executed</pre><h4>⏭️ 5️⃣ Check Phase (Executes setImmediate() Callbacks)</h4><ul><li>Executes <strong>callbacks scheduled via </strong><strong>setImmediate()</strong>.</li><li>setImmediate() runs <strong>right after the poll phase</strong>.</li><li><strong>Ensures code execution happens without waiting for the next event loop cycle.</strong></li></ul><pre>setTimeout(() =&gt; console.log(&quot;setTimeout&quot;), 0);<br>setImmediate(() =&gt; console.log(&quot;setImmediate&quot;));<br><br>console.log(&quot;Event Loop Running...&quot;);</pre><pre>Event Loop Running...<br>setImmediate<br>setTimeout</pre><p>If inside an I/O operation, setImmediate() runs before setTimeout(fn, 0)</p><h4>🛑 6️⃣ Close Callbacks Phase</h4><ul><li>Handles <strong>cleanup tasks</strong>, such as:</li><li>Closing database connections, Destroying sockets, Releasing resources</li><li>Executes <strong>callbacks registered via </strong><strong>.on(&quot;close&quot;)</strong>.</li></ul><pre>const net = require(&quot;net&quot;);<br>const server = net.createServer();<br><br>server.on(&quot;close&quot;, () =&gt; console.log(&quot;Server Closed&quot;));<br>server.close();</pre><pre>Server Closed</pre><p><strong>🔹 </strong>Key Point: Runs before the process exits to ensure clean termination.</p><h4>🚀 Special Case: Microtasks (process.nextTick() &amp; Promises)</h4><ul><li>Microtasks run between each phase of the event loop!</li><li>Higher priority than timers, I/O callbacks, and setImmediate()</li></ul><pre>setTimeout(() =&gt; console.log(&quot;setTimeout&quot;), 0);<br>setImmediate(() =&gt; console.log(&quot;setImmediate&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;Promise&quot;));<br>process.nextTick(() =&gt; console.log(&quot;nextTick&quot;));</pre><pre>nextTick<br>Promise<br>setTimeout<br>setImmediate</pre><p><strong>process.nextTick() executes first</strong></p><ul><li><strong>nextTick callbacks run immediately after the current operation</strong>, before any async operations (including Promises).</li><li>It has the <strong>highest priority</strong> in the event loop.</li></ul><p>2️⃣ <strong>Promise.then() executes next</strong></p><ul><li><strong>Microtasks queue</strong> (which includes Promise.then()) runs <strong>after nextTick</strong>, but before timers and I/O phases.</li></ul><p>3️⃣ <strong>setTimeout() executes before </strong><strong>setImmediate() — </strong>not always</p><ul><li>Both <strong>setTimeout and setImmediate run in different phases</strong> of the event loop.</li><li><strong>setTimeout() is placed in the Timers Phase</strong> of the next event loop cycle.</li><li><strong>setImmediate() is placed in the Check Phase</strong> (which runs <strong>after the poll phase</strong>).</li></ul><p><strong>⚠️ The critical point:</strong></p><ul><li>setTimeout(() =&gt; ..., 0) means the <strong>callback is scheduled for the next event loop iteration&#39;s Timers Phase</strong>.</li><li><strong>If there are no I/O operations, </strong><strong>setTimeout runs before </strong><strong>setImmediate</strong>.</li></ul><p>4️⃣ <strong>setImmediate() executes last</strong></p><ul><li><strong>Runs in the Check Phase, which comes after the Poll Phase</strong>.</li><li>This means it will <strong>always run after </strong><strong>setTimeout()</strong>, unless inside an I/O callback.</li></ul><p>As per node.js docs — if we run the following script which is not within an I/O cycle (i.e. the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process:</p><pre>// timeout_vs_immediate.jssetTimeout(() =&gt; {  console.log(&#39;timeout&#39;);}, 0);setImmediate(() =&gt; {  console.log(&#39;immediate&#39;);});// timeout_vs_immediate.js<br>setTimeout(() =&gt; {<br>  console.log(&#39;timeout&#39;);<br>}, 0);<br>setImmediate(() =&gt; {<br>  console.log(&#39;immediate&#39;);<br>});</pre><h4>🚨 When Can setImmediate() Run Before setTimeout()?</h4><pre>// If inside an I/O operation, setImmediate() can execute before setTimeout().<br>const fs = require(&quot;fs&quot;);<br><br>fs.readFile(__filename, () =&gt; {<br>  setTimeout(() =&gt; console.log(&quot;setTimeout&quot;), 0);<br>  setImmediate(() =&gt; console.log(&quot;setImmediate&quot;));<br>});</pre><pre>setImmediate<br>setTimeout</pre><ul><li>The setImmediate callback is placed <strong>immediately after the I/O operation finishes</strong>.</li><li>setTimeout() has to wait for the <strong>next Timers Phase</strong>, which runs <strong>after the Poll Phase</strong> (where I/O callbacks execute)</li></ul><pre>const fs = require(&quot;fs&quot;);<br><br>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;setTimeout 1&quot;);<br>}, 0);<br><br>setImmediate(() =&gt; {<br>  console.log(&quot;setImmediate 1&quot;);<br>});<br><br>fs.readFile(__filename, () =&gt; {<br>  console.log(&quot;I/O Callback&quot;);<br><br>  setTimeout(() =&gt; console.log(&quot;setTimeout 2&quot;), 0);<br>  setImmediate(() =&gt; console.log(&quot;setImmediate 2&quot;));<br><br>  process.nextTick(() =&gt; console.log(&quot;nextTick inside I/O&quot;));<br>  Promise.resolve().then(() =&gt; console.log(&quot;Promise inside I/O&quot;));<br>});<br><br>process.nextTick(() =&gt; console.log(&quot;nextTick 1&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;Promise 1&quot;));<br><br>console.log(&quot;End&quot;);</pre><pre>Start<br>End<br>nextTick 1<br>Promise 1<br>setTimeout 1<br>setImmediate 1<br>I/O Callback<br>nextTick inside I/O<br>Promise inside I/O<br>setImmediate 2<br>setTimeout 2</pre><h4>How Node.js Handles I/O Operations?</h4><p>Node.js does <strong>not block</strong> while performing I/O tasks. Instead:</p><ol><li><strong>For Disk I/O</strong> (File operations like fs.readFile()):</li></ol><ul><li>Node.js <strong>offloads</strong> the task to the <strong>Worker Pool</strong> (since reading files requires accessing the disk).</li><li>Once the operation completes, the result is sent back to the <strong>Event Loop</strong>.</li></ul><p><strong>2. For Network I/O</strong> (HTTP requests, DB queries):</p><ul><li>Node.js <strong>offloads</strong> the request to the <strong>OS Kernel’s networking stack</strong>, which handles it asynchronously.</li><li>No Worker Pool is involved.</li><li>Once the network response arrives, Node.js picks it up in the <strong>Event Loop (Poll Phase)</strong>.</li></ul><p>3. <strong>Other I/O ex : </strong>dns.lookup(), crypto operations<strong>Worker Pool (libuv) or OS</strong></p><h4>How Node.js is Single threaded framework when it has pool of worker threads which performs I/O / CPU intensive operations parallely ?</h4><p>📌 Node.js is single-threaded because all JavaScript runs on the Event Loop on single main thread .<br>📌 Node.js is not limited to one thread — it uses multiple threads for background tasks (via Worker Pool implemented by libuv a c/c++ library) .</p><p>📌 default worker pool threads count : 4 but can be increased( configurable )</p><p><strong><em>more about how node.js manages memory : </em></strong><a href="https://medium.com/@nagasai317/understanding-max-old-space-size-in-node-js-a-deep-dive-into-memory-management-7955e9d79ad0">https://medium.com/@nagasai317/understanding-max-old-space-size-in-node-js-a-deep-dive-into-memory-management-7955e9d79ad0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=834d43c57194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next Generation Java-script ES6 — Part — 1]]></title>
            <link>https://medium.com/@nagasai317/next-generation-java-script-es6-part-1-76d4a856d4e3?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d4a856d4e3</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 14:48:57 GMT</pubDate>
            <atom:updated>2022-01-03T15:06:08.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Next Generation Java-script ES6 — Part — 1</h3><p>Java-script is evolving quickly. React uses next generation java-script features. Using next-gen java-script allows us to write clean and robust react applications</p><blockquote>If you are looking to learn react , it is quite essential to have proper knowledge about next-gen java-script</blockquote><h3><strong>a. var vs let vs const</strong></h3><p>Before ES6 , there was only var keyword with which we can able to declare variables in java-script</p><p><strong>variables </strong>which are declared <strong>var </strong>keyword can be updated and re-declared</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3RMYuggF8lnt0oqFr63vqQ.png" /></figure><p>variable which is created using var keyword declared outside the function is global scoped , var variables which are declared inside the function is function scoped</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMoA3hE4bVrjxAHHBWAjCA.png" /></figure><p><strong>Hoisting of var :</strong></p><p>Hoisting is a java-script feature which variables and functions are moved to top of their scope and initialized with value of undefined</p><h3>What is the problem associated with var keyword ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W4S8bUiwvlmbnJunw0qmA.png" /></figure><p>if you want to update alertMsg intentionally, then it wont be an issue . what if you don’t want to update ? then , its an issue .</p><p>lets say , alertMsg variable is already created using var keyword and has assigned an empty string to it . but , you unknowingly redeclared this variable with new string , then it would overrides the old one ( empty string ).</p><h3><strong>Let</strong></h3><p>variables which are declared using let keyword <strong>can be updated</strong> but <strong>cant be re-declared</strong> within same scope</p><p>let is now-a-days most preferable way of declaring dynamic variables.</p><p><strong>let is block-scoped</strong> . A block is chunk of code wrapped in curly brackets {}.</p><p>so, a variable declared inside a block is only accessible inside that block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7G6gpd7NBTPZjDQ4u_05pQ.png" /></figure><p><strong>Hoisting of let:</strong></p><p>Like var , let variables are also hoisted to top of scope. unlike var variables which are hoisted and initialized with value of undefined ,let variables are not initialized</p><p><strong>Const</strong></p><p>variables which are declared using const keyword cant be re-declared and updated.</p><p><strong>const is block scoped</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IobR_1LtulyT1vTPXi3rZg.png" /></figure><p><strong>Hoisting of const:</strong></p><p>Like var , const variables are also hoisted to top of scope. unlike var variables which are hoisted and initialized with value of undefined ,const variables are not initialized</p><p>&lt;script src=”<a href="https://gist.github.com/NagaSai6/bb744b92456c80506f98396e7b0141bb.js">https://gist.github.com/NagaSai6/bb744b92456c80506f98396e7b0141bb.js</a>&quot;&gt;&lt;/script&gt;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d4a856d4e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading objects to AWS S3 using pre-signed URLs]]></title>
            <link>https://medium.com/@nagasai317/uploading-objects-to-aws-s3-using-pre-signed-urls-888897ef3b76?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/888897ef3b76</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ajax]]></category>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 10:02:02 GMT</pubDate>
            <atom:updated>2021-11-10T10:02:02.220Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier, If we want to upload files in a web application, first we had to upload it to the server later server will again upload it to external storage like AWS S3. This Design increases the load on your server so, the server will not be able to respond to simultaneous web requests.</p><p>This article demonstrates how to create a Node.js application that uploads files directly to S3 instead of via a web application, utilising S3’s Cross-Origin Resource Sharing (CORS) support. The <a href="http://expressjs.com/">Express</a> web framework is used to facilitate request-handling, but the procedure should be almost identical in any Node.js application</p><p>If You are using Heroku for hosting your back-end, you cant change the file structure once it is deployed that is we cant upload files to a server hosted on Heroku. Here we have no other way to handle file uploads</p><h4>Uploading to <a href="https://aws.amazon.com/s3/">AWS S3</a></h4><p>we use client-side and server js to sign the URL ( which are valid for some time ).through that signed Url’s, we have to upload files (objects ) from client-side that is browser.</p><p>S3 is comprised of a set of buckets, each with a globally unique name, in which individual files (known as objects) and directories, can be stored.</p><p>For uploading files to S3, you will need an Access Key ID and a Secret Access Key, which act as a username and password. The access key account will need to have sufficient access privileges to the target bucket in order for the upload to be successful.</p><h4><strong>Security Credentials</strong></h4><p>Your S3 credentials can be found on the <a href="https://console.aws.amazon.com/iam/home?#security_credential">Security Credentials</a> section of the <a href="https://aws.amazon.com/">AWS “My Account/Console” menu</a></p><p>When you click on Access Keys, it will show you the option to create a new access key . click that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0TRlyfZB-zuK7qCR072Jw.png" /></figure><p>Download key File and store it securely. this file consists of two values</p><p>AWSAccessKeyId=xxxxxxxxxxxxxxxxx</p><p>AWSSecretKey=xxxxxxxxxxxxxxxxxx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*zhwkAE0wgMH68Kp9.jpg" /></figure><p>In general, the method described in this article follows these simple steps:</p><ul><li>A file is selected for upload by the user in their web browser</li><li>The user’s browser makes a request to your web application on Heroku, which produces a temporary signature with which to sign the upload request</li><li>The temporary signed request is returned to the browser in JSON format</li></ul><blockquote>The browser then uploads the file directly to Amazon S3 using the signed request supplied by your Node.js application</blockquote><h4><strong>AWS S3 Setup</strong></h4><ol><li>Create S3 Bucket on AWS, check <a href="https://docs.aws.amazon.com/quickstarts/latest/s3backup/step-1-create-bucket.html">here</a></li><li>You will now need to edit some of the permissions properties of the target S3 bucket so that the final request has sufficient privileges to write to the bucket. In a web browser, sign in to the AWS console and select the S3 section. Select the appropriate bucket and click the <strong>Permissions</strong> tab. A few options are now provided on this page (including Block public access, Access Control List, Bucket Policy, and CORS configuration).</li><li>Firstly, ensure that “Block all public access” is turned off and in particular turn off “Block public access to buckets and objects granted through new access control lists” and “Block public access to buckets and objects granted through any access control lists” for the purposes of this project. Setting up the bucket in this way allows us to read its contents without signed URLs, but this may not be suitable for services running in production.</li><li>Next, you will need to configure the bucket’s CORS (Cross-Origin Resource Sharing) settings, which will allow your application to access content in the S3 bucket. Each rule should specify a set of domains from which access to the bucket is granted and also the methods and headers permitted from those domains.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vNvVfzzzycBKBs0B.png" /><figcaption>source : <a href="https://devcenter3.assets.heroku.com/article-images/1606246183-Screenshot-2020-11-24-at-19.21.01.png">link</a></figcaption></figure><p>This tells S3 to allow any domain access to the bucket and that requests can contain any headers, which is generally fine for testing. When deploying, you should change the ‘AllowedOrigin’ to only accept requests from your domain.</p><h4>Steps</h4><h4>Index.html</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTewEATuiTefwY-h8T6_3A.png" /><figcaption>Client-side</figcaption></figure><h4>Index.js</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uo03yNyNsWODy_XR3sQ3Hw.png" /><figcaption>step 1 — Client-side</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iM68hKquDdW-2OGAjja2jA.png" /><figcaption>step 2 — Client-side</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8A3d_-QoMZZPQzpG3OeMw.png" /><figcaption>step 3 — server-side</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnJ-Xr6ukMZhj2D_RdTbwQ.png" /><figcaption>step 4 — server-side</figcaption></figure><p>here content-length-range restricts the file size to be uploaded to the s3 bucket by users, I set 15360000 bytes equivalent to nearly 15 MB, min 1 Byte and I’m also restricting file type, only pdf files can be uploaded to s3, Expires parameter maximum time limit, Which I have given 200 seconds, after 200 seconds, signed URL that is created is invalid</p><p>learn more about ACL <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvYuWYUL97fL7mimteLihw.png" /><figcaption>step 5 — client-side</figcaption></figure><p>Here we have used the POST but not the PUT method.</p><p>In the case of <strong>PUT URLs</strong>, you have no control over the size of the uploaded file. Refer to this for more <a href="https://advancedweb.hu/differences-between-put-and-post-s3-signed-urls/">info</a></p><p>If You see a success alert, check the s3 bucket, u can find the uploaded file there</p><p>Application:</p><p>let&#39;s say, There is a form with 5 text inputs and 1 file input. Here when submitting the form, we can get a signed URL from the server, through which our file will be uploaded and the corresponding URL is assigned another input ( which is not visible to user’s). After successful upload, we can submit the form with no file but file URL which will be saved in the database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888897ef3b76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is KNN Algorithm?]]></title>
            <link>https://medium.com/@nagasai317/what-is-knn-algorithm-d44754ca84a8?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d44754ca84a8</guid>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 17:56:38 GMT</pubDate>
            <atom:updated>2021-11-08T18:15:40.356Z</atom:updated>
            <content:encoded><![CDATA[<p>K-Nearest Neighbors is a very simple and intuitive supervised machine learning algorithm. It is also called Non-Parametric and Lazing learning algorithm</p><p>In the <strong>Parametric model</strong>, You know which model you are using to fit the given data, ex: Linear regression,i.e y = m x + c, here the data, which you feed to linear regression algorithm, it will try to figure out the best possible straight line to fit the data. In order to use linear regression, we take some mathematical assumptions But in real life, datasets may not satisfy mathematical assumptions</p><p>In the <strong>Non-Parametric Model, </strong>there are no underlying mathematical assumptions. Data set figures out how the model should be .Y=f(x)+c where f(x) can be linear, quadratic or anything. data is what determines how f(x) should be. f(x) can be considered as an infinite-parameter model, which is parametric.</p><p>That means A non Parametric model can have 10 or 20 or 50 or any number of parameters. but No of the parameters is not known exactly that is why it is called non-parametric. Non-Parametric does not mean it does not have parameters, it means that we don’t know how many parameters are involved in model generation.</p><p><strong>Lazy Learning Algorithm: </strong>It means no data points are required to train the model. all the data points used at the time of prediction, make training faster and testing costlier</p><h3><strong>How KNN Algorithm Works?</strong></h3><p>let&#39;s assume there are two classes namely class A and class B, we need to classify new points between these classes. let&#39;s say k = 3, which means we are looking for 3 nearest neighbors for the given new point. after we found 3 neighbours , we will go for the majority, out of 3 neighbors if 2 neighbors belong to class A, then our new point will get the label of class A and vice-versa</p><p>In order to find nearest neighbors we calculate the distance between the points using distance measures such as <strong>Euclidean distance, Manhattan distance</strong></p><h3>K in KNN algorithm</h3><p>K in KNN is the number of nearest neighbors, which is the core deciding factor in classification. when K = 1, the algorithm is called the nearest neighbor algorithm. K is a hyperparameter that we need to choose at the time of model prediction</p><p>There is no standard value for K that gives better prediction results for all kinds of datasets because each dataset is different and have different requirements</p><p>In the case of a small number of neighbours, the noise will have a higher influence on the result, and a large number of neighbors make it computationally expensive. Research has also shown that a small number of neighbors are the most flexible fit which will have low bias but the high variance and a large number of neighbors will have a smoother decision boundary which means lower variance but higher bias.</p><p>It is generally followed that we will use an odd K value if we have an even number of classes to classify</p><h3>Curse of Dimensionality ( from datacamp )</h3><p>KNN performs better with a lower number of features than a large number of features. You can say that when the number of features increases then it requires more data. An increase in dimension also leads to the problem of overfitting. To avoid overfitting, the needed data will need to grow exponentially as you increase the number of dimensions. This problem of higher dimension is known as the Curse of Dimensionality</p><p>To deal with the problem of the curse of dimensionality, you need to perform principal component analysis before applying any machine learning algorithm, or you can also use the feature selection approach. Research has shown that in large dimensions Euclidean distance is not useful anymore. Therefore, you can prefer other measures such as cosine similarity, which get decidedly less affected by the high dimension</p><p>Refer to the following link to implement KNN using the scikit-learn package <a href="https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn">link</a></p><h3>Advantages</h3><ol><li>The algorithm is simple and easy to implement.</li><li>There’s no need to build a model, tune several parameters, or make additional assumptions.</li><li>The algorithm is versatile. It can be used for classification, regression, and search (as we will see in the next section).</li></ol><h3>KNN in practice</h3><p>KNN’s main disadvantage of becoming significantly slower as the volume of data increases makes it an impractical choice in environments where predictions need to be made rapidly. Moreover, there are faster algorithms that can produce more accurate classification and regression results.</p><p>However, provided you have sufficient computing resources to speedily handle the data you are using to make predictions, KNN can still be useful in solving problems that have solutions that depend on identifying similar objects. An example of this is using the KNN algorithm in recommender systems, an application of KNN-search.</p><h3>Distance measures</h3><p><strong>1. Euclidean distance</strong></p><p><strong>2. Manhattan distance</strong></p><p><strong>3. Minkowski distance</strong></p><p><strong>4. Hamming distance</strong></p><p>Euclidean Distance :</p><p>it is generally used to find the distance between two real-valued vectors. Euclidean distance is used when we have to calculate the distance of real values like integer, float, etc… One issue with this distance measurement technique is that we have to normalize or standard the data into a balance scale otherwise the outcome will not preferable.</p><p>Let’s take an example of a 2-Dimensional vector and take a geometrical intuition of distance measures on 2-Dim data for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*85anPCJvvu4I-zCA.png" /><figcaption>source : <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Euclidean_distance_2d.svg/300px-Euclidean_distance_2d.svg.png">link</a></figcaption></figure><p>Suppose we take D-dimensional vector it means <strong>X1</strong> belongs to<strong> Rd </strong>(<strong>X1∈Rd</strong>) and also <strong>X2</strong> belongs to <strong>Rd</strong> (<strong>X2∈Rd</strong>) so the distance between X1 and X2 is written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*ZQ6lsL2oHmbg58vG.png" /><figcaption>source : <a href="https://editor.analyticsvidhya.com/uploads/838013st.png">link</a></figcaption></figure><blockquote><strong><em>Note: Euclidean distance between two vectors or points is the L2 norm of two vectors</em></strong></blockquote><h3>Manhatten Distance</h3><p>This is the simplest way or technique to calculate the distance between two points, often called Taxicab distance or City Block distance, you can easily relate this with your daily life, If you start from somewhere and reached some destination so the Manhatten distance says that the distance between your starting point and the destination point. More mathematical we can say that It calculates the <strong>absolute value</strong> between two points. We calculate the distance exactly as the original path is we didn’t take any diagonal or shortest path.</p><p>Let’s take the geometric intuition for better understanding;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*-xCE-tgaOYk3dsvY.png" /></figure><p>you can see in the image that the points <strong>X1 </strong>and <strong>X2</strong> are 2-Dim vectors and having the coordinates same as before we discussed for euclidean distance, but here we can’t calculate the distance as we calculate earlier apart from this we take the absolute value of the path from X1 to X2. In the image see that we take the path that actually covers from one point to another.</p><p><strong>Manhatten Distance = sum for i to N sum || X1i — X2i ||</strong></p><p>In mathematically we can write as :</p><blockquote><strong><em>Note: Manhatten distance between two vectors or points is the L1 norm of two vector</em></strong></blockquote><p>distance = d + d = 2d</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d44754ca84a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up PySpark on AWS EC2]]></title>
            <link>https://medium.com/@nagasai317/setting-up-pyspark-on-aws-ec2-29da649caf01?source=rss-ed735a6a5dfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/29da649caf01</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Nagasai]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 06:21:41 GMT</pubDate>
            <atom:updated>2021-08-19T06:21:41.182Z</atom:updated>
            <content:encoded><![CDATA[<p>Create an EC2 Instance ( ubuntu ) and connect the instance to local terminal in your computer</p><p>Steps to follow after connecting remote instance to your terminal</p><p>## <strong>Download Anaconda on Ubuntu Virtual Machine</strong></p><p><strong>cmd 1</strong> : wget http://repo.continuum.io/archive/Anaconda3–2020.11-linux-x86_64.sh</p><p>2020.11 is the latest version at the time of writing</p><p>## <strong>Install Anaconda</strong></p><p><strong>cmd2 : </strong>install Anaconda3–2020.11-linux-x86_64.sh</p><p>## <strong>Check which python you are using</strong></p><p><strong>cmd3 : </strong>which python</p><p>if this cmd3 is not returning anything ,do this</p><p><strong>cmd4 : </strong>source .bashrc</p><p>after cmd4 , execute cmd3 again it should return something like this</p><p><strong>/home/ubuntu/anaconda3/python</strong></p><p>## <strong>Configure JupyterNoteBook</strong></p><p><strong>cmd5 : </strong>jupyter notebook — generate-config</p><ul><li>there should be a space between notebook and double dashes</li><li>This will generate configuration file for jupyter at .jupyter/ location</li></ul><p>## <strong>Edit Configuration file Generated</strong></p><p><strong>cmd6 : </strong>cd .jupytrer/</p><p>## <strong>Open Vim Editor to edit configuration File</strong></p><p><strong>cmd7 : </strong>vim jupyter_notebook_config.py</p><p>jupyter_notebook_config.py is the configuration file generated</p><p>After opening jupyter_notebook_config.py , use ‘i’ to insert ( start editing ) in to that file</p><p>paste the below code on top of file</p><ul><li>jupyterNotebook = get_config()</li><li>jupyterNotebook.NotebookApp.ip = “*” ( this allows JupyterNotebook to run on all Ip Address of your instance ) you can modify based on your needs</li><li>jupyterNotebook.NotebookApp.open_browser = False ( Dont opens browser by default )</li><li>jupyterNotebook.NotebookApp.port = 9999</li></ul><p>After inserting above above lines press esc to stop editing and type :wq to save and leave the editor</p><p>## <strong>Check , whether jupyterNoteBook is working or not</strong></p><p><strong>cmd8 : </strong>jupyter notebook</p><p>you should see jupyter notebook running on port 9999</p><p>After this , go to aws and copy the public ip of our Instance ( ec2…..)</p><p>enter the following url in browser</p><p><a href="https://ec2-xx-xx-xxx-xxx/"><strong>https://ec2-xx-xx-xxx-xxx</strong></a><strong>:9999</strong></p><p>ec2-xx-xx is your copied Public IP Address of your instance</p><p>after entering that url ,you will probably get warning of untrusted certificate ( ( coz we dont have ssl certificate as of now) , you can go ahead by ignoring that warning</p><p>## <strong>Installing Spark ( root directory )</strong></p><ul><li>Sparks needs Scala , scala needs java to work</li><li>so we have to install java and scala</li></ul><p><strong>cmd9 : </strong>sudo apt update</p><p><strong>cmd10 : </strong>sudo apt install default-jre ( installing java )</p><p><strong>cmd11 : </strong>sudo apt install scala</p><p>use these commands to check whether they installed properly</p><ul><li>java -version ; should return java version</li><li>scala -version ; should return scala version</li></ul><p>## I<strong>nstall Py4j</strong></p><ul><li><strong>Py4J</strong> enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine</li></ul><p>Inorder to instal this library ,we need to make sure that pip installed is connected to Anaconda’s python instead of ubuntu’s deafult ,</p><p>for that we set path</p><p><strong>cmd12 : export PATH=$PATH:$HOME/anaconda3/bin</strong></p><p>Now use conda to install pip</p><p><strong>cmd13 : conda install pip</strong></p><p>check whether we are using correct pip or not by using <strong>which pip </strong>command , it should return pip connected to anaconda3 ( you will see path )</p><p>## <strong>Install Spark and Hadoop</strong></p><p>source : <a href="https://archive.apache.org/dist/spark">https://archive.apache.org/dist/spark</a></p><p><strong>cmd14 : wget </strong><a href="https://archive.apache.org/dist/spark">https://archive.apache.org/dist/spark</a>/spark-3.1.1/spark-3.1.1-bin-hadoop3.2.tgz</p><p>3.1.1 is the lastest version at the time of writing</p><p>It will download spark and hadoop package and we have to extract it</p><p><strong>cmd15 : sudo tar -zxvf </strong>spark-3.1.1-bin-hadoop3.2.tgz</p><p>## <strong>Now Python has to recognise the spark</strong></p><h4><strong>cmd16: export SPARK_HOME=’/home/ubuntu/</strong>spark-3.1.1-bin-hadoop3.2&#39;</h4><h4><strong>cmd17 : export PATH=$SPARK_HOME:$PATH</strong></h4><h4><strong>cmd18 : export PYTHONPATH=$SPARK_HOME/python:$PYTHONPATH</strong></h4><p>Now again Start the jupyter Note book with <strong>cmd8</strong></p><p>Open a python kernel in browser ( using this <a href="https://ec2-xx-xx-xxx-xxx/"><strong>https://ec2-xx-xx-xxx-xxx</strong></a><strong>:9999 )</strong></p><p>run the following piece of code</p><h4>from pyspark import SparkContext</h4><p><strong>sc = SparkContext()</strong></p><p>run the code , if code runs without errors , pyspark set up process on AWS EC2 is successful</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29da649caf01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>