<?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 Dasuni Wijethilaka on Medium]]></title>
        <description><![CDATA[Stories by Dasuni Wijethilaka on Medium]]></description>
        <link>https://medium.com/@dasunichethanadc?source=rss-9e1a40b77d33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*td_01VDdLdA50NMGJPmnIA.jpeg</url>
            <title>Stories by Dasuni Wijethilaka on Medium</title>
            <link>https://medium.com/@dasunichethanadc?source=rss-9e1a40b77d33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:25:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dasunichethanadc/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[Build Your Own Face Emotion Detector in Python (Step-by-Step Guide for Beginners)]]></title>
            <link>https://medium.com/@dasunichethanadc/build-your-own-face-emotion-detector-in-python-step-by-step-guide-for-beginners-8346237a995c?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/8346237a995c</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 06:37:56 GMT</pubDate>
            <atom:updated>2025-11-01T06:46:39.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*o_lVTpemwWbGbf9GL6IwNg.jpeg" /></figure><p>Have you ever wondered how computers can recognize emotions from faces by detecting if someone is happy, sad, or angry?<br> In this tutorial, let’s talk about how to build a <strong>Face Emotion Detection System</strong> using <strong>Python</strong>, <strong>OpenCV</strong>, and <strong>DeepFace.</strong></p><p>First you need to install <strong>Python 3.7 or higher</strong> on your computer.</p><p><a href="https://www.python.org/downloads/">Download Python</a></p><p>Check if Python is installed by running below command in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*DSbNOOfjW0rvk5aVkyfWxQ.png" /></figure><p>Now Let’s create a new folder for your project and navigate into it with below commands</p><p><em>mkdir emotion-detector</em></p><p><em>cd emotion-detector</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*fPMCblilyvqtAXRf0FRw1g.png" /></figure><p>Now open your favorite IDE and create a python file called <em>emotion_detector.py </em>to write our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJx2joZMfspg9io3lZuvpQ.png" /></figure><p>After that we need install the required libraries to access the web camera and detect facial emotions. Open the terminal and write below commands to install them.</p><p>· opencv-python → to access the webcam and display frames</p><p><em>pip install opencv-python</em></p><p>· deepface → for emotion detection</p><p><em>pip install deepface</em></p><p>· tf-keras → backend for DeepFace</p><p><em>pip install tf-keras</em></p><p>We can also install all 3 Libraries together with this command</p><p><em>pip install opencv-python deepface tf-keras</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujzwj1nl856oci5jdzOWnA.png" /></figure><p>We have completed getting installed all the pre-requisit libraries in our PC. Let’s move on to the next step which is writing the code.</p><p>Open the file you created as emotion_detector.py and import the required libraries</p><ul><li><strong>cv2 (OpenCV)</strong> → to access your webcam, capture video frames, and display them.</li><li><strong>DeepFace</strong> → to analyzes human faces .</li><li><strong>time</strong> → to measure elapsed time.</li><li><strong>Counter</strong> → to counts how many times each emotion appears during detection to find the most common one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*KkP0iTI3IWpv-M47bUewFQ.png" /></figure><p>Defining the Emotion Detection Function to Open the webcam, Analyze user face for 5 seconds, Collect detected emotions and return the emotion detected most frequently</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*JfujjFpOTviL-3wkvO76PQ.png" /></figure><p>Initialize Web camera to Open default webcam by ‘0&#39;. (If you have multiple cameras, you can change the number (e.g., 1 for the next camera))</p><p>Then check if web cam is available and accessible. If not it stops the function early with an error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*6_i8We-WltJ7lLFtOZy9MQ.png" /></figure><p>Let’s setup and start the timer. We can print a text to indicate that the camera is starting so user can be prepared to face camera.</p><p>start_time records the current time when detection starts and emotion_detected empty list to store all emotions detected during the 5-second scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*948hCobccFmFoQloQqRC5Q.png" /></figure><p>Now we can run a loop to continuously capture frames from the webcam and command to Stops automatically after 5 seconds.</p><p>Then capture each frame with cap.read(); returns ret — True if frame capture is successful. and frame — The actual image from the webcam.If the webcam fails to read a frame, the program stops safely.</p><p>We can display Countdown Timer on Frame Draws the countdown (from 5 to 0) on the live video feed.</p><ul><li>(10,30) — position of text on screen.</li><li>(0,255,0) — green color.</li><li>2 — text thickness.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwGSN9sF-lbLXqfzvjDhHg.png" /></figure><p>Let’s try to analyze Emotion Using DeepFace.</p><p>· DeepFace.analyze() takes a single image (frame) and returns detected emotions.</p><p>· actions=[‘emotion’] → only analyze emotions (not age, gender, etc.).</p><p>· enforce_detection=False → prevents errors when no face is visible.</p><p>· silent=True → disables DeepFace console output for cleaner logs.</p><p>If multiple faces are detected, DeepFace returns a list. This ensures we only use the first detected face’s result.</p><p>Then extract the most likely emotion (dominant) from DeepFace’s analysis and add it to the list emotions_detected so we can count emotions later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*R0yw5v4ZbHzrqbV_mnnJFg.png" /></figure><p>Display Detected Emotion or no emotion errors on Frame</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*cD6iOxi12W6DGP0KpuOOWQ.png" /></figure><p>Now we can display the Webcam Feed Opening a real-time video window titled “Emotion Detection”. it will continuously update as each new frame is analyzed. and finally we can let user stop the program early by pressing ‘q’.</p><p>· cap.release() → closes the webcam safely.</p><p>· cv2.destroyAllWindows() → closes all OpenCV display windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*t8uhWy36RpmM8JsmjzbFcw.png" /></figure><p>Now we can write code to find the most common emotion and display final result or handle No Detection Case</p><ul><li>Uses Counter to count how many times each emotion appeared.</li><li>most-common — returns the emotion detected most frequently.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEkET8jSbBr2j-k7Qr-qAg.png" /></figure><p>Finally, you can run this project by giving <em>python emotion_detector.py </em>in the terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0pstOyN0mzoY3pUP7fy3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFScX4tTBXTiBB7wL4VpDQ.png" /></figure><p>And there you have it — your very own <strong>Face Emotion Detection System</strong> built completely from scratch using Python!</p><p>In this project, you learned how to:<br>· Access and control your webcam using <strong>OpenCV</strong></p><p>· Detect emotions in real time with <strong>DeepFace</strong></p><p>· Use simple logic to determine the most common emotion</p><p>· Display results both on screen and in the console</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8346237a995c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get started with Generative AI (GenAI)]]></title>
            <link>https://medium.com/@dasunichethanadc/get-started-with-generative-ai-genai-955d4e2ea9fe?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/955d4e2ea9fe</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 07:13:03 GMT</pubDate>
            <atom:updated>2025-10-17T07:20:36.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b72kXTbNPHZlsyPTrG6-YA.jpeg" /></figure><h3>Generative AI: Redefining Creativity in the Digital Age</h3><p>Artificial Intelligence used to sound like science fiction. But fast-forward to today, and AI isn’t just a buzzword anymore. It’s quietly shaping how we write, design, code, and even think.</p><h3>What Is Generative AI?</h3><p>Generative AI (or <strong>GenAI</strong>) is a type of artificial intelligence that can create new content such as words, images, code, music, videos, and more by learning patterns from existing data.</p><p>Unlike traditional AI systems that just <em>analyze</em> or <em>classify</em> data, Generative AI actually <em>creates</em>. It can produce something entirely new, like a painting, an article, or even a snippet of functional code.</p><ul><li>Writing essays or blogs → <em>ChatGPT, Gemini</em></li><li>Creating artwork and designs → <em>DALL·E, Midjourney</em></li><li>Helping with code → <em>GitHub Copilot, Replit AI</em></li><li>Making music → <em>Suno, Udio, Mubert</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*lDD8P8pIXVtRzjL4wJ9poA.png" /></figure><h3>How Does It Work?</h3><p>Generative AI runs on machine learning at its core. specially a branch called <strong>deep learning</strong>. It studies massive amounts of data, spots patterns, and then uses those patterns to generate something new.</p><p>Two major technologies drive most of what we see today:</p><h3>1. Large Language Models (LLMs)</h3><p>These are trained on billions of text samples, books, websites, articles, even code. They predict the next word in a sentence based on the ones before it.</p><p><em>Example:<br> Input → “Once upon a time,”<br> Prediction → “there was a small village by the sea.”</em></p><p>That’s how tools like ChatGPT can write essays, scripts, and stories one word at a time.</p><h3>2. Diffusion Models</h3><p>These models are behind most image and video generation. They start with random noise and gradually turn it into a clear, detailed image that matches your prompt.</p><p><em>Example:<br> Prompt → “A cat playing guitar in outer space.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpwXztzmfKDYMFiYooNXsA.jpeg" /></figure><h3>Why Generative AI Feels So Special</h3><p>Traditional software follows strict rules. Generative AI learns creativity. It’s like having a co-creator who understands your vision and brings it to life in seconds.</p><p>Feature Description Creativity Generates unique, original results. Adaptability Learns and adjusts to different tasks. Versatility Works with text, visuals, video, and code. Scalability Can create thousands of assets instantly. Whether it’s generating marketing visuals or writing product descriptions, it’s becoming the creative partner no one saw coming.</p><h3>Where Is Generative AI Used Today?</h3><p>Pretty much everywhere you look.</p><p>· <strong>Content creation</strong> — Blogs, ads, social media posts</p><p>· <strong>Design</strong> — Logos, illustrations, and campaign visuals</p><p>· <strong>Education</strong> — Study notes, translations, and tutoring</p><p>· <strong>Software development</strong> — Writing, testing, and fixing code</p><p>· <strong>Customer service</strong> — Smart chatbots and voice assistants</p><p>· <strong>Entertainment</strong> — Storyboarding, music, and video ideas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53jAZ9fZFsPyumuH01Gxhw.jpeg" /></figure><h3>The Art of Prompt Engineering</h3><p>A prompt is basically your instruction , how you tell the AI what you want.<br> And the clearer your prompt is, the better the result.</p><p>Here are the 4 elements of a good prompt, from most to least important</p><ol><li><strong>🧠 Task</strong> — What do you want it to do?<br> <em>Ex: “Summarize this article.”</em></li><li><strong>🌍 Context</strong> — What’s it about?<br> <em>Ex: “It’s about renewable energy and climate change.”</em></li><li><strong>📐 Format</strong> — How should it look?<br> <em>Ex: “Write the summary in 3 short bullet points.”</em></li><li><strong>💡 Example</strong> — Show a sample answer or tone.<br><em> Ex: “Example: • Point 1 … • Point 2 … • Point 3 …”</em></li></ol><p>When you use AI models like ChatGPT or Gemini, there’s a hidden setting called <strong>temperature</strong> that controls creativity.</p><ul><li><strong>Low temperature</strong> (near 0) → More predictable, focused, deterministic outputs</li><li><strong>Medium temperature</strong> (0.7–1.0) → Balanced between coherence and creativity</li><li><strong>High temperature</strong> (1.5+) → More random, creative, varied outputs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*pC7DoxsjlHERovUxx6luJQ.png" /></figure><h3>The Challenges We face in GenAI</h3><ul><li><strong>Biases in data</strong></li></ul><p>Generative AI systems learn from massive datasets collected from the internet which, unfortunately, means they also learn our flaws. The models absorb the biases, stereotypes, and cultural imbalances hidden in that data. For example, an AI trained mostly on Western sources might unintentionally favor certain languages, appearances, or social perspectives. These biases aren’t intentional, but they can shape how the model responds to prompts or represents people, making fairness and inclusivity a continuing challenge for AI developers.</p><ul><li><strong>Misinformation</strong></li></ul><p>One of the biggest challenges with Generative AI is its confidence. It can generate text that sounds polished and credible even when it’s completely wrong. Because models are trained to predict what looks right rather than what’s <em>true</em>, they sometimes produce misinformation without realizing it. This can be especially harmful in areas like health, finance, or news. The takeaway? AI output should always be fact-checked, just like any other online information.</p><ul><li><strong>Language inequality</strong></li></ul><p>Most AI models are heavily trained in English because that’s where most of the world’s digital content exists. As a result, languages with smaller online communities like Sinhala, Tamil get less representation and poorer performance. This creates a gap in accessibility and accuracy for non-English users. Bridging this language divide will be key to making AI truly global, giving everyone equal creative and technological opportunities.</p><ul><li><strong>Ethical issues</strong></li></ul><p>Then there’s the ethical side of things one that’s often overlooked in the excitement. Generative AI can unintentionally copy copyrighted materials, create deepfakes, or reproduce private information if the training data wasn’t handled properly. Questions about ownership, consent, and privacy are becoming more urgent as AI-generated media spreads online. Building ethical guidelines and transparency into AI development isn’t just ideal — it’s essential for trust and accountability.</p><h3>What’s Next for Generative AI?</h3><p>We’re just scratching the surface. In the coming years, Generative AI will blend into every creative field imaginable:</p><ul><li><strong>Education</strong> — Personalized learning and tutoring</li><li><strong>Entertainment</strong> — AI-driven video editing and storytelling</li><li><strong>Business</strong> — Automated marketing and analytics</li><li><strong>Healthcare</strong> — Drug discovery and smarter diagnoses</li></ul><p>Generative AI isn’t just a tech trend . It’s a creative revolution. It doesn’t think like us, but it learns from us. And when used right, it can make us more imaginative, more productive, and more human than ever before.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955d4e2ea9fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures and Algorithms (Part 2)]]></title>
            <link>https://medium.com/@dasunichethanadc/data-structures-and-algorithms-part-2-64868947e90a?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/64868947e90a</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Wed, 07 May 2025 07:59:44 GMT</pubDate>
            <atom:updated>2025-05-07T07:59:44.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*o6A7SHmo_nU9mNOLpBj5Zg.png" /></figure><p>Welcome to the second chapter of the <strong>DSA series</strong>! In this post, we’ll dive into <strong>Non-Linear Data Structures</strong> and begin exploring <strong>Sorting Algorithms</strong> — essential tools for organizing and managing complex data in efficient ways.</p><h3>🌲 Non-Linear Data Structures</h3><p><strong>Non-linear data structures</strong> organize data hierarchically or in a connected manner. This makes them ideal for representing relationships such as trees and networks.</p><h4>1. Trees</h4><p>A <strong>tree</strong> is a widely-used non-linear data structure that mimics a hierarchical tree structure with a root and subtrees of children, represented as a set of connected nodes.</p><p>📌 Key Terms:</p><ul><li><strong>Node</strong>: Each element in the tree is called a node.</li><li><strong>Root</strong>: The topmost node of a tree. It has no parent. Depth = 0.</li><li><strong>Parent</strong>: A node that has child nodes.</li><li><strong>Child</strong>: A node that is a descendant of another node.</li><li><strong>Leaf</strong>: A node that has no children.</li><li><strong>Depth</strong>: The level of a node relative to the root. Root has a depth of 0, its children have a depth of 1, and so on.</li></ul><p>A <strong>Binary Search Tree (BST)</strong> is a specialized type of binary tree that maintains a specific ordering property:</p><p>At any node with value k, all the nodes in its left subtree have values <strong>strictly less than </strong>k, and all the nodes in its right subtree have values <strong>greater than</strong> k.</p><h4>🔑 Key Properties:</h4><ul><li>Each node has <strong>at most two children</strong>: left and right.</li><li><strong>Left subtree</strong> contains only nodes with values <strong>less than the current node</strong>.</li><li><strong>Right subtree</strong> contains only nodes with values <strong>greater than the current node</strong>.</li><li>No duplicate values are stored (in strict BSTs).</li></ul><p>ex: lets arrange the following set of values in a tree</p><p>84, 41, 96, 24, 37, 50, 13, 98</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMNBrTCJYcsTyF3_c3lZ2w.png" /></figure><p>🧠 Why Trees?</p><p>Trees are excellent for:</p><ul><li>Representing hierarchical data (e.g., file systems, organizational charts)</li><li>Optimizing search operations (e.g., Binary Search Trees)</li><li>Routing algorithms (e.g., in networking)</li><li>Parsing expressions in compilers</li></ul><h4>2. Graphs</h4><p>A <strong>graph</strong> is a non-linear data structure that consists of:</p><ul><li>A <strong>set of vertices (or nodes)</strong>, and</li><li>A <strong>set of edges</strong>, which are connections between those vertices.</li></ul><p>Graphs are incredibly versatile and are used in many domains — from modeling networks to solving pathfinding problems.</p><h4>🔑 Key Properties:</h4><ul><li><strong>Vertex (Node)</strong>: A point or position in the graph.</li><li><strong>Edge</strong>: A line connecting two vertices.</li><li><strong>Weight</strong>: A number associated with an edge (optional), representing cost, distance, or time.</li></ul><p>In the image you provided:</p><h4>Undirected Graph</h4><ul><li>Edges have <strong>no direction</strong>. Ex: Edge between A and B means you can go both from A to B <strong>and</strong> B to A.</li><li>The adjacency matrix is <strong>symmetric</strong>.</li><li>Applications: Social networks (friendships), bidirectional road maps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*b7jZYkk9PY4Yr5N-vQ29DA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*FCREJf3Rlhyuc_5OnS3YWQ.png" /></figure><h4>Directed Graph</h4><ul><li>Edges have a <strong>clear direction</strong>.</li><li>Ex: A ➝ C (value 7) does <strong>not</strong> imply C ➝ A exists.</li><li>The adjacency matrix is <strong>not necessarily symmetric</strong>.</li><li>Applications: Web page links, one-way streets, task scheduling.</li></ul><p><strong>Example Matrix (Directed)</strong><br> From A to C = 7<br> From C to A = 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*xtmrIJYwrywiwSjDXALBZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*c4Gvz99thMZ54YfxjpI-4w.png" /></figure><p>🧠 Why Trees?</p><ul><li>Finding the <strong>shortest path</strong> in GPS navigation systems.</li><li>Representing and navigating <strong>computer networks</strong>.</li><li>Modeling <strong>social networks</strong> like LinkedIn or Facebook.</li><li>Managing <strong>task dependencies</strong> in project scheduling.</li></ul><h3>🌲 Sorting Algorithms</h3><p>Sorting algorithms are fundamental techniques in computer science used to arrange a list or an array of elements particular order, usually ascending or descending order. Effective sorting improves the efficiency of other algorithms and is significant in many applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*Wo_8vaj3LTEGCQQEVIhcpg.png" /></figure><h3>Insertion Sort</h3><ul><li>Builds the final sorted array one item at a time.</li><li>Takes an element from the unsorted part and inserts it into the correct position in the sorted part.</li><li>Good for Small or partially sorted datasets and simple implementations</li><li>Simple implementation</li></ul><p>Process:</p><ol><li>Assume the first element is sorted.</li><li>Compare the next element with the sorted part and insert it in the correct position.</li><li>Repeat for all elements.</li></ol><p><strong>Initial Array: </strong><strong>[6, 3, 8, 1]</strong></p><ol><li>First element 6 is considered sorted.</li><li>Take 3: Compare with 6. Since 3 &lt; 6, insert 3 before 6.<br> → [3, 6, 8, 1]</li><li>Take 8: Compare with 6. Since 8 &gt; 6, it&#39;s already in the correct position.<br> → [3, 6, 8, 1]</li><li>Take 1: Compare with 8, 6, and 3, shift all right, and insert 1 at beginning.<br> → [1, 3, 6, 8]</li></ol><p>✅ <strong>Sorted Array:</strong> [1, 3, 6, 8]</p><h3>Time &amp; Space Complexity:</h3><ul><li><strong>Best Case (Sorted List):</strong> O(n)</li><li><strong>Average Case:</strong> O(n²)</li><li><strong>Worst Case (Reverse Sorted):</strong> O(n²)</li><li><strong>Space:</strong> O(1) (In-place)</li></ul><h3>Selection Sort</h3><ul><li>Repeatedly selects the smallest (or largest) element from the unsorted part and swaps it with the first unsorted element.</li><li>Doesn’t adapt to input data (always makes the same number of comparisons).</li><li>When memory write operations are costly (fewer swaps compared to bubble sort)</li></ul><p>Process:</p><ol><li>Find the minimum element and move it to the beginning.</li><li>Repeat for the rest of the array.</li></ol><p><strong>Initial Array: </strong><strong>[6, 3, 8, 1]</strong></p><ol><li>Find the minimum from [6, 3, 8, 1] → 1, swap with first element.<br> → [1, 3, 8, 6]</li><li>Find the minimum from [3, 8, 6] → 3, already in place.<br> → [1, 3, 8, 6]</li><li>Find the minimum from [8, 6] → 6, swap with 8.<br> → [1, 3, 6, 8]</li></ol><p>✅ <strong>Sorted Array:</strong> [1, 3, 6, 8]</p><h3>Time &amp; Space Complexity:</h3><ul><li><strong>Best, Average, and Worst Case:</strong> O(n²)</li><li><strong>Space:</strong> O(1) (In-place)</li></ul><h3>Bubble Sort</h3><ul><li>Repeatedly compares adjacent elements and swaps them if they are in the wrong order.</li><li>With each pass, the largest unsorted element “bubbles up” to its correct position.</li><li>Good for Educational purposes and simple problems and Bubble sort is easy to understand and implement</li></ul><p>Process:</p><ol><li>Compare adjacent elements.</li><li>Swap if needed.</li><li>Repeat passes until the array is sorted.</li></ol><p><strong>Initial Array: </strong><strong>[6, 3, 8, 1]</strong></p><p>First Pass:</p><ul><li>Compare 6 and 3 → swap → [3, 6, 8, 1]</li><li>Compare 6 and 8 → no change</li><li>Compare 8 and 1 → swap → [3, 6, 1, 8]</li></ul><p>Second Pass:</p><ul><li>Compare 3 and 6 → no change</li><li>Compare 6 and 1 → swap → [3, 1, 6, 8]</li></ul><p>Third Pass:</p><ul><li>Compare 3 and 1 → swap → [1, 3, 6, 8]</li></ul><p>✅ <strong>Sorted Array:</strong> [1, 3, 6, 8]</p><h3>Time &amp; Space Complexity:</h3><ul><li><strong>Best Case (Sorted List):</strong> O(n)</li><li><strong>Average &amp; Worst Case:</strong> O(n²)</li><li><strong>Space:</strong> O(1) (In-place)</li></ul><p>Hope you picked up some useful stuff about non-linear data structures and sorting algorithms in this blog. Catch you next time with another interesting topic.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64868947e90a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures and Algorithms (Part 1)]]></title>
            <link>https://medium.com/@dasunichethanadc/data-structures-and-algorithms-part-1-224a4afef900?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/224a4afef900</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 18:43:24 GMT</pubDate>
            <atom:updated>2025-04-07T18:43:24.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*bmTgFJl_aHlQvUNxOD7YWA.png" /></figure><p><strong>Data Structure</strong></p><p>A data structure is a form and storage of data in a way that it becomes easier to access, maintain, and modify. The data structure relies on the type of data and the operations we want to do.</p><p>Data structures are crucial in computer science to efficiently manage significant quantities of data. They facilitate efficient and effective algorithms, which reduce complexity and improve performance.</p><p>Common applications include databases, search engines, and other applications based on fast and well-organized access to data.</p><p><strong>Algorithm</strong></p><p>An algorithm is a clear, step-by-step method for solving a problem or accomplishing some task. In computer science, algorithms are written in programming languages and operate on data structures.</p><p>Algorithms form the core of programming. A good algorithm makes programs efficient and faster, and it helps us solve problems effectively.</p><p>Studying algorithms helps programmers write better, optimized code and improve overall system performance.</p><p><strong>Why Study Data Structures and Algorithms (DSA)?</strong></p><p>Efficient Searching: Imagine searching for a product in a shop with over 1 million products — without data structures, the process becomes significantly slower as data grows.</p><p>Handling Large Amounts of Data: Even with the speed of processors, they can’t compensate for inefficient data handling when there are billions of records to process.</p><p>Scalability and Performance: Web applications are bombarded with thousands of simultaneous users’ requests. Were it not for effective data structures, even high-performance servers would crash or hang.</p><p>In this blog we are discussing about data structures</p><p><strong>Importance of Data Structures:</strong></p><p>Correctness: A proper data structure ensures proper handling of data through an agreed interface. This is critical to developing reliable software.</p><p>Time Efficiency: Good data structures reduce the time complexity of operations like searching, inserting, deleting, and updating information — making programs run faster.</p><p>Space Efficiency: Data structures help minimize space complexity, conserving memory effectively, especially when dealing with large data sets.</p><p>There are 2 types of Data structures</p><p>1. <strong>Linear Data Structures</strong><br>Data elements are stored sequentially, one following the other. All elements can be accessed in a single pass, from beginning to end (traversing). Easy to comprehend and implement.</p><p>Examples: Array, Linked List, Stack, Queue</p><p>2. Non-Linear Data Structures<br>Data elements are stored in a hierarchical or connected manner — not sequentially. Cannot access all elements at once; specific methods are required. Complexity: Difficult to implement but more memory-efficient.</p><p>Examples: Tree, Graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MouYBAerTbwfNmVRKqo63A.png" /><figcaption>Data Structure types</figcaption></figure><p><strong>Linear Data Structures</strong></p><ol><li>Array -An <strong>array</strong> is a data structure that allows us to store multiple values of the same data type in a single variable. It is widely used in programming because it enables efficient storage and manipulation of data.</li></ol><p>Key Characteristics of Arrays</p><ul><li>Fixed Size: The size of an array is usually determined when it is created.</li><li>Indexed Storage: Elements in an array are stored in contiguous memory locations and can be accessed using an index.</li><li>Efficient Access: Accessing any element using its index takes constant time O(1).</li><li>Sequential Storage: Elements are stored in a continuous memory block.</li></ul><p><em>Ex: my_array = [7, 12, 9, 4, 11]</em></p><p>Element id starts from 0</p><p><em>Accessing Elements of array =&gt; my_array[0] =&gt; 7</em></p><p>2. Linked List — A Linked List is a linear data structure where elements (called nodes) are not stored in contiguous memory. Instead, each node contains:</p><p>Data — the value stored in the node.</p><p>Pointer — a reference to the next node in the sequence.</p><p>Key Characteristics of Arrays</p><p>· This structure allows dynamic memory allocation and efficient insertion/deletion operations.</p><p>· Dynamic Size: Grows or shrinks during runtime.</p><p>· Non-contiguous Storage: Nodes are scattered in memory, linked by pointers.</p><p>· Slow Access: Must traverse from the head to access a specific node (no random access).</p><p>· More Memory: Each node uses extra memory for the pointer.</p><p>Types of Linked Lists</p><ul><li><strong>Singly Linked List</strong>: Each node points to the next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGDGebvG3UnI6blmxEvg9g.png" /></figure><ul><li><strong>Doubly Linked List</strong>: Each node points to both next and previous nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F03aRVRy70SP7NVD06a8Ig.png" /></figure><ul><li><strong>Circular Linked List</strong>: Last node points back to the first.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3pDOSVclcJ8IEANxuLwgg.png" /></figure><p>3. Queue — A Queue is a linear data structure that follows the FIFO (First In, First Out) principle — the first element added is the first one to be removed.</p><p>Key Characteristics</p><ul><li>Ordered: Elements are added to the rear and removed from the front.</li><li>Use Cases: Task scheduling, printer queues, customer service systems.</li></ul><p>Operations</p><ul><li>Enqueue: Add an element to the rear.</li><li>Dequeue: Remove the front element.</li><li>Peek/Front: See the front element without removing it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1M0GVj8MAVm5OxyXdWIeQ.png" /></figure><p>4. Stack — A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle — the last element added is the first one to be removed.</p><p>Key Characteristics</p><ul><li>Ordered: Elements are added and removed from the top.</li><li>Use Cases: Undo functionality, backtracking, function calls in recursion.</li></ul><p>Operations</p><ul><li>Push: Add an element to the top.</li><li>Pop: Remove the top element.</li><li>Peek/Top: View the top element without removing it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RXtRPvKDafRdbJ_kYQhB2g.png" /></figure><p>We will discuss about the Non linear data structures and as well as the algorithms in the upcoming blogs</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=224a4afef900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with TypeScript in React]]></title>
            <link>https://medium.com/@dasunichethanadc/getting-started-with-typescript-in-react-f3c7ddae4ccd?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c7ddae4ccd</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 10:14:19 GMT</pubDate>
            <atom:updated>2025-03-14T10:18:15.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYpMeQ13WpYzs53OSjQy2A.jpeg" /></figure><p>TypeScript has become an essential tool for modern React development, allowing for type safety and an improved developer experience. This tutorial will walk you through installing and using TypeScript with React, illustrating real-world use cases, and showing best practice.</p><p>TypeScript enhances React development by</p><ul><li><strong>Catch errors early</strong>: Identify bugs during development rather than at runtime</li><li><strong>Better IDE support</strong>: Get intelligent code completion and inline documentation</li><li><strong>Improved code maintenance</strong>: Types act as built-in documentation for your components</li></ul><p><strong>Create React App</strong>: npx create-react-app my-app --template typescript</p><p><strong>Function Components with props</strong></p><p>The simplest way to type a function component is by defining the props structure:</p><pre>function Button({ text, onClick }: { text: string; onClick: () =&gt; void }) {<br> return &lt;button onClick={onClick}&gt;{text}&lt;/button&gt;;<br>}<br>interface CardProps {<br> title: string;<br> description: string;<br> imageUrl?: string; // Optional prop with &#39;?&#39;<br>}<br>function Card({ title, description, imageUrl }: CardProps) {<br> return (<br> &lt;div className=&quot;card&quot;&gt;<br> {imageUrl &amp;&amp; &lt;img src={imageUrl} alt={title} /&gt;}<br> &lt;h2&gt;{title}&lt;/h2&gt;<br> &lt;p&gt;{description}&lt;/p&gt;<br> &lt;/div&gt;<br> );<br>}</pre><p><strong>Children Props</strong></p><pre>import { ReactNode } from &#39;react&#39;;<br>interface LayoutProps {<br> children: ReactNode; // Accepts any valid JSX content<br> title: string;<br>}<br>function Layout({ children, title }: LayoutProps) {<br> return (<br> &lt;div&gt;<br> &lt;header&gt;<br> &lt;h1&gt;{title}&lt;/h1&gt;<br> &lt;/header&gt;<br> &lt;main&gt;{children}&lt;/main&gt;<br> &lt;/div&gt;<br> );<br>}</pre><p><strong>React Hooks</strong></p><p>React Hooks let you use state and other React features in functional components, making your code simpler and easier to reuse.</p><p>1. u<strong>seState</strong> hook can infer the state type from the initial value:</p><pre>// Type inferred as string<br>const [name, setName] = useState(&#39;&#39;);<br>// for more complex states<br>const [user, setUser] = useState&lt;User | null&gt;(null);<br>// Union types<br>type Status = &#39;idle&#39; | &#39;loading&#39; | &#39;success&#39; | &#39;error&#39;;<br>const [status, setStatus] = useState&lt;Status&gt;(&#39;idle&#39;);</pre><p>2. <strong>UseReducer</strong> can be typed with action and state types:</p><pre>interface State {<br> count: number;<br>}<br>type Action = <br> | { type: &#39;increment&#39; }<br> | { type: &#39;decrement&#39; }<br> | { type: &#39;reset&#39; }<br> | { type: &#39;set&#39;; value: number };<br>function reducer(state: State, action: Action): State {<br> switch (action.type) {<br> case &#39;increment&#39;:<br> return { count: state.count + 1 };<br> case &#39;decrement&#39;:<br> return { count: state.count - 1 };<br> case &#39;reset&#39;:<br> return { count: 0 };<br> case &#39;set&#39;:<br> return { count: action.value };<br> default:<br> throw new Error(`Unhandled action type`);<br> }<br>}<br>function Counter() {<br> const [state, dispatch] = useReducer(reducer, { count: 0 });<br> <br> return (<br> &lt;div&gt;<br> Count: {state.count}<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;reset&#39; })}&gt;Reset&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;set&#39;, value: 10 })}&gt;Set to 10&lt;/button&gt;<br> &lt;/div&gt;<br> );<br>}</pre><p>3. <strong>useContext</strong> Type-safe context providers and consumers:</p><pre>import { createContext, useContext, ReactNode, useState } from &#39;react&#39;;<br>interface ThemeContextType {<br> theme: &#39;light&#39; | &#39;dark&#39;;<br> toggleTheme: () =&gt; void;<br>}<br>// Create context with a default value<br>const ThemeContext = createContext&lt;ThemeContextType | undefined&gt;(undefined);<br>// Provider component<br>interface ThemeProviderProps {<br> children: ReactNode;<br>}<br>export function ThemeProvider({ children }: ThemeProviderProps) {<br> const [theme, setTheme] = useState&lt;&#39;light&#39; | &#39;dark&#39;&gt;(&#39;light&#39;);<br> <br> const toggleTheme = () =&gt; {<br> setTheme(current =&gt; current === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;);<br> };<br> <br> return (<br> &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br> {children}<br> &lt;/ThemeContext.Provider&gt;<br> );<br>}<br>// Custom hook for consuming context<br>export function useTheme() {<br> const context = useContext(ThemeContext);<br> if (context === undefined) {<br> throw new Error(&#39;useTheme must be used within a ThemeProvider&#39;);<br> }<br> return context;<br>}<br>// Usage<br>function ThemedButton() {<br> const { theme, toggleTheme } = useTheme();<br> return (<br> &lt;button <br> onClick={toggleTheme}<br> style={{ background: theme === &#39;dark&#39; ? &#39;#333&#39; : &#39;#fff&#39;, color: theme === &#39;dark&#39; ? &#39;#fff&#39; : &#39;#333&#39; }}<br> &gt;<br> Toggle to {theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;} mode<br> &lt;/button&gt;<br> );<br>}</pre><p><strong>Event Handling in TypeScript</strong></p><pre>import { ChangeEvent, FormEvent, MouseEvent } from &#39;react&#39;;<br>function LoginForm() {<br> const handleSubmit = (e: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br> e.preventDefault();<br> // Form submission logic<br> };<br>const handleInputChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br> console.log(e.target.value);<br> };<br> <br> const handleButtonClick = (e: MouseEvent&lt;HTMLButtonElement&gt;) =&gt; {<br> console.log(&#39;Button clicked&#39;);<br> };<br>return (<br> &lt;form onSubmit={handleSubmit}&gt;<br> &lt;input type=&quot;email&quot; onChange={handleInputChange} /&gt;<br> &lt;button type=&quot;submit&quot; onClick={handleButtonClick}&gt;Log in&lt;/button&gt;<br> &lt;/form&gt;<br> );<br>}</pre><p><strong>Best Practices</strong></p><ol><li><strong>Start with loose types, refine later</strong>: Begin with less strict types (any or unknown), then gradually add stricter typing as your application evolves.</li><li><strong>Create prop interfaces/types for each component</strong>: Enhances documentation and reusability.</li><li><strong>Enable strict mode in tsconfig.json</strong>: Catch more issues with strictness enabled.</li><li><strong>Add JSDoc comments to complex types</strong>: Provides excellent editor tooltips.</li><li><strong>Prefer interfaces for public APIs and types for complex unions</strong>: Generally follows TypeScript community practices.</li></ol><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c7ddae4ccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Handlebars.js]]></title>
            <link>https://medium.com/@dasunichethanadc/a-beginners-guide-to-handlebars-js-54ec00bb16ac?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/54ec00bb16ac</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 06:52:59 GMT</pubDate>
            <atom:updated>2025-02-27T06:52:59.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdMiI4OAmdpuKcxOJmY8ig.png" /></figure><p>While creating modern web applications, dynamically updating the user interface is a critical requirement. Handlebars.js is a lightweight, logic-less templating engine that simplifies the process of rendering dynamic HTML content for developers. It extends the capabilities of Mustache.js and provides additional features like helper functions and block expressions but remains simple and easy to implement.</p><h3>Why Use Handlebars.js?</h3><p>Many web applications require dynamic content rendering, but directly manipulating the DOM with JavaScript can be tedious and error-prone. Handlebars.js provides a structured way to separate logic from the UI, making code cleaner and more maintainable. Here are some reasons why developers love Handlebars</p><ul><li><strong>Separation of Concerns</strong>: Keeps HTML structure separate from JavaScript logic, making code modular and reusable.</li><li><strong>Logic-less Templates</strong>: Uses simple placeholders instead of embedding JavaScript logic directly into HTML.</li><li><strong>Reusability</strong>: Encourages writing reusable templates for components like headers, footers, and content sections.</li><li><strong>Integration</strong>: Compatible with various front-end and back-end frameworks, making it a versatile choice for templating.</li><li><strong>Improved Readability</strong>: Handlebars syntax is clean and easy to understand, making it accessible even for beginners.</li></ul><h3>Setting Up Handlebars.js in a React Project</h3><h3>Step 1: Create a React Project</h3><p>If you don’t have a React project already, create one using Create React App:</p><pre>npx create-react-app my-handlebars-app<br>cd my-handlebars-app</pre><h3>Step 2: Install Handlebars.js</h3><p>Inside your project directory, install Handlebars:</p><pre>npm install handlebars</pre><h3>Step 3: Create a Handlebars Template</h3><p>Create a new folder called templates inside the src directory. Then, create a Handlebars template file template.hbs inside templates:</p><pre>&lt;h1&gt;{{title}}&lt;/h1&gt;<br>&lt;p&gt;{{description}}&lt;/p&gt;</pre><h3>Step 4: Load and Compile the Template in React</h3><p>Now, let’s load the Handlebars template in a React component and render dynamic content.</p><h4>Create a Component Using Handlebars</h4><p>Create a new file HandlebarsComponent.js inside the src folder:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import Handlebars from &#39;handlebars&#39;;</pre><pre>const HandlebarsComponent = () =&gt; {<br>  const [html, setHtml] = useState(&#39;&#39;);</pre><pre>  useEffect(() =&gt; {<br>    // Fetch the Handlebars template file<br>    fetch(&#39;/templates/template.hbs&#39;)<br>      .then((response) =&gt; response.text())<br>      .then((templateSource) =&gt; {<br>        const template = Handlebars.compile(templateSource);<br>        const data = {<br>          title: &#39;Welcome to Handlebars.js&#39;,<br>          description: &#39;A powerful yet simple templating engine in React.&#39;,<br>        };<br>        setHtml(template(data));<br>      });<br>  }, []);</pre><pre>  return &lt;div dangerouslySetInnerHTML={{ __html: html }} /&gt;;<br>};</pre><pre>export default HandlebarsComponent;</pre><h3>Step 5: Use the Component in Your App</h3><p>Open App.js and import the HandlebarsComponent:</p><pre>import React from &#39;react&#39;;<br>import HandlebarsComponent from &#39;./HandlebarsComponent&#39;;</pre><pre>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;HandlebarsComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><h3>Step 6: Start the Development Server</h3><p>Run the following command to start your React app:</p><pre>npm start</pre><p>You should see the Handlebars template rendered with dynamic data in your React application.</p><h3>Using Helpers in Handlebars with React</h3><p>Helpers allow you to extend Handlebars with custom functions. They make templates more powerful by handling operations like string formatting and conditional logic.</p><h4>Example: Uppercase Helper</h4><p>Modify HandlebarsComponent.js to register a helper function:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import Handlebars from &#39;handlebars&#39;;</pre><pre>const HandlebarsComponent = () =&gt; {<br>  const [html, setHtml] = useState(&#39;&#39;);</pre><pre>  useEffect(() =&gt; {<br>    Handlebars.registerHelper(&#39;uppercase&#39;, function(str) {<br>      return str.toUpperCase();<br>    });</pre><pre>    fetch(&#39;/templates/template.hbs&#39;)<br>      .then((response) =&gt; response.text())<br>      .then((templateSource) =&gt; {<br>        const template = Handlebars.compile(templateSource);<br>        const data = {<br>          title: &#39;Welcome to Handlebars.js&#39;,<br>          description: &#39;A powerful yet simple templating engine in React.&#39;,<br>        };<br>        setHtml(template(data));<br>      });<br>  }, []);</pre><pre>  return &lt;div dangerouslySetInnerHTML={{ __html: html }} /&gt;;<br>};</pre><pre>export default HandlebarsComponent;</pre><p>Modify template.hbs to use the helper:</p><pre>&lt;h1&gt;{{uppercase title}}&lt;/h1&gt;<br>&lt;p&gt;{{description}}&lt;/p&gt;</pre><p>The title will be displayed in uppercase due to the helper function.</p><p>If you’re interested in learning more, check out the official Handlebars.js documentation: <a href="https://handlebarsjs.com/">Handlebars.js</a>.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54ec00bb16ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Husky: Git Hooks Made Easy]]></title>
            <link>https://medium.com/@dasunichethanadc/understanding-husky-git-hooks-made-easy-35e48aacf3ea?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e48aacf3ea</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:43:31 GMT</pubDate>
            <atom:updated>2025-01-14T18:51:56.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RirxJP2sMJymGY-36ZKyHQ.jpeg" /></figure><p><strong>What is Husky?</strong></p><p>Husky is a popular development tool that makes working with Git hooks more accessible and manageable. Git hooks are scripts that run automatically before or after Git events like commit, push, or receive. While Git hooks are powerful, they can be challenging to set up and share across a development team. Husky simplifies this process by allowing you to manage and share Git hooks using npm scripts, making them a part of your project’s package.json.</p><p><strong>The Importance of Husky</strong></p><p>Husky plays a crucial role in maintaining code quality and consistency across development teams for several reasons:</p><p>1. Automated Quality Control: By automating checks before commits or pushes, Husky ensures that only code meeting your team’s standards makes it into your repository.</p><p>2. Consistency Across Teams: Since Husky configurations are stored in your project files, every team member automatically gets the same Git hooks when they clone the repository.</p><p>3. Easy Integration: Husky seamlessly integrates with other development tools and can be configured using simple npm scripts, making it accessible even to developers who aren’t Git experts.</p><p>4. Prevention of Issues: By catching problems before they enter your codebase, Husky helps prevent issues from propagating through your development pipeline.</p><p><strong>Common Use Cases for Husky</strong></p><p>Husky can be utilized in various scenarios to improve your development workflow:</p><p>1. Code Quality Checks:<br> — Linting code with ESLint<br> — Formatting code with Prettier<br> — Running unit tests before pushes<br> — Validating commit messages</p><p>2. Branch Management:<br> — Enforcing branch naming conventions<br> — Preventing direct commits to protected branches<br> — Validating branch names before pushes</p><p>3. Dependency Management:<br> — Checking for outdated dependencies<br> — Ensuring package-lock.json is up to date<br> — Verifying node_modules consistency</p><p>4. Custom Workflows:<br> — Running build processes before commits<br> — Updating documentation automatically<br> — Generating changelogs</p><p><strong>Setting Up Husky with ESLint and Prettier</strong></p><ol><li>Install the necessary dependencies:</li></ol><p><em>npm install — save-dev husky eslint prettier eslint-config-prettier lint-staged</em></p><p>2. Initialize Husky and lint-staged:<br><em>npx husky install</em></p><p>3. Add the prepare script to package.json:</p><pre>{<br> &quot;scripts&quot;: {<br> &quot;prepare&quot;: &quot;husky install&quot;,<br> &quot;lint&quot;: &quot;eslint .&quot;,<br> &quot;format&quot;: &quot;prettier - write .&quot;<br> }<br>}</pre><p>4. Create ESLint configuration (.eslintrc.json):</p><pre>{<br> &quot;extends&quot;: [<br> &quot;eslint:recommended&quot;,<br> &quot;prettier&quot;<br> ],<br> &quot;parserOptions&quot;: {<br> &quot;ecmaVersion&quot;: &quot;latest&quot;,<br> &quot;sourceType&quot;: &quot;module&quot;<br> },<br> &quot;rules&quot;: {<br> &quot;no-unused-vars&quot;: &quot;warn&quot;,<br> &quot;no-console&quot;: &quot;warn&quot;<br> }<br>}</pre><p>5. Create Prettier configuration (.prettierrc):</p><pre>{<br> &quot;semi&quot;: true,<br> &quot;singleQuote&quot;: true,<br> &quot;tabWidth&quot;: 2,<br> &quot;trailingComma&quot;: &quot;es5&quot;<br>}</pre><p>6. Configure lint-staged in package.json:</p><pre>{<br> &quot;lint-staged&quot;: {<br> &quot;*.{js,jsx,ts,tsx}&quot;: [<br> &quot;eslint - fix&quot;,<br> &quot;prettier - write&quot;<br> ],<br> &quot;*.{json,md,yml}&quot;: [<br> &quot;prettier - write&quot;<br> ]<br> }<br>}</pre><p>7. Add the pre-commit hook:<br><em>npx husky add .husky/pre-commit “npx lint-staged”</em></p><p><strong>Setting Up Commitlint</strong></p><p>1. Install commitlint:<br><em>npm install — save-dev </em><a href="http://twitter.com/commitlint/cli"><em>@commitlint/cli</em></a><em> </em><a href="http://twitter.com/commitlint/config-conventional"><em>@commitlint/config-conventional</em></a></p><p>2. Create a commitlint configuration file (commitlint.config.js):</p><pre>module.exports = {<br> extends: [&#39;@commitlint/config-conventional&#39;],<br> rules: {<br> &#39;type-enum&#39;: [<br> 2,<br> &#39;always&#39;,<br> [&#39;feat&#39;, &#39;fix&#39;, &#39;docs&#39;, &#39;style&#39;, &#39;refactor&#39;, &#39;test&#39;, &#39;chore&#39;]<br> ],<br> &#39;subject-case&#39;: [2, &#39;always&#39;, &#39;sentence-case&#39;],<br> &#39;subject-max-length&#39;: [2, &#39;always&#39;, 50]<br> }<br>};</pre><p>3. Add the commit-msg hook:<br><em>npx husky add .husky/commit-msg ‘npx — no — commitlint — edit $1’</em></p><p><strong>Setting Up Branch Name Linting</strong></p><p>1. Install the branch name linting package:<br><em>npm install — save-dev branch-name-lint</em></p><p>2. Create a branch naming configuration (branch-name-lint.json):</p><pre>{<br> &quot;pattern&quot;: &quot;^(feature|bugfix|hotfix|release)/.+$&quot;,<br> &quot;errorMsg&quot;: &quot;Branch name must start with feature/, bugfix/, hotfix/, or release/&quot;<br>}</pre><p>3. Add a pre-push hook for branch name validation:<br><em>npx husky add .husky/pre-push ‘npx branch-name-lint — config branch-name-lint.json’</em></p><p><strong>Example Scenarios</strong></p><p>Code Formatting and Linting:</p><pre># Stage files<br>git add .<br># On commit, ESLint and Prettier will automatically run<br>git commit -m &quot;feat: add user authentication&quot;<br># If there are style issues, the commit will fail with error messages<br># Fix the issues manually or run:<br>npm run format</pre><p>Commit Message Validation:</p><pre># Valid commit<br>git commit -m &quot;feat: add new user authentication system&quot;<br># Invalid commit (will be rejected)<br>git commit -m &quot;added some stuff&quot;</pre><p>Branch Name Validation:</p><pre># Valid branch names<br>git checkout -b feature/user-auth<br>git checkout -b bugfix/login-error<br># Invalid branch names (will be rejected on push)<br>git checkout -b new-feature<br>git checkout -b random-branch</pre><p><strong>Tips for Effective Usage</strong></p><p>Want to make the most of your code quality tools? Start with VS Code — just install ESLint and Prettier extensions. Set up format-on-save and make Prettier your default formatter. It’ll save you tons of time fixing code style manually.</p><p>Make sure your team’s on the same page. Write down your coding rules in simple terms and share examples of good commit messages and branch names. A quick guide that everyone can reference works wonders.</p><p>When you’re adding these tools to an existing project, take it slow. Start with basic formatting rules, then gradually add stricter ones as your team gets comfortable. It’s like learning to walk before you run.</p><p>To keep things running smoothly, only check files that have changed using lint-staged. Also, create ignore files to skip checking things like build files or node_modules.</p><p>Sometimes you might need to bypass these checks in emergencies. That’s okay — just use `git commit — no-verify`, but try not to make it a habit.</p><p><strong>Troubleshooting Common Issues</strong></p><p>Running into issues with ESLint and Prettier fighting each other? Make sure you’ve installed eslint-config-prettier to prevent conflicts. If something looks wrong, use `eslint — print-config file.js` to see what rules are actually being used.</p><p>If your hooks are running slowly, first check how many files you’re linting. You might be checking more files than needed. Also, look at your ESLint rules — some can really slow things down. Consider moving bigger checks to when you push code instead of every commit.</p><p>Having trouble with Git hooks not working? First, check if Husky is installed properly — you should see a .husky folder in your project. Make sure the hook files can be executed (you might need to run `chmod +x` on them). If hooks aren’t running at all, check if they’re set up correctly in your Git settings.</p><p>Remember, these tools are here to help, not get in your way. If something’s not working well for your team, it’s okay to adjust the rules until you find what works best.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e48aacf3ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark Web Mysteries]]></title>
            <link>https://medium.com/@dasunichethanadc/dark-web-mysteries-a2e0e8e3c1b?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e0e8e3c1b</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 06:42:56 GMT</pubDate>
            <atom:updated>2023-10-02T06:42:56.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zI48Q3zhyPo_NNtCvKseTg.jpeg" /></figure><p>Welcome to the dark web, an enigmatic corner of the internet where anonymity reigns. Explore its encrypted, ‘.onion’-addressed sites, digital veils, and Bitcoin-based marketplaces. Unravel its complexities, from the allure of anonymity to the concerns of cybersecurity experts and law enforcement, in this revealing journey.</p><p>Introduction to the Dark Web:</p><p>The internet can be divided into three layers, each with its own characteristics and accessibility:</p><ol><li>Surface Web: This is the part of the internet that most people are familiar with. It includes websites that are indexed by search engines like Google and can be accessed using standard web browsers. These websites are publicly visible and easily searchable.</li><li>Deep Web: The deep web refers to web content that is not indexed by traditional search engines. It includes web pages that are password-protected, behind paywalls, or part of databases that search engines can&#39;t crawl. Examples of the deep web include email inboxes, online banking, and private company intranets.</li><li>Dark Web: The dark web is a small, hidden part of the deep web that is intentionally concealed and requires specialized software to access. It is characterized by a high level of anonymity and encryption. Here are some key features of the dark web:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IE_qgZhM1Pdj_8NK1CqyWw.jpeg" /></figure><ul><li><strong>Anonymity:</strong> Users on the dark web often remain anonymous through the use of tools like Tor (The Onion Router), which routes internet traffic through a series of encrypted nodes, making it difficult to trace users&#39; locations or identities.</li><li><strong>Encrypted Communication:</strong> Dark web websites use encryption to secure user data and communications, adding an extra layer of privacy and security.</li><li><strong>Hidden Services: </strong>Websites on the dark web often have addresses that end with &quot;.onion&quot; and are not indexed by search engines. These are known as hidden services and can only be accessed using a Tor-enabled browser.</li><li><strong>Illicit Activities:</strong> While not all content on the dark web is illegal, it has gained notoriety for hosting illegal marketplaces for drugs, weapons, stolen data, and other illicit goods and services.</li><li><strong>Diverse Communities:</strong> The dark web is also home to various forums, chat rooms, and communities discussing a wide range of topics, including privacy, security, and whistleblowing.</li><li><strong>Challenges for Law Enforcement: </strong>Due to its anonymity and encryption, the dark web presents challenges for law enforcement agencies in monitoring and investigating illegal activities.</li></ul><p><strong>Accessing the Dark Web</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ssk5uNzhZfWoIPFBWb_I2Q.png" /></figure><p><strong>Tor (The Onion Router):</strong> Tor is the most widely used tool to access the dark web. It’s a free, open-source software that enables users to browse the internet with a high degree of anonymity. Tor works by routing your connection through a network of volunteer-operated servers, making it extremely difficult for anyone to trace your online activity back to your physical location or identity.<br> <br><strong>Specialized Browsers:</strong> To access .onion websites (unique to the dark web), users need specialized browsers, such as the Tor Browser. These browsers are designed to interface with the Tor network and provide a gateway to .onion sites. They ensure a secure and private connection to the dark web.</p><p><strong>Reasons People Choose to Access the Dark Web:</strong></p><p><em>1. Privacy and Anonymity:</em> One of the primary reasons people access the dark web is to maintain their online privacy and anonymity. This is especially important for activists, journalists, whistleblowers, and individuals living in regions with strict internet censorship.</p><p><em>2. Avoiding Surveillance:</em> Some users turn to the dark web to evade government surveillance or corporate tracking. They believe that the dark web provides a level of protection against intrusive monitoring.</p><p><em>3. Research and Education:</em> Researchers, cybersecurity professionals, and academics use the dark web to study cybersecurity threats, monitor illegal activities, and gain insights into the digital underworld. It serves as a valuable resource for understanding the evolving landscape of cybercrime.</p><p><em>4. Access to Restricted Information:</em> The dark web hosts various forums and communities that share information that may be restricted or censored on the surface web. This includes discussions on sensitive topics, technical knowledge, and even leaked data.</p><p><em>5. Whistleblowing:</em> Whistleblowers often use the dark web to share confidential information securely. Platforms like SecureDrop provide a means for whistleblowers to submit documents and communicate with journalists while preserving their anonymity.</p><p><em>6. Marketplaces:</em> While not all users engage in illegal activities, some visit the dark web to access underground marketplaces where various goods and services are offered. These include drugs, firearms, counterfeit currency, and hacking tools.</p><p><em>7. Curiosity:</em> For some, the allure of the unknown and the desire to explore hidden aspects of the internet drive them to access the dark web out of curiosity. They may not have malicious intentions but are interested in understanding this secretive part of the internet.</p><p>It’s important to note that while the dark web serves legitimate purposes, it also harbors illegal activities. Accessing the dark web can be legally and ethically complex, and users should be aware of the potential risks and legal consequences associated with their activities.</p><p><strong>Content and Activities on the Dark Web</strong></p><p><strong><em>Marketplaces</em></strong>: The dark web hosts a variety of marketplaces where users can buy and sell goods and services. These include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*A8-WnoAEjXqFThpT8eSHCQ.jpeg" /></figure><ol><li><em>Illicit Drugs: Perhaps the most notorious, these marketplaces facilitate the sale of drugs, often with detailed listings, reviews, and user ratings.</em></li><li><em>Stolen Data:</em> <em>Cybercriminals trade in stolen personal information, credit card data, login credentials, and hacked databases.</em></li><li><em>Weapons: Some marketplaces offer firearms, explosives, and other illegal weapons.</em></li><li><em>Counterfeit Goods: Fake passports, driver’s licenses, counterfeit currency, and brand-name knockoffs can be found.</em></li><li><em>Hacking Tools: Malware, hacking services, and tools for conducting cyberattacks are available for purchase.</em></li><li><em>Digital Goods: Stolen software, accounts, and digital products are traded.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhnQAhqaP4Ye1Zjfn2r0iQ.jpeg" /></figure><p><strong><em>Forums and Communities:</em></strong> The dark web hosts various forums and chat rooms, providing a platform for discussions on a wide range of topics, including:</p><ol><li><em>Cybersecurity: Communities focused on hacking, cybersecurity, and sharing knowledge.</em></li><li><em>Whistleblowing: Secure channels for whistleblowers to communicate with journalists or activists.</em></li><li><em>Political and Activist Discussions: Platforms for discussing political activism and sharing controversial content.</em></li><li><em>Privacy and Anonymity: Discussions on digital privacy tools, techniques, and experiences.</em></li></ol><p><strong><em>Hidden Services:</em></strong><em> </em>These are websites with addresses ending in “.onion” and are only accessible through Tor. They can include:</p><ol><li><em>Secure Messaging: Encrypted messaging services that prioritize user privacy.</em></li><li><em>File Sharing: Anonymous file-sharing services for sharing sensitive documents.</em></li><li><em>Censorship Circumvention: Platforms for bypassing internet censorship in repressive regimes.</em></li><li><em>Whistleblower Platforms: SecureDrop, for instance, allows whistleblowers to submit documents to news outlets securely.</em></li></ol><p><strong>Legal and Illegal Aspects:</strong></p><p><strong><em>Legal Aspects:</em></strong></p><ol><li><em>Legitimate Use: While the dark web is often associated with illegal activities, it also serves legitimate purposes. Whistleblowing, privacy advocacy, and research are among these legal uses.</em></li><li><em>Security Research: Cybersecurity professionals may monitor the dark web to study threats and vulnerabilities.</em></li><li><em>Anonymity for At-Risk Users: Some individuals, like activists or journalists in oppressive regimes, rely on the dark web for secure communication.</em></li></ol><p><strong><em>Illegal Aspects:</em></strong></p><ol><li><em>Drug Trade: The sale and distribution of illegal drugs on the dark web are rampant and pose significant health and legal risks.</em></li><li><em>Cybercrime: Hacking services, stolen data, and cyberattack tools contribute to cybercrime on the dark web.</em></li><li><em>Illegal Weapons: Marketplaces offering firearms and explosives violate laws and endanger public safety.</em></li><li><em>Counterfeit Goods: Counterfeiting undermines intellectual property rights and legitimate businesses.</em><br> <br>Understanding the dual nature of the dark web is crucial. While it hosts both legal and illegal activities, law enforcement agencies globally are vigilant in combating cybercrime and illegal markets operating in this hidden digital realm.</li></ol><p><strong>Dark Web Marketplaces:</strong></p><p><strong><em>Prominent Dark Web Marketplaces and Their History:</em></strong></p><ol><li>Silk Road: Founded by Ross Ulbricht in 2011, Silk Road was one of the first and most famous dark web marketplaces. It primarily facilitated the sale of illegal drugs and was seized by law enforcement in 2013.</li><li>AlphaBay: AlphaBay emerged as one of the largest dark web marketplaces after the demise of Silk Road. It offered a wide range of illegal products, including drugs, firearms, hacking tools, and counterfeit items, until it was shut down in 2017.</li><li>Dream Market: Dream Market operated from 2013 to 2019 and was known for hosting a variety of illegal goods and services.</li><li>Empire Market: Empire Market was a prominent successor to AlphaBay and Dream Market until it experienced an exit scam in 2020, where its operators disappeared with users’ funds.</li></ol><p><strong><em>Types of Products Sold on Dark Web Marketplaces:</em></strong></p><ol><li>Illicit Drugs: Dark web marketplaces have been notorious for drug sales, including prescription medications, synthetic drugs, and narcotics.<br>Counterfeit Goods: These platforms offer counterfeit passports, driver’s licenses, credit cards, counterfeit currency, and fake luxury items.</li><li>Hacking Tools and Services: Cybercriminals can buy tools for hacking, such as malware, exploit kits, DDoS services, and stolen data.</li><li>Stolen Data: Dark web marketplaces are hubs for trading stolen personal information, login credentials, and financial data.<br>Firearms and Weapons: Some marketplaces illegally sell firearms, ammunition, explosives, and weapon-related items.</li></ol><p><strong>Anonymity and Security:</strong></p><p><strong><em>Maintaining Anonymity on the Dark Web:</em></strong></p><ol><li>Tor Network: The Tor network, or The Onion Router, is a crucial tool for dark web users. It routes internet traffic through a series of encrypted nodes, making it difficult to trace a user’s location or identity.</li><li>Cryptocurrencies: Transactions on the dark web often use cryptocurrencies like Bitcoin to ensure anonymity.</li><li>VPN Services: While not foolproof, some users also employ VPNs (Virtual Private Networks) in conjunction with Tor for an extra layer of security.</li><li>Encryption: Dark web communication relies heavily on end-to-end encryption, ensuring that messages and data remain private.</li></ol><p><strong><em>Risks and Challenges:</em></strong></p><ol><li>Exit Scams: Users can fall victim to marketplace exit scams where the operators disappear with funds.</li><li>Law Enforcement: While Tor provides anonymity, it doesn’t make users immune to law enforcement action. Dark web users can still face legal consequences.</li><li>Hacking and Phishing: Cybercriminals on the dark web may attempt to hack or phish users, compromising their anonymity and security.<br>Marketplace Reliability: Trusting sellers and maintaining privacy can be challenging on these platforms, given the prevalence of scams.</li></ol><p><strong>Cybersecurity Threats from the Dark Web:</strong></p><ol><li>Stolen Data Trade: Cybercriminals trade stolen data on the dark web, including login credentials, credit card information, and personal details. This data is often used for identity theft, fraud, or sold to other criminals.</li><li>Hacking Tools and Services: Malware, exploit kits, and hacking services are available for purchase. These tools can be used to launch cyberattacks on individuals, businesses, or organizations.</li><li>Distributed Denial of Service (DDoS) Attacks: Dark web forums and marketplaces can offer DDoS-for-hire services, allowing individuals or groups to launch devastating DDoS attacks on websites and services.</li><li>Ransomware: Some ransomware operators negotiate ransom payments and sell decryption keys on the dark web. This fuels the growth of ransomware attacks, which can disrupt businesses and individuals.</li><li>Cybercrime-as-a-Service: The dark web also hosts platforms that offer cybercrime services, allowing less-skilled criminals to access advanced hacking capabilities.</li></ol><p>Understanding these elements of the dark web is crucial for both individuals seeking to protect their online security and law enforcement agencies combating cybercrime. It’s a complex and evolving digital landscape with both legitimate and illicit activities.</p><p>The dark web, a realm of anonymity and complexity, serves both legitimate purposes and illegal activities. Navigating it demands caution, and law enforcement faces ongoing challenges combatting cybercrime.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e0e8e3c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Props: The Secret Sauce Behind React’s Component Magic]]></title>
            <link>https://medium.com/@dasunichethanadc/props-the-secret-sauce-behind-reacts-component-magic-20c7aa2148db?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/20c7aa2148db</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 00:19:06 GMT</pubDate>
            <atom:updated>2023-09-16T00:21:47.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EoxgcZ64-AMUNwAcDBucw.png" /></figure><p>In ReactJS, “props” stands for “properties,” and they are essentially a way to pass data from one component to another. Think of props as a set of instructions or information that a parent component provides to its child components. These instructions are similar in function to HTML attributes.</p><p>Here’s a simplified explanation:</p><p>In React, components are like building blocks for your user interface. Sometimes, you need to customize how these components behave or display content. Props are like messages or data packets you attach to these components to tell them what to do or how to look.</p><p>Props are read-only, meaning that once you set them for a component, you can’t change them directly within that component. This ensures that data flows in a predictable and one-way manner, which is a core concept in React’s design philosophy. Essentially, it helps maintain a clear and organized structure in your application by allowing you to pass data efficiently between different parts of your user interface.</p><p><strong>What’s really happening there? Lets dig in</strong></p><p>Certainly, let’s dive deeper into the concept of props in React and understand what’s happening behind the scenes.</p><p><strong>1. Component Hierarchy</strong>: In a React application, you typically have a hierarchy of components. These components can be thought of as building blocks that make up your user interface. Some components are parent components, while others are child components nested within them.</p><p><strong>2. Data Flow</strong>: React promotes a one-way data flow, which means that data is passed from parent components to child components and not the other way around. This ensures a clear and predictable flow of data through your application.</p><p><strong>3. Props as Messengers</strong>: This is where props come into play. Props are essentially a mechanism for passing data from parent components to child components. They act as messengers who carry information.</p><p><strong>4. Declaration</strong>: When you define a component, you can declare props that it should expect. These declarations provide a contract for what kind of data the component can receive.</p><p>example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*conEpYC41a51iTSPge6jBA.png" /></figure><p>Here, ‘props’ is a parameter that your component function can accept.</p><p><strong>5. Passing Data</strong>: In your parent component, when you use a child component, you can pass data to it by setting attributes on the child component like you would with HTML attributes.</p><p>example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*IyDvKkGYhfvCb2xOsAIcRQ.png" /></figure><p>In this example, we are passing two props to ‘MyComponent’: ‘name’ and ‘age’.</p><p><strong>6. Accessing Props</strong>: Inside the child component, you can access these props via the ‘props’ object that is automatically provided to your component function. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*DZYCpAS92KmdOsJvkN9IWA.png" /></figure><p>Here, we are using `props.name` and `props.age` to display the data passed from the parent component.</p><p>7. Immutable: One critical thing to understand is that props are read-only within the child component. This means you cannot directly modify their values. They are intended to be a source of data for rendering and making decisions within the component.</p><p>8. Reactivity: When the values of props change in the parent component, React will automatically re-render the child components with the updated props. This ensures that your UI stays in sync with the underlying data.</p><p>9. Component Composition: By composing components with props, you can build complex user interfaces by breaking them down into smaller, reusable pieces. Each piece (component) receives the necessary data it needs through props.</p><p>In summary, props in React are a fundamental mechanism for passing data from parent to child components, following a strict one-way data flow. They enable you to build modular and reusable components, making your application easier to manage and maintain. React takes care of efficiently updating your UI when props change, ensuring a responsive and dynamic user experience.</p><p><strong>Use Props in Applications</strong></p><p><strong>1. Passing Data</strong></p><p>One of the most common use cases for props is passing data from a parent component to a child component. You can pass any type of data as props, including strings, numbers, objects, and functions.</p><p>Example:</p><p>In this example, the `name` variable in the `ParentComponent` is passed as a prop to `ChildComponent`, which then displays it.</p><p><strong>2. Using Props in Conditional Rendering</strong></p><p>Props can be used to conditionally render components or elements based on certain conditions.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*lrGiOBttb7xVYQ-2mTdO2w.png" /></figure><p>In this example, the `show` prop is used to conditionally render the `&lt;p&gt;` element based on its value.</p><p><strong>3. Passing Functions as Props</strong></p><p>Props can also be functions. This allows you to pass callbacks from a parent component to a child component, enabling communication between them.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Exizv9WAuaR_rU3i6sHX_w.png" /></figure><p>Here, the `onClick` prop in `ChildComponent` is a function passed from `ParentComponent` and executed when the button is clicked.</p><p><strong>4. Setting Default Props</strong></p><p>You can set default values for props if they are not provided. This ensures that your component works even if some props are missing.</p><p>Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*iLbLYBlD0pRnV6xn7qGTqQ.png" /></figure><p>In this example, if the `name` prop is not provided, it defaults to “Guest.”</p><p><strong>5. Mapping Props to Render Lists</strong></p><p>Props are often used to map data and render lists of components dynamically.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*6-pBj0BHi82zDqnfrQPUVg.png" /></figure><p>Here, the `users` prop is an array of user data, and the component dynamically renders a list of users.</p><p>These are just a few examples of how you can use React props in your applications. Props play a central role in component communication and enable you to create flexible and reusable components in React.</p><p>In the world of React, mastering the art of working with props is essential for building modular, maintainable, and responsive applications. React props not only facilitate data transfer but also form the basis for creating reusable, composable components, unlocking the full potential of React’s component-based development paradigm. So, embrace the power of props in your React journey and watch your user interfaces come to life with dynamic interactivity and efficiency.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20c7aa2148db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the World of IoT: A Beginner’s Guide to the Internet of Things]]></title>
            <link>https://medium.com/@dasunichethanadc/why-iot-d06e9b49283d?source=rss-9e1a40b77d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/d06e9b49283d</guid>
            <dc:creator><![CDATA[Dasuni Wijethilaka]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 06:32:59 GMT</pubDate>
            <atom:updated>2023-08-08T06:33:33.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*T5eOz0voQfFTzVhvP8SMvg.jpeg" /></figure><p>The Internet of Things (IoT) is a super cool tech idea that’s changing how we do stuff. Basically, it’s when regular things like your fridge, lights, and even your alarm clock become smart buddies connected to the internet. This lets them talk to each other and share information. These smart pals can gather data, chat with other gadgets, and even make choices without us telling them what to do.</p><p><strong>IoT is a Big Deal:</strong></p><p>IoT is a big deal because it’s like making our real world and our digital world best friends. This makes life easier and cooler in lots of ways. Your alarm clock is not only waking you up but also telling your coffee maker to get brewing, and your room’s temperature to adjust just right. These things help us out without even asking us.</p><p><strong>Connecting Regular Stuff:</strong></p><p>IoT can make normal stuff smart. We can give phones, watches, fridges, and even cars special parts like sensors and tiny brains that help them understand their surroundings. This means they can collect information, think about it, and then take action.</p><p><strong>Sharing Data and Doing Stuff Automatically:</strong></p><p>These smart gadgets use cloud storage space. All the information they collect goes there. Then, they can learn from it and work together. IoT makes normal things like fridges and lights super smart by letting them talk and work together. IoT is shaping a future where our world is smarter and more helpful with a bunch of mini-genius gadgets assisting us.</p><p><strong>Important Parts of IoT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZvvv03QHAMIbk9d6x04yw.png" /></figure><p>Sensors:</p><p>Sensors are like super tiny detectives that can sense stuff in the world around them, like how hot it is, how bright it is, or if there’s movement. They collect all this information and turn it into data that gadgets can understand. There are different types of sensors for different jobs:</p><ul><li>Temperature Sensors: Smart thermometers tell devices whether it’s hot or cold.</li><li>Humidity Sensors: Able to tell how much moisture is in the air.</li><li>Motion Sensors: These can feel movements.</li><li>Light Sensors: These sensors can tell if it’s dark or sunny.</li></ul><p>Actuators:</p><p>Once sensors gather information, actuators jump into action. They do things based on the data they get.</p><ul><li>Fan Actuators: If the temperature sensor notices that a room is getting too warm, a fan actuator will start and reduce the temperature.</li><li>Motor Actuators: Used in automatic blinds that open and close based on how much light is coming in.</li><li>Valve Actuators: These are used in water systems to can shut off the water if a sensor detects a leak.</li></ul><p>Actuators basically turn digital decisions into real-world actions. They’re like the bridge between a smart idea and actual movement.</p><p><strong>Communication Protocols of IoT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*B0chQePjrgGCkMNhsJnhJA.png" /></figure><ol><li>Wi-Fi: Used for devices that are close to a network. It’s fast and can handle a lot of data.</li><li>Bluetooth: It uses less power, making it great for wearables and small gadgets.</li><li>Zigbee: Zigbee is like a secret code language. It’s low-power and good for connecting lots of devices in a small area, like smart home devices.</li><li>LoRa (Long Range): This is like a messenger that can travel far distances. It’s used for devices spread out over a large area.</li><li>MQTT (Message Queuing Telemetry Transport): MQTT is the mailman of IoT. It’s efficient at delivering small bits of information between devices and servers. This is often used in situations where devices need to send regular updates.</li></ol><p>Choosing the Right Protocol:</p><p>Picking the right communication protocol depends on what you need:</p><ul><li>Range</li><li>Power Consumption</li><li>Data Rate</li></ul><p><strong>Data Collection and Analysis in IoT</strong></p><p>Collecting Data and Sending to the Cloud:</p><p>Sensors as detectives, gathering clues from the world around them. Once they have these clues, they package them up and send them to the cloud.</p><p>Processing Data Closer to Home:</p><p>Sometimes, sending data all the way to the cloud takes time, and in some cases, we need quick decisions. Then we can use edge computing. Instead of sending all the data to the cloud, some processing happens right there on the device. This quick thinking lets devices make decisions faster.</p><p>Turning Data into Insights:</p><p>Smart algorithms dig through the data to find patterns, trends, and useful information. This turning of data into useful information is like turning clues into answers.</p><p><strong>Cloud Computing:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WSVxR3gqByHuULDMlph6lA.png" /></figure><p>The cloud is a smart digital space that can store tons of data and process it really fast. It’s where all the data from different devices comes together, ready to be sorted, analyzed, and used. Cloud computing offers several benefits:</p><ul><li>Storage: The cloud can store vast amounts of data.</li><li>Processing Power: It can process and analyze data from countless devices at once.</li><li>Scalability: As more devices join the IoT, the cloud can handle the load.</li></ul><p>Major Cloud Providers and Their IoT Services:</p><ol><li>Amazon Web Services (AWS)</li><li>Microsoft Azure</li><li>Google Cloud</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcJvvOwKi3ZNg4RFUkebww.jpeg" /></figure><p>These service providers offer cloud platforms tailored for IoT. They provide tools and services that help developers build, manage, and analyze IoT applications. AWS IoT Core helps devices connect securely to the cloud, while Azure IoT offers analytics and machine learning for IoT data.</p><p><strong>Security and Privacy Concerns:</strong></p><p>While IoT brings a world of convenience, it also opens the door to security and privacy challenges. Here’s how the IoT world is working to lock down these issues.</p><p>Security Risks and Challenges:</p><p>IoT devices can sometimes be vulnerable to attacks. Hackers might find weak points to control devices or access data. This could lead to data breaches, privacy invasions, or even manipulating devices for harmful purposes.</p><p>Encryption, Authentication, and Secure Protocols:</p><p>To protect IoT devices, they use tools like encryption, authentication, and secure protocols. It’s like locking up the digital world with a strong key. Encryption scrambles data, making it unreadable without the right key. Authentication ensures only authorized users can access devices. Secure protocols are like secret paths for data, making sure no one finds information while it’s traveling.</p><p>User Privacy and Data Protection:</p><p>User privacy is a top priority in IoT. Device makers work hard to build in privacy features. They give you control over what data is collected and how it’s used.</p><p><strong>Use Cases of IoT:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*HVcT5liXr4X1TNgez3IEjA.jpeg" /></figure><p>1. Smart Homes: Lights that turn on when you enter, thermostats that adjust to your liking, and security cameras that keep an eye on things.</p><p>2. Industrial IoT (IIoT): Factories, farms, and warehouses use IIoT to streamline processes. Sensors monitor machines, helping prevent breakdowns. Farms use IoT to optimize irrigation, and logistics companies use it to track goods in real time, reducing delays.</p><p>3. Healthcare: Wearable devices monitor your heart rate and activity. Doctors can keep tabs on patients remotely, and smart pills can even help track medication intake.</p><p>4. Smart Cities: Sensors monitor traffic, helping reduce congestion. Waste management gets efficient with sensors that notify when bins are full. Smart streetlights adjust brightness based on need, saving energy.</p><p><strong>Challenges and Trends in IoT:</strong></p><p>1. Scalability Challenges: As more devices join the IoT party, managing them becomes complex. Ensuring they communicate smoothly, without overwhelming networks, should be solved carefully.</p><p>2. Environmental Impact: More IoT devices mean more power consumption and electronic waste. Efficient designs, recyclable materials, and responsible disposal are key to minimizing the ecological footprint of IoT.</p><p>3. 5G’s Boost: The rollout of 5G networks brings super-speedy connections. This can mean quicker data transfers and more real-time control for IoT devices.</p><p>4. AI and IoT Duo: Artificial Intelligence (AI) partnering with IoT makes devices smarter. AI analyzes data from sensors to predict patterns or make decisions.</p><p>5. Blockchain Security: Blockchain technology adds layers of security and transparency to IoT. It can verify data authenticity and ensure trust between devices.</p><p>I hope you enjoyed reading this article and it was able to enlighten you a bit about IoT. Thank you.</p><p><em>✍️Blogs by Dasuni</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d06e9b49283d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>