<?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 Amit Singh on Medium]]></title>
        <description><![CDATA[Stories by Amit Singh on Medium]]></description>
        <link>https://medium.com/@amitonline?source=rss-365fae8b62ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6cxZuwRWuFajdoJyrm0ndw.jpeg</url>
            <title>Stories by Amit Singh on Medium</title>
            <link>https://medium.com/@amitonline?source=rss-365fae8b62ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:32:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitonline/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 AI Model Size (Without the Technical Jargon)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@amitonline/understanding-ai-model-size-without-the-technical-jargon-eff395857372?source=rss-365fae8b62ce------2"><img src="https://cdn-images-1.medium.com/max/1024/1*AzVGacHLlBlSKEwTlPop6A.png" width="1024"></a></p><p class="medium-feed-snippet">Artificial Intelligence models can feel complicated, especially when you hear terms like parameters, tokens, or model size. Let&#x2019;s break&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@amitonline/understanding-ai-model-size-without-the-technical-jargon-eff395857372?source=rss-365fae8b62ce------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@amitonline/understanding-ai-model-size-without-the-technical-jargon-eff395857372?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/eff395857372</guid>
            <category><![CDATA[artificail-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tolen]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 15:09:30 GMT</pubDate>
            <atom:updated>2026-03-21T15:11:07.069Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Types of Websites / Web Apps: Choosing the Right Approach]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">When building a website or a web application, one of the first architectural decisions you&#x2019;ll face is how the content will be rendered and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@amitonline/types-of-websites-web-apps-choosing-the-right-approach-d6e28356f1cc?source=rss-365fae8b62ce------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@amitonline/types-of-websites-web-apps-choosing-the-right-approach-d6e28356f1cc?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e28356f1cc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 03:21:15 GMT</pubDate>
            <atom:updated>2025-08-25T03:21:15.610Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding RESTful Architecture: A Comprehensive Guide with Interview Q&A]]></title>
            <link>https://medium.com/@amitonline/understanding-restful-architecture-a-comprehensive-guide-with-interview-q-a-f12c7bb3a708?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/f12c7bb3a708</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 14:48:20 GMT</pubDate>
            <atom:updated>2024-12-02T14:48:20.812Z</atom:updated>
            <content:encoded><![CDATA[<p>RESTful architecture is the cornerstone of modern web services. It provides a scalable, stateless, and efficient way to design and implement APIs, enabling seamless communication between clients and servers. This article explores the principles of RESTful architecture, its benefits, and common interview questions with answers to help you prepare for your next technical interview.</p><h3>What Is RESTful Architecture?</h3><p>REST (Representational State Transfer) is an architectural style for designing networked applications. It was introduced by <strong>Roy Fielding</strong> in his doctoral dissertation in 2000. RESTful services use standard HTTP methods and are based on stateless communication between clients and servers.</p><h3>Key Characteristics of REST:</h3><ol><li><strong>Stateless</strong>: Each request from the client contains all necessary information, ensuring no dependency on previous requests.</li><li><strong>Client-Server</strong>: Separation of concerns between the client (frontend) and server (backend).</li><li><strong>Uniform Interface</strong>: Adherence to a standardized way of interacting with resources using URIs, HTTP methods, and headers.</li><li><strong>Cacheable</strong>: Responses can be marked as cacheable to improve performance.</li><li><strong>Layered System</strong>: Supports intermediaries like proxies for scalability and security.</li><li><strong>Code on Demand (Optional)</strong>: Allows servers to send executable code to clients (e.g., JavaScript).</li></ol><h3>Components of RESTful APIs</h3><p><strong>Resources</strong>: Represented by URIs (Uniform Resource Identifiers). For example, /users represents the collection of users.</p><p><strong>HTTP Methods</strong>: Used to perform actions on resources:</p><ul><li>GET: Retrieve data.</li><li>POST: Create new resources.</li><li>PUT: Update existing resources or create them if they don’t exist.</li><li>DELETE: Remove resources.</li></ul><p><strong>Stateless Communication</strong>: Each API call is independent and must carry all required information (e.g., authentication tokens).</p><p><strong>Representations</strong>: Resources can be represented in various formats like JSON, XML, or plain text.</p><h3>Advantages of RESTful Architecture</h3><ol><li><strong>Scalability</strong>: Stateless nature allows easy scaling of the server.</li><li><strong>Flexibility</strong>: Can use any data format (though JSON is most common).</li><li><strong>Interoperability</strong>: Wide adoption of HTTP makes it compatible across platforms.</li><li><strong>Simplicity</strong>: Intuitive design based on HTTP methods and URIs.</li></ol><h3>Common Interview Questions and Answers on RESTful Architecture</h3><h3>1. What is RESTful architecture?</h3><p><strong>Answer</strong>:<br> RESTful architecture is an architectural style that leverages HTTP protocols to create scalable, stateless, and resource-driven web services. It uses standard HTTP methods, URIs, and status codes for interactions between clients and servers.</p><h3>2. What are the main HTTP methods used in RESTful APIs?</h3><p><strong>Answer</strong>:</p><ul><li><strong>GET</strong>: Fetches data from the server.</li><li><strong>POST</strong>: Creates a new resource.</li><li><strong>PUT</strong>: Updates or creates a resource.</li><li><strong>DELETE</strong>: Removes a resource.</li><li><strong>PATCH</strong>: Updates part of a resource.</li></ul><h3>3. What does it mean for a REST API to be stateless?</h3><p><strong>Answer</strong>:<br> Stateless means that the server does not store any client context between requests. Each request must contain all the necessary information (e.g., authentication tokens, request parameters) for the server to process it.</p><h3>4. What is the difference between PUT and POST?</h3><p><strong>Answer</strong>:</p><ul><li><strong>POST</strong> is used to create a new resource, and the server generates the resource ID.</li><li><strong>PUT</strong> is used to update an existing resource or create a resource with a client-provided ID.</li></ul><h3>5. What are the common status codes used in RESTful APIs?</h3><p><strong>Answer</strong>:</p><ul><li><strong>200 OK</strong>: Request succeeded.</li><li><strong>201 Created</strong>: Resource successfully created.</li><li><strong>400 Bad Request</strong>: Invalid request syntax or parameters.</li><li><strong>401 Unauthorized</strong>: Authentication is required.</li><li><strong>404 Not Found</strong>: Resource not found.</li><li><strong>500 Internal Server Error</strong>: Server-side issue.</li></ul><h3>6. How do you handle versioning in REST APIs?</h3><p><strong>Answer</strong>:</p><ul><li>Include the version in the URL (e.g., /v1/users).</li><li>Use request headers (e.g., Accept: application/vnd.api+json; version=1.0).</li><li>Embed the version in a query parameter (e.g., /users?version=1).</li></ul><h3>7. What is HATEOAS, and how does it relate to REST?</h3><p><strong>Answer</strong>:<br> HATEOAS (Hypermedia as the Engine of Application State) is a constraint of REST where the server provides links to related actions in its responses. It allows clients to discover actions dynamically without hardcoding URLs.</p><h3>8. What tools can you use to test RESTful APIs?</h3><p><strong>Answer</strong>:</p><ul><li><strong>Postman</strong></li><li><strong>cURL</strong></li><li><strong>Insomnia</strong></li><li><strong>Swagger</strong></li><li><strong>JMeter</strong> (for performance testing)</li></ul><h3>9. How can you optimize RESTful APIs for performance?</h3><p><strong>Answer</strong>:</p><ul><li>Use caching (e.g., HTTP caching with ETag or Cache-Control).</li><li>Implement pagination for large datasets.</li><li>Compress responses using gzip.</li><li>Optimize database queries.</li><li>Use asynchronous processing for heavy tasks.</li></ul><h3>10. What are RESTful alternatives, and when would you use them?</h3><p><strong>Answer</strong>:<br> Alternatives include:</p><ul><li><strong>GraphQL</strong>: When clients require specific data with fewer requests.</li><li><strong>gRPC</strong>: For efficient communication in microservices architecture.<br> Use them when REST is less efficient for your use case.</li></ul><h3>Practical Example: A Simple REST API</h3><p>Here’s an example of a REST API built using Node.js and Express:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>app.use(express.json());<br>let users = [{ id: 1, name: &#39;John Doe&#39; }];<br>// GET all users<br>app.get(&#39;/users&#39;, (req, res) =&gt; {<br>  res.json(users);<br>});<br>// POST a new user<br>app.post(&#39;/users&#39;, (req, res) =&gt; {<br>  const newUser = { id: users.length + 1, ...req.body };<br>  users.push(newUser);<br>  res.status(201).json(newUser);<br>});<br><br>// PUT update a user<br>app.put(&#39;/users/:id&#39;, (req, res) =&gt; {<br>  const user = users.find(u =&gt; u.id === parseInt(req.params.id));<br>  if (!user) return res.status(404).send(&#39;User not found&#39;);<br>  Object.assign(user, req.body);<br>  res.json(user);<br>});<br><br>// DELETE a user<br>app.delete(&#39;/users/:id&#39;, (req, res) =&gt; {<br>  users = users.filter(u =&gt; u.id !== parseInt(req.params.id));<br>  res.status(204).send();<br>});<br><br>app.listen(3000, () =&gt; console.log(&#39;Server running on http://localhost:3000&#39;));</pre><h3>Conclusion</h3><p>RESTful architecture remains a vital paradigm for building modern APIs. Its simplicity, scalability, and alignment with web standards make it a preferred choice for developers. Understanding its principles and preparing for common interview questions will help you excel in designing and implementing robust web services.</p><p>Whether you’re building APIs or preparing for an interview, mastering RESTful architecture is a skill worth investing in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f12c7bb3a708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing React Apps for Complex Use Cases: What’s New in React 18]]></title>
            <link>https://medium.com/@amitonline/optimizing-react-apps-for-complex-use-cases-whats-new-in-react-18-e070fc8a08b7?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/e070fc8a08b7</guid>
            <category><![CDATA[react18]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[react-18-new-features]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 08:21:05 GMT</pubDate>
            <atom:updated>2024-12-02T08:21:05.752Z</atom:updated>
            <content:encoded><![CDATA[<p>React has become one of the most popular frameworks for building user interfaces, especially for dynamic, data-intensive web applications. However, as React applications grow more complex, performance optimization becomes a key concern. In this article, we’ll explore some best practices for optimizing React apps in complex use cases, and delve into how React 18 offers new features that make these optimizations more efficient.</p><h3>The Challenges of Complex React Apps</h3><p>When dealing with complex applications — those that have large datasets, real-time updates, or intricate UI structures — performance can suffer. Here are some common challenges you might face:</p><ul><li><strong>Rendering Large Lists:</strong> Rendering hundreds or thousands of items at once can cause performance bottlenecks.</li><li><strong>Frequent Re-renders:</strong> Unnecessary re-renders can impact the responsiveness of your app.</li><li><strong>Complex UI State Management:</strong> Managing complex state transitions can cause issues, especially when multiple components need to react to changes in state.</li><li><strong>Slow Initial Load Times:</strong> Heavy JavaScript bundles or large asset files can make your app slow to load, frustrating users.</li></ul><p>React 18 comes with several new features designed to address these challenges, allowing you to optimize your app more effectively. Let’s explore how React 18 helps tackle these issues.</p><h3>Key React Optimization Strategies for Complex Use Cases</h3><h3>1. Lazy Loading Components</h3><p>One of the simplest and most effective ways to optimize performance is to use <strong>React’s lazy loading</strong> for components that are not needed immediately on page load. This allows React to split the code into smaller bundles, improving the initial load time.</p><pre>import React, { Suspense, lazy } from &#39;react&#39;;<br>const LazyComponent = lazy(() =&gt; import(&#39;./LazyComponent&#39;));function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;LazyComponent /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p>This approach not only reduces the bundle size but also speeds up the app’s first meaningful paint.</p><h3>2. Memoization to Prevent Unnecessary Re-renders</h3><p>React’s useMemo and useCallback hooks are perfect for preventing unnecessary recalculations and re-renders. This is especially useful in complex apps with large data sets or expensive operations.</p><ul><li><strong>useMemo</strong> helps with memoizing the result of a computation so it doesn’t have to be recalculated unless necessary.</li><li><strong>useCallback</strong> is used to memoize functions, preventing them from being recreated on every render.</li></ul><p>Example of useMemo to optimize a filtering operation:</p><pre>const filteredData = useMemo(() =&gt; {<br>  return data.filter(item =&gt; item.isActive);<br>}, [data]);</pre><h3>3. Virtualization for Rendering Large Lists</h3><p>Rendering a long list of items can drastically degrade performance. A technique called <strong>virtualization</strong> renders only the items visible on the screen at any given time, making it ideal for large data sets.</p><p>Libraries like <strong>react-window</strong> or <strong>react-virtualized</strong> are perfect for this task. For example:</p><pre>import { FixedSizeList as List } from &#39;react-window&#39;;function App() {<br>  return (<br>    &lt;List<br>      height={150}<br>      itemCount={1000}<br>      itemSize={35}<br>      width={300}<br>    &gt;<br>      {({ index, style }) =&gt; &lt;div style={style}&gt;{data[index]}&lt;/div&gt;}<br>    &lt;/List&gt;<br>  );<br>}</pre><p>Virtualization ensures that only the items in the viewport are rendered, reducing the load on the DOM.</p><h3>4. Debouncing Input Handling</h3><p>In complex apps, input fields that trigger heavy computations (like live search or filters) can be a performance bottleneck. <strong>Debouncing</strong> the input can delay the triggering of a function until the user has stopped typing, reducing the frequency of the operation.</p><p>Here’s how you can implement debouncing using useEffect and useState:</p><pre>const [query, setQuery] = useState(&#39;&#39;);<br>const [debouncedQuery, setDebouncedQuery] = useState(query);useEffect(() =&gt; {<br>  const timer = setTimeout(() =&gt; setDebouncedQuery(query), 300);<br>  return () =&gt; clearTimeout(timer);<br>}, [query]);// Use debouncedQuery for the actual search operation</pre><h3>5. Code-Splitting and Bundle Optimization</h3><p>React supports <strong>code-splitting</strong> out of the box with React.lazy() and Suspense, but it’s also important to optimize your app’s bundling process. Using tools like <strong>Webpack</strong> or <strong>Vite</strong> can help you minimize the bundle size and split your code efficiently.</p><p>For example, you can dynamically import libraries or components only when needed, which prevents them from being included in the initial bundle.</p><h3>6. Avoiding Re-renders with PureComponent and React.memo</h3><p>In scenarios where a component receives the same props but re-renders unnecessarily, <strong>React.memo</strong> and <strong>PureComponent</strong> can prevent these re-renders by shallowly comparing props. Use React.memo for functional components and PureComponent for class components to optimize rendering.</p><pre>const MemoizedComponent = React.memo(function MyComponent({ data }) {<br>  return &lt;div&gt;{data}&lt;/div&gt;;<br>});</pre><h3>React 18 Features for Optimizing Complex Apps</h3><p>React 18 introduces <strong>Concurrent Rendering</strong> and <strong>Suspense improvements</strong>, which significantly enhance the ability to optimize complex React apps.</p><h3>1. Concurrent Rendering</h3><p>One of the most exciting features of React 18 is <strong>Concurrent Mode</strong>, which allows React to work on multiple tasks at once, making the UI more responsive. React can now pause rendering work and continue it later, which is particularly useful for large, complex apps with many components.</p><ul><li><strong>Rendering can be interrupted and resumed</strong> to ensure the app remains responsive even during complex computations.</li><li>It prioritizes <strong>important updates</strong> (such as user interactions) and delays less critical ones (like data loading), improving the perceived performance.</li></ul><p>To enable Concurrent Mode, you can wrap your app in createRoot:</p><pre>import { createRoot } from &#39;react-dom&#39;;const root = createRoot(document.getElementById(&#39;root&#39;));<br>root.render(&lt;App /&gt;);</pre><h3>2. Automatic Batching</h3><p>React 18 introduces <strong>automatic batching</strong>, where updates made in different event handlers are batched together and applied in a single render. This reduces the number of re-renders and improves performance.</p><p>Previously, React would only batch updates triggered by React events. With React 18, updates from non-React events (like setTimeout or network responses) are also batched, reducing the work the browser has to do.</p><h3>3. Suspense for Data Fetching</h3><p>React 18 improves <strong>Suspense</strong> by making it more powerful and flexible, particularly for handling data fetching. With <strong>Suspense for data fetching</strong>, React can pause the rendering of components until the data is ready, improving user experience by showing loading indicators only when necessary.</p><pre>function MyComponent() {<br>  const data = useAsyncDataFetching();<br>  if (data.status === &#39;loading&#39;) {<br>    return &lt;Loading /&gt;;<br>  }<br>  return &lt;DisplayData data={data} /&gt;;<br>}</pre><p>This is a huge leap forward, especially for complex apps that rely on external APIs and asynchronous data.</p><h3>Conclusion</h3><p>Optimizing React apps for complex use cases involves a combination of strategies like lazy loading, memoization, virtualization, and debouncing. With React 18’s new features such as Concurrent Rendering, automatic batching, and improved Suspense, building high-performance, responsive applications has become easier and more efficient. By leveraging these tools, developers can create faster, more scalable apps that offer a seamless user experience, even as complexity grows.</p><p>React 18 sets a new standard for performance optimization, and adopting these best practices will help ensure your app can handle the demands of modern, data-intensive web applications.</p><p>Keep learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e070fc8a08b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic HTML and React: Building Accessible and Meaningful Interfaces]]></title>
            <link>https://medium.com/@amitonline/semantic-html-and-react-building-accessible-and-meaningful-interfaces-ab8124d198da?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8124d198da</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 05:45:19 GMT</pubDate>
            <atom:updated>2024-11-29T05:54:17.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Accessible environment" src="https://cdn-images-1.medium.com/max/1024/0*sMm_3OiVtVYo0xAb" /></figure><p>In the world of web development, <strong>accessibility</strong> isn’t just a buzzword; it’s a commitment to ensuring that everyone, regardless of ability, can use your website or app effectively. Semantic HTML and React work hand-in-hand to make this commitment achievable. Let’s explore how embracing semantic HTML and leveraging React effectively can result in accessible and meaningful interfaces.</p><h3>What Is Semantic HTML?</h3><p>Semantic HTML uses elements that clearly define their meaning in a way both developers and browsers can understand. For example:</p><ul><li>&lt;header&gt; for page headers.</li><li>&lt;article&gt; for self-contained content.</li><li>&lt;button&gt; for interactive triggers.</li></ul><p>These elements improve readability for both humans and machines, including assistive technologies like screen readers.</p><h3>Why Semantic HTML Matters in React</h3><p>React, by design, is component-based, allowing you to create reusable UI blocks. However, when wrapping everything in &lt;div&gt;s (commonly called <em>div soup</em>), you risk losing semantic meaning. Accessibility tools may struggle to parse the page, leading to a poor experience for users with disabilities.</p><p>By incorporating semantic HTML into your React components, you enhance the experience for:</p><ol><li><strong>Screen reader users:</strong> Providing clear roles and content.</li><li><strong>SEO bots:</strong> Improving content indexing and ranking.</li><li><strong>Everyone else:</strong> Enabling consistent styling and behavior.</li></ol><h3>Semantic Tags in React</h3><p>React’s JSX syntax is a perfect match for semantic HTML. Here’s how to use it effectively:</p><h3>1. Replace &lt;div&gt;s with Meaningful Tags</h3><p>Instead of</p><pre>&lt;div className=&quot;nav&quot;&gt;  <br>  &lt;div className=&quot;nav-item&quot;&gt;Home&lt;/div&gt;  <br>  &lt;div className=&quot;nav-item&quot;&gt;About&lt;/div&gt;  <br>&lt;/div&gt;</pre><p>Use:</p><pre>&lt;nav&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;#home&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;#about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;</pre><h3>2. Leverage &lt;button&gt; Instead of &lt;div&gt; for Actions</h3><p>Buttons inherently convey interactivity and can be focused via keyboard. Avoid this:</p><pre>&lt;div onClick={handleClick}&gt;Click Me&lt;/div&gt;</pre><p>Do this:</p><pre>&lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;</pre><h3>3. Use &lt;section&gt; and &lt;article&gt; Thoughtfully</h3><p>For grouped content:</p><pre>&lt;section&gt;<br>  &lt;header&gt;<br>    &lt;h2&gt;Latest News&lt;/h2&gt;<br>  &lt;/header&gt;<br>  &lt;article&gt;<br>    &lt;h3&gt;Article Title&lt;/h3&gt;<br>    &lt;p&gt;Article content...&lt;/p&gt;<br>  &lt;/article&gt;<br>&lt;/section&gt;</pre><p>This approach provides structure and clarity for assistive technologies.</p><h3>Common Semantic Pitfalls in React</h3><h3>1. Ignoring ARIA Roles When Necessary</h3><p>Semantic HTML covers most use cases, but when building custom components, ARIA roles become essential. For example:</p><pre>const Dropdown = ({ options }) =&gt; (<br>  &lt;div role=&quot;menu&quot;&gt;<br>    {options.map((option) =&gt; (<br>      &lt;div role=&quot;menuitem&quot; tabIndex=&quot;0&quot; key={option.id}&gt;<br>        {option.label}<br>      &lt;/div&gt;<br>    ))}<br>  &lt;/div&gt;<br>);</pre><h3>2. Misusing Headings</h3><p>Headings (&lt;h1&gt; to &lt;h6&gt;) should form a clear hierarchy. Jumping levels confuses screen readers.</p><p>Correct:</p><pre>&lt;h1&gt;Page Title&lt;/h1&gt;   &lt;h2&gt;Section Title&lt;/h2&gt;   &lt;h3&gt;Subsection&lt;/h3&gt;</pre><p>Incorrect:</p><pre>&lt;h1&gt;Page Title&lt;/h1&gt;   &lt;h4&gt;Section Title&lt;/h4&gt;</pre><h3>3. Forgetting Label Association</h3><p>Form elements need explicit labels:</p><pre>&lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;  <br>&lt;input id=&quot;email&quot; type=&quot;email&quot; /&gt;</pre><p>Avoid:</p><pre>&lt;input placeholder=&quot;Email&quot; /&gt;</pre><h3>Building Accessible Components with Semantic Tags</h3><p>Here’s a quick example of an accessible modal component:</p><pre>const Modal = ({ isOpen, title, children, onClose }) =&gt; {<br>  if (!isOpen) return null;  return (<br>    &lt;div role=&quot;dialog&quot; aria-labelledby=&quot;modal-title&quot; aria-hidden={!isOpen}&gt;<br>      &lt;header&gt;<br>        &lt;h2 id=&quot;modal-title&quot;&gt;{title}&lt;/h2&gt;<br>        &lt;button onClick={onClose} aria-label=&quot;Close&quot;&gt;<br>          ✖<br>        &lt;/button&gt;<br>      &lt;/header&gt;<br>      &lt;main&gt;{children}&lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Key Takeaways</h3><ol><li><strong>role=&quot;dialog&quot;</strong> communicates the modal’s purpose.</li><li><strong>aria-labelledby</strong> links the modal to its title.</li><li><strong>aria-hidden</strong> ensures it’s hidden when closed.</li></ol><h3>Testing Your Semantic React App</h3><ul><li><strong>Lighthouse Audit:</strong> Use Chrome DevTools to check accessibility scores.</li><li><strong>Screen Readers:</strong> Test with NVDA, VoiceOver, or JAWS.</li><li><strong>Keyboard Navigation:</strong> Ensure all interactive elements are focusable and operable via keyboard.</li></ul><h3>Final Thoughts</h3><p>Semantic HTML is foundational to building accessible, meaningful interfaces in React. By intentionally choosing semantic tags and integrating accessibility practices, you create applications that work for everyone, including users with disabilities.</p><p>Accessibility isn’t an afterthought — it’s a cornerstone of great web development. As developers, we have the power and responsibility to make the web a more inclusive place.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8124d198da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP status codes]]></title>
            <link>https://medium.com/@amitonline/http-status-codes-ec0960d77215?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0960d77215</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 14:38:20 GMT</pubDate>
            <atom:updated>2024-11-08T14:38:20.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="explainging Http status code" src="https://cdn-images-1.medium.com/max/643/1*MvvcccLuipgpwExuAYgEBg.png" /></figure><p>Imagine you’re a web browser, and you’re trying to talk to a web server to get a webpage. The server sends back a status code as part of its response to tell you how things went. These codes are like short messages that give you a quick update on your request.</p><p>Here’s how they’re organized:</p><ul><li><strong>1xx (Informational):</strong> The request was received, and the server is continuing to process it. You don’t usually see these in your browser.</li><li><strong>2xx (Successful):</strong> Everything went great! The request was successfully received, understood, and accepted.</li><li><strong>200 OK:</strong> This is the most common one. It means the webpage was found and is being sent to you.</li><li><strong>201 Created:</strong> The server successfully created something new, like a new user account.</li><li><strong>3xx (Redirection):</strong> You need to take further action to complete the request. Often, this means you’re being redirected to a different URL.</li><li><strong>301 Moved Permanently:</strong> The page has permanently moved to a new location.</li><li><strong>302 Found (or 307 Temporary Redirect):</strong> The page has temporarily moved.</li><li><strong>4xx (Client Error):</strong> Oops! Something went wrong with your request.</li><li><strong>400 Bad Request:</strong> The server couldn’t understand your request.</li><li><strong>401 Unauthorized:</strong> You need to be logged in to see this page.</li><li><strong>403 Forbidden:</strong> You’re not allowed to access this page, even if you’re logged in.</li><li><strong>404 Not Found:</strong> The page you’re looking for doesn’t exist.</li><li><strong>5xx (Server Error):</strong> The server messed up! This means there’s a problem on the website’s end.</li><li><strong>500 Internal Server Error:</strong> A general error occurred on the server.</li><li><strong>503 Service Unavailable:</strong> The server is temporarily unavailable, maybe because it’s overloaded or down for maintenance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*4dkvZENlvxGSI7Y5HOKj9A.png" /></figure><p><strong>Why are they important</strong></p><ul><li><strong>User Experience:</strong> By understanding status codes, you can design your front-end application to handle errors gracefully. Instead of just showing a blank page or a generic error message, you can provide helpful information to the user and guide them towards a solution. For example, if a user tries to access a page they don’t have permission for (403 Forbidden), you could redirect them to the login page or display a customized message explaining the situation.</li><li><strong>Debugging:</strong> Status codes are crucial for troubleshooting issues in your application. When something goes wrong, checking the status code can give you valuable clues about the source of the problem.</li><li><strong>API Design:</strong> If you’re designing APIs, you’ll need to use status codes correctly to communicate the results of API calls to other developers.</li></ul><p><strong>In Angular or React:</strong></p><p>Both Angular and React have built-in mechanisms for handling HTTP responses, including status codes. You can use these mechanisms to intercept responses, check the status code, and trigger appropriate actions in your application.</p><p>For example, in Angular, you can use the HttpClient module to make HTTP requests. The HttpClient methods return an Observable that emits an HttpResponse object. This object contains the response data as well as the status code. You can then use RxJS operators to handle different status codes.</p><pre>this.http.get(&#39;/api/data&#39;)<br>  .subscribe(<br>    (response: HttpResponse&lt;any&gt;) =&gt; {<br>      if (response.status === 200) {<br>        // Success! Do something with the data.<br>      } else if (response.status === 404) {<br>        // Not found. Show an error message.<br>      }<br>    },<br>    (error) =&gt; {<br>      // Handle errors<br>    }<br>  );</pre><p>Similarly, in React, you can use the fetch API or a library like axios to make HTTP requests. You can then check the status code in the response and update the component&#39;s state accordingly.</p><pre>fetch(&#39;/api/data&#39;)<br>  .then(response =&gt; {<br>    if (response.ok) {<br>      return response.json();<br>    } else if (response.status === 404) {<br>      // Not found. Show an error message.<br>    }<br>  })<br>  .then(data =&gt; {<br>    // Do something with the data<br>  })<br>  .catch(error =&gt; {<br>    // Handle errors<br>  });</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0960d77215" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExplaZero-Shot, One-Shot, and Few-Shot Prompting: A Comprehensive Guide]]></title>
            <link>https://medium.com/@amitonline/zero-shot-one-shot-and-few-shot-prompting-a-comprehensive-guide-2bee8fdc15a3?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bee8fdc15a3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 12:45:43 GMT</pubDate>
            <atom:updated>2024-09-06T12:54:16.240Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding Prompting Techniques</strong></p><p>In the realm of natural language processing, prompting plays a crucial role in guiding models to generate desired outputs. Different prompting techniques cater to varying levels of model understanding and complexity. Let’s delve into three common approaches: zero-shot, one-shot, and few-shot prompting.</p><p><strong>1. Zero-Shot Prompting</strong></p><ul><li><strong>Definition:</strong> This technique involves providing the model with a general instruction or prompt without any specific examples.</li></ul><blockquote><strong>How it works:</strong> The model leverages its existing knowledge and understanding of language to generate a response.</blockquote><p><strong>Example:</strong></p><ul><li><strong>Prompt:</strong> “Translate the sentence ‘Hello, how are you?’ into French.”</li><li><strong>Expected response:</strong> “Bonjour, comment allez-vous?</li></ul><p><strong>2. One-Shot Prompting</strong></p><ul><li><strong>Definition:</strong> In this approach, a single example is provided along with the prompt.</li></ul><blockquote><strong>How it works:</strong> The model learns from the example and applies that knowledge to the new prompt.</blockquote><p><strong>Example:</strong></p><ul><li><strong>Prompt:</strong> “Summarize the following text: The quick brown fox jumps over the lazy dog.”</li></ul><p><strong>Example:</strong> “A fox jumped over a dog.”</p><ul><li><strong>Expected response:</strong> “A fox leaped over a lazy dog.”</li></ul><p><strong>3. Few-Shot Prompting</strong></p><ul><li><strong>Definition:</strong> This technique involves providing multiple examples to the model.</li></ul><blockquote><strong>How it works:</strong> The model identifies patterns and generalizes from the examples.</blockquote><p><strong>Example:</strong></p><ul><li><strong>Prompt:</strong> “Classify the following sentences as positive or negative:</li><li>I love pizza.</li><li>The movie was terrible.</li><li>I am feeling happy today.”</li></ul><p><strong>Examples:</strong></p><ul><li>Positive: “I had a great time at the party.”</li><li>Negative: “The weather is awful.”</li></ul><p><strong>Expected responses:</strong></p><ul><li>Positive: I love pizza.</li><li>Negative: The movie was terrible.</li><li>Positive: I am feeling happy today.</li></ul><p><strong>Choosing the Right Technique</strong></p><p>The choice of prompting technique depends on factors such as the complexity of the task, the model’s capabilities, and the availability of examples. Here are some general guidelines:</p><ul><li><strong>Zero-shot prompting:</strong> Suitable for simple tasks or models with extensive pre-training.</li><li><strong>One-shot prompting:</strong> Effective when a single example can provide sufficient guidance.</li><li><strong>Few-shot prompting:</strong> Useful for more complex tasks or when the model needs to learn from multiple examples.</li></ul><p>By understanding these prompting techniques, you can effectively guide language models to generate high-quality outputs and unlock their full potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PAO7-2y_6aVDyw3_zcrVEw.png" /></figure><p>Keep learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bee8fdc15a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Event Handling: Your Questions Answered]]></title>
            <link>https://medium.com/@amitonline/mastering-javascript-event-handling-your-questions-answered-8d1e31fea37a?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1e31fea37a</guid>
            <category><![CDATA[events]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 06:43:30 GMT</pubDate>
            <atom:updated>2024-08-09T06:43:30.238Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript event handling is a fundamental concept that every web developer should be familiar with. Whether you’re dealing with user interactions or automated tasks, understanding how events work will make you a more effective developer. Let’s dive into the topic through a Q&amp;A format, addressing some common questions.</p><h3>Q1: What is an event in JavaScript?</h3><p><strong>A</strong>: In JavaScript, an event is an action or occurrence recognized by the browser or a script. Events can be triggered by user interactions (like clicks, key presses, or mouse movements), or they can be automatically triggered by the browser (like when a page is loaded).</p><p>For example, clicking a button on a webpage generates a click event.</p><h3>Q2: How do I listen for events in JavaScript?</h3><p><strong>A</strong>: You can listen for events using the addEventListener method. This method attaches an event handler to a specified element, allowing you to define what should happen when the event is triggered.</p><p><strong>Example</strong>:</p><pre>javascriptopy codedocument.getElementById(&quot;myButton&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Button clicked!&quot;);<br>});</pre><p>In this example, when the button with the ID myButton is clicked, an alert box will appear.</p><h3>Q3: What is event bubbling?</h3><p><strong>A</strong>: Event bubbling is a concept where an event starts from the deepest target element and then bubbles up to its parent elements, triggering event handlers on those elements along the way.</p><p><strong>Example</strong>: Consider the following HTML structure:</p><pre>html code&lt;div id=&quot;parent&quot;&gt;<br>    &lt;button id=&quot;child&quot;&gt;Click Me&lt;/button&gt;<br>&lt;/div&gt;</pre><p>If you add event listeners to both the div and the button, and then click the button, the event will first trigger the button&#39;s event handler, and then it will bubble up to trigger the div&#39;s event handler.</p><pre>javascriptpy document.getElementById(&quot;parent&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Div clicked!&quot;);<br>})</pre><pre>document.getElementById(&quot;child&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Button clicked!&quot;);<br>});</pre><p>When the button is clicked, both alerts will be shown because of event bubbling.</p><h3>Q4: Can I stop event bubbling?</h3><p><strong>A</strong>: Yes, you can stop event bubbling using the stopPropagation() method. This prevents the event from bubbling up to parent elements.</p><p><strong>Example</strong>:</p><pre>document.getElementById(&quot;child&quot;).addEventListener(&quot;click&quot;, function(event) {<br>    event.stopPropagation();<br>    alert(&quot;Button clicked!&quot;);<br>});</pre><pre>document.getElementById(&quot;parent&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Div clicked!&quot;);<br>});</pre><p>In this case, only the button’s alert will be shown, because stopPropagation() prevents the event from reaching the div.</p><h3>Q5: What is event capturing, and how is it different from event bubbling?</h3><p><strong>A</strong>: Event capturing is the opposite of event bubbling. Instead of starting from the target element and bubbling up, the event starts from the outermost parent and travels down to the target element.</p><p>By default, JavaScript uses event bubbling, but you can opt for event capturing by setting the third argument of addEventListener to true.</p><p><strong>Example</strong>:</p><pre>document.getElementById(&quot;parent&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Div clicked!&quot;);<br>}, true);</pre><pre>document.getElementById(&quot;child&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Button clicked!&quot;);<br>}, true);</pre><p>With event capturing, the div&#39;s event handler will be triggered before the button&#39;s handler when the button is clicked.</p><h3>Q6: What are some common events in JavaScript?</h3><p><strong>A</strong>: Some common events include:</p><ul><li><strong>click</strong>: Triggered when an element is clicked.</li><li><strong>mouseover</strong>: Triggered when the mouse pointer is moved over an element.</li><li><strong>keydown</strong>: Triggered when a key is pressed down.</li><li><strong>submit</strong>: Triggered when a form is submitted.</li><li><strong>load</strong>: Triggered when the page or an image is fully loaded.</li></ul><p>These events allow you to interact with the user and respond to their actions.</p><h3>Q7: How can I remove an event listener?</h3><p><strong>A</strong>: You can remove an event listener using the removeEventListener method. It&#39;s important to pass the exact same function reference used when adding the listener.</p><p><strong>Example</strong>:</p><pre>javascriptCopy codefunction showAlert() {<br>    alert(&quot;Button clicked!&quot;);<br>}</pre><pre>document.getElementById(&quot;myButton&quot;).addEventListener(&quot;click&quot;, showAlert);<br>// Later in your code<br>document.getElementById(&quot;myButton&quot;).removeEventListener(&quot;click&quot;, showAlert);</pre><p>This removes the click event listener from the button, so the alert will no longer be shown.</p><h3>Q8: What are event delegation and why should I use it?</h3><p><strong>A</strong>: Event delegation is a technique where you use a single event listener to manage similar events for multiple child elements, leveraging event bubbling.</p><p>Instead of attaching individual event listeners to each child element, you attach one to their parent. This is useful for dynamically generated content or when you have many elements that need the same event handler.</p><p><strong>Example</strong>:</p><pre>javascriptCopy codedocument.getElementById(&quot;parent&quot;).addEventListener(&quot;click&quot;, function(event) {<br>    if (event.target &amp;&amp; event.target.nodeName === &quot;BUTTON&quot;) {<br>        alert(&quot;Button clicked: &quot; + event.target.id);<br>    }<br>});</pre><p>Here, a single event listener on the parent element handles clicks for all buttons inside it.</p><h3>Q9: What is the difference between event.target and event.currentTarget?</h3><p><strong>A</strong>:</p><ul><li><strong>event.target</strong>: Refers to the element that triggered the event. It&#39;s the actual element on which the event occurred.</li><li><strong>event.currentTarget</strong>: Refers to the element on which the event listener is attached.</li></ul><p><strong>Example</strong>:</p><pre>javascriptopy codedocument.getElementById(&quot;parent&quot;).addEventListener(&quot;click&quot;, function(event) {<br>    console.log(&quot;event.target: &quot;, event.target); // The clicked element<br>    console.log(&quot;event.currentTarget: &quot;, event.currentTarget); // The parent element<br>});</pre><p>This helps differentiate between where the event happened and where the event listener was placed.</p><h3>Q10: What are synthetic events in React, and how do they relate to JavaScript events?</h3><p><strong>A</strong>: React uses a system called “Synthetic Events” to handle events across all browsers. Synthetic events are cross-browser wrappers around the browser’s native event system, ensuring consistent behavior.</p><p><strong>Example</strong>:</p><pre>javascriptCopy codefunction handleClick(event) {<br>    console.log(&quot;Button clicked&quot;);<br>    event.preventDefault();<br>}</pre><pre>&lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;</pre><p>In this example, onClick is a synthetic event in React. It works similarly to native events but provides additional features and consistency.</p><h3>Conclusion</h3><p>Understanding JavaScript event handling, including concepts like event bubbling and event capturing, is crucial for building interactive and responsive web applications. By mastering these concepts, you can create more efficient, maintainable, and user-friendly applications.</p><p>Feel free to experiment with these examples, and you’ll soon be well on your way to mastering JavaScript events!</p><p><strong>Happy coding!</strong> If you found this article helpful, consider sharing it with your fellow developers and leaving a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1e31fea37a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From TypeScript to Dart: A Beginner’s Guide to State Management with Flutter’s Provider]]></title>
            <link>https://medium.com/@amitonline/from-typescript-to-dart-a-beginners-guide-to-state-management-with-flutter-s-provider-d5254af776fa?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5254af776fa</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 12:56:41 GMT</pubDate>
            <atom:updated>2024-07-16T12:56:41.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Transitioning from TypeScript to Dart can be smooth and rewarding, especially when diving into Flutter for mobile app development. This guide will walk you through the basics of Dart, focusing on state management using the provider package, leveraging your TypeScript knowledge.</p><h3>Basic Syntax and Types</h3><h4>Variables and Types</h4><p>Both Dart and TypeScript are statically typed languages, but Dart syntax has its own nuances.</p><p><strong>TypeScript:</strong></p><pre>let name: string = &#39;John&#39;;<br>const age: number = 30;<br>let isStudent: boolean = true;</pre><p><strong>Dart:</strong></p><pre>String name = &#39;John&#39;;<br>const int age = 30;<br>bool isStudent = true;</pre><ul><li><strong>Type Inference</strong>: Use var in Dart, similar to let in TypeScript.</li><li><strong>Constants</strong>: Dart’s const is a compile-time constant, while final is a runtime constant.</li></ul><h4>Functions</h4><p><strong>TypeScript:</strong></p><pre>function greet(name: string): string {<br>  return `Hello, ${name}`;<br>}</pre><pre>const add = (a: number, b: number): number =&gt; a + b;</pre><p><strong>Dart:</strong></p><pre>String greet(String name) {<br>  return &#39;Hello, $name&#39;;<br>}<br><br>int add(int a, int b) =&gt; a + b;</pre><ul><li><strong>Arrow Functions</strong>: Dart uses =&gt; for concise functions.</li><li><strong>String Interpolation</strong>: Achieved with $ in Dart.</li></ul><h3>Classes and Objects</h3><p>Classes in Dart and TypeScript have similar constructs but different syntax.</p><p><strong>TypeScript:</strong></p><pre>class Person {<br>  name: string;<br>  age: number;<br><br>constructor(name: string, age: number) {<br>    this.name = name;<br>    this.age = age;<br>  }<br>  greet(): string {<br>    return `Hello, my name is ${this.name}`;<br>  }<br>}<br>const john = new Person(&#39;John&#39;, 30);</pre><p><strong>Dart:</strong></p><pre>class Person {<br>  String name;<br>  int age;<br>  Person(this.name, this.age);<br>  String greet() {<br>    return &#39;Hello, my name is $name&#39;;<br>  }<br>}<br>final john = Person(&#39;John&#39;, 30);</pre><ul><li><strong>Constructors</strong>: Defined directly with this for parameter assignment in Dart.</li><li><strong>Instantiation</strong>: No new keyword needed.</li></ul><h3>Asynchronous Programming</h3><p>Handling asynchronous code is straightforward with Dart’s Future, similar to TypeScript&#39;s Promise.</p><p><strong>TypeScript:</strong></p><pre>async function fetchData(): Promise&lt;string&gt; {<br>  const response = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await response.json();<br>  return data;<br>}</pre><p><strong>Dart:</strong></p><pre>Future&lt;String&gt; fetchData() async {<br>  final response = await http.get(Uri.parse(&#39;https://api.example.com/data&#39;));<br>  final data = jsonDecode(response.body);<br>  return data;<br>}</pre><ul><li><strong>Future</strong>: Dart’s equivalent of Promise.</li><li><strong>Async/Await</strong>: Same syntax as TypeScript.</li></ul><h3>Error Handling</h3><p>Dart’s error handling is similar to TypeScript’s try-catch.</p><p><strong>TypeScript:</strong></p><pre>try {<br>  // some code that might throw an error<br>} catch (error) {<br>  console.error(error);<br>} finally {<br>  // cleanup code<br>}</pre><p><strong>Dart:</strong></p><pre>try {<br>  // some code that might throw an error<br>} catch (e) {<br>  print(e);<br>} finally {<br>  // cleanup code<br>}</pre><ul><li><strong>Specific Exceptions</strong>: Use on to catch specific exceptions in Dart.</li></ul><h3>Collections</h3><p>Dart’s collection types are similar to TypeScript’s arrays and lists.</p><p><strong>TypeScript:</strong></p><pre>let numbers: number[] = [1, 2, 3];<br>numbers.push(4);<br>let names: Array&lt;string&gt; = [&#39;Alice&#39;, &#39;Bob&#39;];</pre><p><strong>Dart:</strong></p><pre>List&lt;int&gt; numbers = [1, 2, 3];<br>numbers.add(4);<br>List&lt;String&gt; names = [&#39;Alice&#39;, &#39;Bob&#39;];</pre><ul><li><strong>List</strong>: Equivalent to arrays in TypeScript.</li><li><strong>Add Elements</strong>: Use add in Dart.</li></ul><h3>Null Safety</h3><p>Dart’s null safety helps prevent null reference errors by distinguishing nullable and non-nullable types.</p><p><strong>TypeScript:</strong></p><pre>let name: string | null = null;</pre><p><strong>Dart:</strong></p><pre>String? name = null;<br></pre><ul><li><strong>Nullable Types</strong>: Use ? to indicate nullable types.</li><li><strong>Non-null Assertion</strong>: Use ! to assert non-null values.</li></ul><h3>Using Provider in Dart</h3><p>Now, let’s implement state management in Dart using the provider package.</p><h4>Step 1: Add the Provider Dependency</h4><p>Add provider to your pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  provider: ^6.0.0</pre><p>Run flutter pub get to install the package.</p><h4>Step 2: Create a ChangeNotifier Class</h4><p>Define a state management class using ChangeNotifier.</p><p><strong>TypeScript:</strong></p><pre>class Counter {<br>  private count: number = 0;<br>  getCount(): number {<br>    return this.count;<br>  }<br>  increment(): void {<br>    this.count++;<br>  }<br>}</pre><p><strong>Dart:</strong></p><pre>import &#39;package:flutter/foundation.dart&#39;;<br><br>class Counter with ChangeNotifier {<br>  int _count = 0;<br>  int get count =&gt; _count;<br>  void increment() {<br>    _count++;<br>    notifyListeners();<br>  }<br>}</pre><ul><li><strong>ChangeNotifier</strong>: Enables the class to notify listeners about state changes.</li></ul><h4>Step 3: Provide the ChangeNotifier</h4><p>Wrap your app with ChangeNotifierProvider.</p><p><strong>TypeScript:</strong></p><pre>// No direct equivalent in plain Type</pre><p><strong>Dart:</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br>import &#39;counter.dart&#39;;  // Your ChangeNotifier class<br><br>void main() {<br>  runApp(<br>    ChangeNotifierProvider(<br>      create: (context) =&gt; Counter(),<br>      child: MyApp(),<br>    ),<br>  );<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: CounterScreen(),<br>    );<br>  }<br>}</pre><h4>Step 4: Consume the ChangeNotifier</h4><p>Access and interact with the state using Consumer or Provider.of.</p><p><strong>TypeScript:</strong></p><pre>// No direct equivalent in plain TypeScript</pre><p><strong>Dart:</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br>import &#39;counter.dart&#39;;<br><br>class CounterScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Provider Example&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(&#39;You have pushed the button this many times:&#39;),<br>            Consumer&lt;Counter&gt;(<br>              builder: (context, counter, child) {<br>                return Text(<br>                  &#39;${counter.count}&#39;,<br>                  style: Theme.of(context).textTheme.headline4,<br>                );<br>              },<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          Provider.of&lt;Counter&gt;(context, listen: false).increment();<br>        },<br>        tooltip: &#39;Increment&#39;,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Consumer</strong>: Rebuilds its child widget when the state changes.</li><li><strong>Provider.of</strong>: Accesses the state for actions without rebuilding the widget.</li></ul><h3>Conclusion</h3><p>Transitioning from TypeScript to Dart is seamless with many familiar concepts. By understanding Dart’s syntax and leveraging the provider package, you can manage state efficiently in your Flutter applications. Dive in and start building amazing Flutter apps with confidence!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5254af776fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Machine Learning Algorithms: KNN, K-Means, Regression, and Naive Bayes Using a Car…]]></title>
            <link>https://medium.com/@amitonline/understanding-machine-learning-algorithms-knn-k-means-regression-and-naive-bayes-using-a-car-30e3896ecf88?source=rss-365fae8b62ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e3896ecf88</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 15:18:08 GMT</pubDate>
            <atom:updated>2024-06-24T15:18:08.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Machine Learning Algorithms: KNN, K-Means, Regression, and Naive Bayes Using a Car Showroom Example</h3><p>In the rapidly evolving world of machine learning, understanding different algorithms and their applications can seem daunting. However, using familiar examples can make these concepts more accessible. Let’s dive into four popular machine learning algorithms — K-Nearest Neighbors (KNN), K-Means clustering, Regression, and Naive Bayes — through the lens of a car showroom.</p><h4>K-Nearest Neighbors (KNN): Classifying New Cars</h4><p><strong>Scenario</strong>: Imagine you work at a car showroom, and you want to classify new cars into categories like Sedan, SUV, and Hatchback based on their features.</p><p><strong>How It Works</strong>:</p><ol><li><strong>Training Data</strong>: You have a dataset of cars with known categories and features such as engine size, fuel type, and number of doors.</li><li><strong>New Car</strong>: A new car arrives at the showroom. You measure its features.</li><li><strong>Finding Neighbors</strong>: KNN algorithm compares the new car’s features with those in your dataset, calculating the distance (e.g., Euclidean distance) to each known car.</li><li><strong>Classifying</strong>: If you use K=5, KNN finds the 5 nearest cars in the dataset. If 3 out of these 5 cars are SUVs, the new car is classified as an SUV.</li></ol><p><strong>Application</strong>: KNN is highly intuitive and works well when you have a well-labeled dataset and want to classify new items based on similarity to known items.</p><h4>K-Means Clustering: Grouping Cars into Clusters</h4><p><strong>Scenario</strong>: The showroom wants to group cars into clusters based on similarities for better inventory management and marketing.</p><p><strong>How It Works</strong>:</p><ol><li><strong>Initialization</strong>: The algorithm starts by placing K random centroids in the feature space (e.g., K=3 for three clusters).</li><li><strong>Assignment</strong>: Each car is assigned to the nearest centroid based on features like price, engine size, and fuel efficiency.</li><li><strong>Update Centroids</strong>: The centroids are recalculated by finding the mean position of all cars in each cluster.</li><li><strong>Iteration</strong>: Steps 2 and 3 are repeated until the centroids stabilize, meaning the cars in each cluster don’t change significantly.</li></ol><p><strong>Application</strong>: K-Means clustering helps in segmenting the cars into meaningful clusters, such as budget, mid-range, and luxury vehicles, based on their features. This can optimize inventory and target marketing strategies.</p><h4>Regression: Predicting Car Prices</h4><p><strong>Scenario</strong>: You want to predict the price of a car based on its features.</p><p><strong>How It Works</strong>:</p><ol><li><strong>Training Data</strong>: You collect data on car prices and their features (e.g., engine size, age, mileage).</li><li><strong>Model Building</strong>: You use this data to build a regression model that describes the relationship between the car’s features and its price.</li><li><strong>Prediction</strong>: When a new car arrives, you input its features into the regression model to predict its price.</li></ol><p><strong>Example</strong>: Linear regression might fit a line to the data points representing the relationship between car age and price. The model then uses this line to predict the price of new cars based on their age.</p><p><strong>Application</strong>: Regression is essential for pricing strategies, helping the showroom set competitive prices based on a car’s features.</p><h4>Naive Bayes: Classifying Car Types</h4><p><strong>Scenario</strong>: You want to classify cars into categories like Economy, Mid-range, and Luxury based on their features.</p><p><strong>How It Works</strong>:</p><ol><li><strong>Training Data</strong>: You have a dataset of cars with known categories and features like fuel efficiency, engine size, and interior quality.</li><li><strong>Feature Independence</strong>: Naive Bayes assumes that each feature independently contributes to the probability of a car belonging to a certain category.</li><li><strong>Calculating Probabilities</strong>: For a new car, Naive Bayes calculates the probability of it being in each category based on its features.</li><li><strong>Classifying</strong>: The car is classified into the category with the highest probability.</li></ol><p><strong>Application</strong>: Despite its simplifying assumption of feature independence, Naive Bayes is effective for quick and reliable classification, especially when you need to categorize a large number of cars efficiently.</p><h3>Conclusion</h3><p>In a car showroom, leveraging machine learning algorithms can greatly enhance operations, from classifying new arrivals and predicting prices to segmenting inventory and understanding customer preferences. Here’s a quick recap:</p><ul><li><strong>KNN</strong>: Ideal for classifying new cars based on similarity to known cars.</li><li><strong>K-Means Clustering</strong>: Perfect for grouping cars into clusters for better inventory management.</li><li><strong>Regression</strong>: Essential for predicting car prices based on various features.</li><li><strong>Naive Bayes</strong>: Efficient for categorizing cars into predefined types using probability.</li></ul><p>Understanding and applying these algorithms can transform your car showroom into a data-driven, efficient, and customer-focused enterprise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e3896ecf88" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>