<?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 Kaushik K on Medium]]></title>
        <description><![CDATA[Stories by Kaushik K on Medium]]></description>
        <link>https://medium.com/@13kaushik.k?source=rss-9b52cf17847f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QkJcJvhUE7XbtIVJHJEXFw.jpeg</url>
            <title>Stories by Kaushik K on Medium</title>
            <link>https://medium.com/@13kaushik.k?source=rss-9b52cf17847f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:45:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@13kaushik.k/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[How Amazon Pay Detects and Recovers from Downtime Across Global Processors; My Notes from AWS…]]></title>
            <link>https://medium.com/@13kaushik.k/how-amazon-pay-detects-and-recovers-from-downtime-across-global-processors-my-notes-from-aws-d11fbbf2952d?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d11fbbf2952d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 10:10:15 GMT</pubDate>
            <atom:updated>2026-04-28T10:10:15.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Amazon Pay Detects and Recovers from Downtime Across Global Processors; My Notes from AWS Summit Bengaluru 2026</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZxwAOPq_bKlfBqj8wXGZQ.png" /></figure><p>I recently attended <strong>AWS Summit Bengaluru 2026</strong>, and one of the standout sessions was <strong>ANT101 — “How Amazon Pay Detects and Recovers from Downtime Across Global Processors”</strong></p><p>In 30 minutes, they walked through how Amazon Pay built a fully automated system to detect payment processor failures, suppress broken traffic, route around outages, and recover. All without human intervention. Here’s what I took away.</p><h3>The Problem</h3><p>Amazon Pay works with multiple payment processors and banks worldwide. When one of those processors goes down, even partially it can tank the success rate for thousands of transactions. The challenge: how do you detect that quickly, act on it without killing good traffic, and recover automatically when the outage resolves?</p><h3>The Architecture: Three Layers</h3><p>The system is organized into three clean layers:</p><p><strong>1. Ingestion: </strong>Every transaction emits a rich event: transaction ID, payment method, bank, processor, network, error codes, latency, and more. These flow through SNS → SQS → Lambda → Kinesis Data Streams, landing as standardized events in Kinesis within seconds.</p><p><strong>2. Processing &amp; Detection: </strong>This is where it gets interesting. They originally built a V1 pipeline using Amazon OpenSearch Service with a Health Scoring Lambda. But they evolved to a <strong>V2 pipeline using Amazon Managed Service for Apache Flink</strong>, which gave them sub-second per-record latency, stateful processing with windows and aggregations, and exactly-once semantics via built-in checkpointing. The Flink pipeline feeds a Suppression Rule Evaluator that checks rules stored in DynamoDB, and pushes actions to an SQS action queue.</p><p><strong>3. Action: </strong>A Decision Engine (Lambda) receives confirmed anomalies and asks one question: <em>“Can I route around this?”</em> If yes, it updates the Routing Tree. If no, it writes to the Suppression DB. Either way, Amazon SNS fires alerts.</p><h3>How They Catch Failures</h3><p>Two key design decisions stood out:</p><p><strong>Sliding sampling windows of 1–2 minutes.</strong> They tried ~30-second windows and got too many false positives. They tried 5-minute windows and customers were already failing by the time suppression kicked in. The 1–2 minute sweet spot balances speed with stability.</p><p><strong>Multi-dimensional monitoring.</strong> Success rate isn’t just tracked globally. It’s calculated independently across combinations of payment method, processor, bank, network, and more. Configurable thresholds mean high-volume dimensions get tighter bounds, while low-volume ones get wider bounds. A minimum volume gate prevents false positives on thin slices.</p><h3>Two Levels of Suppression</h3><p>Not all failures are equal, so there are two responses:</p><p><strong>Soft Suppression</strong> is the first line of defense. The payment instrument is still available but flagged, customers see a warning, it’s not recommended, but they can still attempt the transaction. Higher threshold to trigger.</p><p><strong>Hard Suppression</strong> is for severe degradations. The instrument is greyed out entirely, customers can’t select it, it’s removed from recommendations, and a message explains why. Lower threshold to trigger.</p><h3>Dynamic Routing: The Invisible Fix</h3><p>When redundancy exists (i.e., another processor can handle the same transaction type), the system re-routes traffic automatically. Processor A is down? Shift to Processor B. The customer never knows.</p><p>When there’s no redundancy, suppression kicks in and the customer is informed.</p><h3>The 95/5 Canary Model: Automated Recovery</h3><p>This was probably my favorite part of the talk. Recovery is fully automated using a canary approach:</p><ol><li><strong>Normal state</strong>: 100% traffic flowing.</li><li><strong>Anomaly detected</strong>: Success rate drops.</li><li><strong>Suppress</strong>: Traffic split ~95% suppressed / 5% canary.</li><li><strong>Canary recovers</strong>: The 5% canary traffic shows the success rate is back.</li><li><strong>Auto unsuppress</strong>: Full traffic restored.</li></ol><p>The beauty of this is that outages resolve at any time 2 AM, holidays, weekends. Without the canary, a human would have to manually verify and unsuppress. With it, the entire cycle from detection → suppression → canary → recovery → unsuppression is fully automated, end to end.</p><h3>Why Flink Over Lambda?</h3><p>They shared a comparison that made the V1 → V2 migration rationale clear. Apache Flink offers sub-second latency, stateful windowed processing, and exactly-once guarantees out of the box. Lambda is stateless per invocation with seconds-level latency and requires idempotent writes to achieve similar guarantees. For a system that needs to maintain real-time sliding windows and aggregations across high-cardinality dimensions, Flink was the clear winner.</p><h3>Why Kinesis Over MSK?</h3><p>Amazon Pay chose Kinesis Data Streams for its serverless-native model and instant scaling in on-demand mode. For their use case: unpredictable, bursty payment traffic, the per-shard-hour pricing and low latency (~70ms with Enhanced Fan-Out) made more sense than MSK’s broker-instance model.</p><h3>Key Takeaways</h3><ol><li><strong>Tune for false positives, not just speed.</strong> A false suppression kills good traffic. The 2-minute window with configurable thresholds prioritizes precision.</li><li><strong>Granularity matters.</strong> Monitoring at the level of bank × processor × method with multi-level aggregation reduces blast radius. Only suppress what’s actually broken.</li><li><strong>Automate the full cycle, including recovery.</strong> The canary is non-negotiable and was one of the most important changes they made.</li><li><strong>Design for the entire spectrum of failures.</strong> Not just catastrophe, partial degradations, single-processor issues, and everything in between.</li></ol><p>If you’re building payment systems or any high-availability platform that depends on third-party providers, this pattern of detect → suppress/route → canary-recover is worth studying.</p><p>#AWSSummit #AWSSummitBengaluru2026 #AmazonPay #Payments #SystemDesign #ApacheFlink #Kinesis #DynamoDB #Resilience #AWS #DistributedSystems</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d11fbbf2952d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Stopped Claude Code From Breaking My Architecture -Here’s Exactly How]]></title>
            <link>https://medium.com/@13kaushik.k/i-stopped-claude-code-from-breaking-my-architecture-heres-exactly-how-60dd53ed00ca?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dd53ed00ca</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 14:51:42 GMT</pubDate>
            <atom:updated>2026-04-14T14:58:43.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv-dVRMtiA0Uia-vdxSzJQ.jpeg" /></figure><p>Last week I asked Claude Code a simple question:</p><blockquote>“Write me a FastAPI route that fetches all users from the database.”</blockquote><p>It generated this:</p><pre>from fastapi import APIRouter, Depends<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from sqlalchemy import select<br>from .database import get_db<br>from .models import User<br><br>router = APIRouter()<br><br>@router.get(&quot;/users&quot;)<br>async def get_users(db: AsyncSession = Depends(get_db)):<br>    result = await db.execute(select(User))<br>    return result.scalars().all()</pre><p>Clean code. Correct syntax. Perfectly typed.</p><p>And a direct violation of my architecture.</p><h3>The rule it broke</h3><p>My project enforces a strict layered architecture: routes can only talk to services, services talk to repositories, repositories talk to the database. SQLAlchemy never appears in a route file. Ever.</p><p>I had this rule written down in .arklint.yml:</p><pre>- id: no-direct-db-in-routes<br>  type: boundary<br>  description: &quot;API routes must not import database modules directly&quot;<br>  source: &quot;routes/**&quot;<br>  blocked_imports:<br>    - &quot;sqlalchemy&quot;<br>    - &quot;psycopg2&quot;<br>    - &quot;pymongo&quot;<br>  severity: error<br><br>- id: layered-architecture<br>  type: layer-boundary<br>  description: &quot;Enforce routes → services → repositories direction&quot;<br>  layers:<br>    - name: routes<br>      path: &quot;routes/**&quot;<br>    - name: services<br>      path: &quot;services/**&quot;<br>    - name: repositories<br>      path: &quot;repositories/**&quot;<br>  allowed_dependencies:<br>    routes:<br>      - services<br>    services:<br>      - repositories<br>    repositories: []<br>  severity: error</pre><p>Claude Code didn’t know any of this existed. So it did what made sense without that context -put the database access in the route.</p><h3>Setting it up yourself</h3><p>You can reproduce this in about 10 minutes. Here’s exactly what I did.</p><p><strong>Install Arklint:</strong></p><pre>pip install arklint<br># or: npm install -g arklint<br># or: dotnet tool install -g arklint</pre><p><strong>Create a test project with the right folder structure:</strong></p><pre>mkdir -p my-project/routes my-project/services my-project/repositories<br>cd my-project</pre><p><strong>Generate a starter </strong><strong>.arklint.yml tailored to your stack:</strong></p><pre>arklint init</pre><p>Arklint detects your project type automatically — package.json gives you Node/TypeScript rules, *.csproj gives you .NET rules, pyproject.toml gives you Python rules. Edit the generated file to match your actual architecture.</p><p><strong>Verify it works:</strong></p><pre>arklint check</pre><h3>Why MCP alone isn’t enough</h3><p>I’d already added Arklint’s MCP server to Claude Code:</p><pre>claude mcp add arklint -- arklint mcp --config /path/to/.arklint.yml</pre><p>The MCP server exposes four tools to AI agents:</p><ul><li>list_rules — what rules are in force</li><li>get_rule_details — full config of a specific rule</li><li>check_file — validate an existing file</li><li>check_snippet — validate a code snippet <strong>before writing it to disk</strong></li></ul><p>That last one is the important one. Claude Code can call check_snippet with generated code and get back a list of violations before the file ever lands in your project.</p><p>But here’s what I learned: <strong>having the tools available isn’t enough.</strong> Claude Code doesn’t automatically reach for check_snippet before writing code. It needs to be told to.</p><p>I opened the project in Claude Code:</p><pre>claude .</pre><p>And asked:</p><blockquote>“Write me a FastAPI route that fetches all users from the database.”</blockquote><p>It still violated the rule. Same sqlalchemy import in the route. The MCP server was running — Claude Code just didn&#39;t know it was supposed to use it first.</p><h3>The missing piece: arklint export</h3><p>One command fixed everything:</p><pre>arklint export --format claude</pre><p>This writes a CLAUDE.md into your project root with explicit instructions for Claude Code — telling it to call check_snippet via the MCP server before writing any file, and listing every architectural rule it needs to respect.</p><p>Then I asked the exact same question again.</p><p>This time Claude Code responded:</p><blockquote>“Following the architectural rules in your CLAUDE.md, routes can’t import DB modules directly and must go through the routes → services → repositories layers.”</blockquote><p>And generated this instead:</p><pre># routes/users.py<br>from fastapi import APIRouter, Depends<br>from services.user_service import UserService<br><br>router = APIRouter()<br><br>@router.get(&quot;/users&quot;)<br>async def get_users(service: UserService = Depends()):<br>    return await service.get_all_users()<br><br># services/user_service.py<br>from repositories.user_repository import UserRepository<br><br>class UserService:<br>    def __init__(self, repo: UserRepository = Depends()):<br>        self.repo = repo<br><br>    async def get_all_users(self):<br>        return await self.repo.find_all()</pre><pre># repositories/user_repository.py<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from sqlalchemy import select<br>from db.session import get_db<br>from models.user import User<br><br>class UserRepository:<br>    def __init__(self, db: AsyncSession = Depends(get_db)):<br>        self.db = db<br>    <br>    async def find_all(self):<br>        result = await self.db.execute(select(User))<br>        return result.scalars().all()</pre><p>SQLAlchemy is in repositories/ where it belongs. The route only knows about the service. Claude even cited which rules it was following.</p><p><strong>Same prompt. Completely different output.</strong></p><h3>The complete setup: start to finish</h3><pre># 1. Install<br>pip install arklint<br><br># 2. Create your project structure<br>mkdir -p my-project/routes my-project/services my-project/repositories<br>cd my-project<br><br># 3. Generate .arklint.yml for your stack<br>arklint init<br><br># 4. Add MCP server to Claude Code<br>claude mcp add arklint -- arklint mcp --config $(pwd)/.arklint.yml<br><br># 5. Export rules into CLAUDE.md<br>arklint export --format claude<br><br># 6. Open in Claude Code<br>claude .</pre><p>From this point, every time Claude Code writes a file it checks against your architectural rules first.</p><h3>What this actually means</h3><p>AI coding tools are not going away. The question isn’t whether to use them, it’s whether the code they generate respects the structure you’ve spent time designing.</p><p>The answer used to be: it doesn’t, and you find out in code review.</p><p>Now there’s a better answer: give the AI your rules before it writes a single line.</p><p>Arklint is open source: <a href="https://github.com/Kaushik13k/arklint"><strong>github.com/Kaushik13k/arklint</strong></a></p><p>Full docs at<a href="https://arklint.elevane.org/"> https://arklint.elevane.org/</a></p><p><em>#AI #Python #FastAPI #SoftwareArchitecture #ClaudeCode</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dd53ed00ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Got Tired of AI-Generated Code Breaking My Architecture. So I Built Arklint]]></title>
            <link>https://medium.com/@13kaushik.k/i-got-tired-of-ai-generated-code-breaking-my-architecture-so-i-built-arklint-62c42200093c?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/62c42200093c</guid>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 14:02:05 GMT</pubDate>
            <atom:updated>2026-03-30T14:10:00.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzOvLSM354j-ki8Fml-GTw.jpeg" /></figure><p>We agree on an architecture. We write it down somewhere. A Notion doc, a README, a Slack message that everyone reacts to with 🙌 and then never reads again.</p><p>Three months later, a route handler is hitting the database directly. A utility file is importing from a domain model. A new HTTP library nobody approved quietly snuck in via a pull request. The architecture still exists in the doc. In production, it’s already gone.</p><p>We’ve been here more times than I’d like to admit. And then AI coding tools made it worse.</p><h3>The Problem Got Worse With AI</h3><p>GitHub Copilot, Cursor, Claude Code they generate syntactically correct, well-typed, beautifully formatted code that violates your architecture constantly. Not because the AI is careless. Because the AI has no idea your architecture exists.</p><p>It doesn’t know routes aren’t supposed to touch the database. It doesn’t know you banned requests in favour of httpx. It doesn&#39;t know your service layer is supposed to be the only thing talking to external APIs. It just generates what looks right and what looks right is often what exists elsewhere in the codebase, violations included.</p><h3>What I Tried First</h3><p>Before building anything, I looked at what existed.</p><p><strong>Dependency Cruiser</strong> is powerful but JavaScript-only and primarily focused on import graphs rather than architectural rules. It’s a great visualisation tool but not a rule enforcement layer.</p><p><strong>ArchUnit</strong> is excellent if you’re on Java. No Python, no Node.js, no cross-language support.</p><p><strong>Custom ESLint/flake8 plugins</strong> work, but they require every team to write and maintain their own plugin per rule. There’s no shared format, no AI integration, and no way to export rules into AI instruction files.</p><p><strong>Pre-commit hooks with grep</strong> I tried this. It works until someone needs a legitimate exception, and then you’re maintaining a growing list of # noqa equivalents with no structure.</p><p>None of these gave me what I wanted: a single YAML file that defines the architecture, enforced automatically, across languages, with AI awareness built in.</p><p>So I built Arklint.</p><h3>What Arklint Does</h3><p>Arklint lets you define your architectural rules in a single .arklint.yml file and enforce them automatically in local development, pre-commit hooks, and CI pipelines.</p><p>Here’s what a real config looks like:</p><pre>rules:<br>  - id: no-direct-db-in-routes<br>    type: boundary<br>    description: Route handlers must not import database modules directly<br>    from_modules: [&quot;routes&quot;]<br>    banned_imports: [&quot;db&quot;, &quot;models&quot;]<br>    severity: error<br><br>  - id: use-httpx-not-requests<br>    type: dependency<br>    description: Use httpx instead of requests<br>    banned: [&quot;requests&quot;]<br>    severity: warning<br><br>  - id: no-sql-in-routes<br>    type: pattern-ban<br>    description: No raw SQL queries in route handlers<br>    pattern: &#39;execute\(&#39;<br>    directory: routes/<br>    severity: error</pre><p>Run arklint check and you get:</p><pre>Arklint v0.6.0 — Scanning 142 files against 5 rules...<br>  ✗ FAIL  no-direct-db-in-routes<br>          routes/orders.py:14 — banned import &#39;db.session&#39;<br>  ✗ FAIL  no-sql-in-routes<br>          routes/users.py:38 — pattern matched: execute(<br>  ✓ PASS  use-httpx-not-requests<br>  ✓ PASS  service-layer-boundary<br>  ✓ PASS  repo-naming-convention<br> ✗ 2 violations found</pre><p>Violations are errors. CI fails. The rule is enforced.</p><h3>Five Rule Types</h3><p>Arklint covers the full surface area of architectural concerns:</p><ul><li><strong>boundary: </strong>controls which modules can import from which packages</li><li><strong>dependency: </strong>restricts which libraries can coexist in a project</li><li><strong>file-pattern: </strong>enforces naming conventions in specific directories</li><li><strong>pattern-ban: </strong>prevents regex patterns from appearing anywhere (or in specific paths)</li><li><strong>layer-boundary: </strong>enforces one-directional dependencies: routes → services → repositories → nothing</li></ul><h3>The Part I’m Most Excited About: AI Awareness</h3><p>The reason Arklint exists is AI-generated code breaking architecture. So the most important feature isn’t the linter it’s making the linter visible to AI tools.</p><p><strong>MCP Server: </strong>Arklint exposes your rules via the Model Context Protocol. AI agents (Claude, Cursor, Copilot) can query your rules before generating code:</p><pre>AI: What are the architectural rules for this project?<br>Arklint MCP: routes/ must not import from db/ or models/.<br>              All HTTP calls must use httpx, not requests.<br>              Services must not call external APIs directly.<br>AI: Understood. Generating route handler using service layer only...</pre><p>The AI now knows your architecture exists. Violations drop dramatically.</p><p><strong>Rule Export: </strong>Export your rules directly into AI instruction files:</p><pre>arklint export --format claude      # → CLAUDE.md<br>arklint export --format cursorrules # → .cursorrules<br>arklint export --format copilot     # → .github/copilot-instructions.md</pre><p>Your .arklint.yml becomes the single source of truth for the linter and for every AI tool your team uses.</p><p><strong>arklint learn-</strong>Don&#39;t know YAML? Describe the rule in plain English:</p><pre>arklint learn --describe &quot;no raw SQL in route handlers&quot; --provider anthropic</pre><p>Arklint calls Claude, generates the YAML rule, shows it to you, and asks if you want to append it to your config. One command from intent to enforcement.</p><h3>Multi-Language Support</h3><p>The same .arklint.yml works across your stack. Install once per language:</p><pre>pip install arklint        # Python<br>npm install -g arklint     # Node.js<br>dotnet tool install -g arklint  # .NET</pre><p>Same binary. Same config. Same rules. Whether you’re enforcing architecture on a FastAPI backend, an Express API, or a .NET service one file governs all of them.</p><h3>Other Commands Worth Knowing</h3><pre>arklint watch      # live feedback as you edit — re-runs on every file change<br>arklint visualize  # generates a Mermaid diagram of your architecture rules<br>arklint validate   # checks your .arklint.yml is valid without running checks<br>arklint check --diff origin/main  # only scan files changed in this PR</pre><p>The --diff flag is particularly useful in CI — instead of scanning the full codebase on every PR, Arklint only checks the files that changed.</p><h3>Getting Started</h3><pre>pip install arklint   # or npm / dotnet<br>arklint init          # detects your ecosystem and generates a starter config<br>arklint check         # run your first scan</pre><p>arklint init detects your project ecosystem automatically FastAPI, Django, Express, clean architecture, and more and generates a tailored starter config.</p><p>For CI, add one step:</p><pre>- name: Arklint check<br>  run: arklint check --strict</pre><h3>Where It Goes From Here</h3><p>Arklint is open source and actively maintained. If your team has architectural standards that live in a doc nobody reads, try Arklint. If you find a bug, have a rule type in mind, or want to contribute, the repo is open at <a href="https://github.com/Kaushik13k/arklint">github.com/Kaushik13k/arklint</a>.</p><p>And if you’re using AI tools to write code which you probably are! give arklint export --format claude a try. Your AI assistant knowing your architecture exists is half the battle.</p><p><em>Install: </em><em>pip install arklint · </em><em>npm install -g arklint · </em><em>dotnet tool install -g arklint</em> <em>Docs: </em><a href="https://arklint.elevane.org/"><em>arklint.elevane.org</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62c42200093c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deadlocks]]></title>
            <link>https://medium.com/aimonks/understanding-deadlocks-b6b483dae376?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b483dae376</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Sun, 07 May 2023 16:23:52 GMT</pubDate>
            <atom:updated>2024-12-06T12:33:46.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unraveling Deadlock: Definition and Strategies to Resolve the Issue</h4><h4>What is meant by deadlock?</h4><p>Deadlock<strong> </strong>is a situation where multiple processes are stuck and unable to proceed because they are all waiting for one another to release a resource or execute a certain action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbp1IK7eiee3hfmbz5TwxA.jpeg" /></figure><h4>Let’s explore the concept of deadlock</h4><p>Imagine a real-life scenario where two cars meet at a four-way junction and one of them needs to cross the other’s path to move ahead.</p><p>Assume that Car A is coming from the east and Car B is coming from the north toward the junction. The drivers of the two cars arrive at the crossroads simultaneously, and they both intend to turn left to continue on their separate routes. However, they cannot move forward simultaneously since <strong>there is only enough room for a single car to pass</strong> at a time. Both drivers give each other the go-ahead signal, but neither wants to take the chance of hitting the other vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2v1UYUMqNPLHoiaqNbvhng.gif" /></figure><p>Therefore, both automobiles wait for the other vehicle to make the initial move before leaving the junction. This is a classic instance of a <strong>deadlock</strong>, in which two or more processes get stuck as they compete for the same resources.</p><h4>Lets code this particular instance</h4><pre>import threading<br><br>lock_a = threading.Lock()<br>lock_b = threading.Lock()<br><br>def car_a():<br>    while True:<br>        print(&quot;Car A is approaching the intersection.&quot;)<br>        lock_a.acquire()<br>        print(&quot;Car A is waiting for Car B...&quot;)<br>        lock_b.acquire()<br>        print(&quot;Car A is crossing the intersection!&quot;)<br>        lock_b.release()<br>        lock_a.release()<br><br>def car_b():<br>    while True: <br>        print(&quot;Car B is approaching the intersection.&quot;)<br>        lock_b.acquire()<br>        print(&quot;Car B is waiting for Car A...&quot;)<br>        lock_a.acquire()<br>        print(&quot;Car B is crossing the intersection!&quot;)<br>        lock_a.release()<br>        lock_b.release()<br><br>thread_a = threading.Thread(target=car_a)<br>thread_b = threading.Thread(target=car_b)<br><br>thread_a.start()<br>thread_b.start()<br><br>thread_a.join()<br>thread_b.join()</pre><h4>Output obtained</h4><pre>.<br>.<br>.<br>.<br>.<br>Car A is crossing the intersection!<br>Car A is approaching the intersection.<br>Car A is waiting for Car B...<br>Car B is waiting for Car A...</pre><p>Here, we can observe that at one point, a deadlock occurred in the code! Cars A and B are both waiting for one another!</p><h4>Lets take another example</h4><p>Deadlock is frequently explained in computer science using the Dining Philosophers issue as an example.</p><p>A group of philosophers are seated around a circular table with a bowl of rice and chopstick for each, as depicted in the famous <strong>Dining Philosophers problem</strong>. Each philosopher needs two chopsticks to eat, one on their left and one on their right. Chopsticks are limited to the number of philosophers(in our case there are 5 philosophers. Hence, 5 chopstick), thus the philosophers have to share the available supply.</p><p>The philosophers, When they sense the need for a break after some time of thought, they begin to eat.</p><p>The issue comes when two nearby philosophers each attempt to take up their right chopstick after simultaneously picking up their left ones. In this case, either philosopher is able to eat since they are stuck waiting for each other to put down their chopstick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qtel1lbBoK1wREdzz3vhlA.jpeg" /></figure><h4>Lets see this in code</h4><pre>import threading<br>class Philosopher(threading.Thread):<br>    def __init__(self, name, left_chopstick, right_chopstick):<br>        threading.Thread.__init__(self)<br>        self.name = name<br>        self.left_chopstick = left_chopstick<br>        self.right_chopstick = right_chopstick<br><br>    def run(self):<br>        while True:<br>            print(f&quot;{self.name} is thinking&quot;)<br>            self.left_chopstick.acquire()<br>            print(f&quot;{self.name} picked up left chopstick&quot;)<br>            self.right_chopstick.acquire()<br>            print(f&quot;{self.name} picked up right chopstick&quot;)<br>            print(f&quot;{self.name} is eating&quot;)<br>            self.right_chopstick.release()<br>            print(f&quot;{self.name} put down right chopstick&quot;)<br>            self.left_chopstick.release()<br>            print(f&quot;{self.name} put down left chopstick&quot;)<br><br>def main():<br>    chopsticks = [threading.Lock() for i in range(5)]<br>    philosophers = [Philosopher(f&quot;Philosopher {i+1}&quot;, chopsticks[i], chopsticks[(i+1)%5]) for i in range(5)]<br>    for p in philosophers:<br>        p.start()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>How to avoid the deadlock</h4><h4><strong>1. Resource Hierarchy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EetqUwrUZEYkVJ64XolGkg.jpeg" /></figure><p>Giving each lock a distinct ID allows us to create a sort of hierarchy for what to lock first and what to lock later. Using the example of Dining Philosophers problem. Here, we’ll establish a guideline for picking up forks. This is where we give the forks their <strong>serial numbers</strong>. The rule would dictate that we should take up the fork bearing the <strong>lower number</strong> first.</p><p>As an example., C1 will be selected by P3 first, followed by C2 by P2. P1 will take the C3, while the P5 will take the C4. Therefore, the final P4 will have the choice of selecting C1 or C5. Given that C1 is the lowest integer and is chosen by alternate philosopher. So, It won’t select a fork and will instead wait for C1 to become available. Now, the C5 will be available for P5. Hence, it will pick it up and start eating. Once done eating will will put away both C5 and C4. P1 will now have access to the for C4.</p><p>This continued until P3 did the same thing, at which point P4 had the chopsticks to use to eat since P3 had left the C1. This demonstrates that your thread will avoid a deadlock since it knows which lock/resource to utilize and always uses the same sequence.</p><h4>Code implementation</h4><pre>import threading<br><br>class Philosopher(threading.Thread):<br>    def __init__(self, name, left_chopstick, right_chopstick):<br>        threading.Thread.__init__(self)<br>        self.name = name<br>        self.left_chopstick = left_chopstick if left_chopstick.order &lt; right_chopstick.order else right_chopstick<br>        self.right_chopstick = right_chopstick if left_chopstick.order &lt; right_chopstick.order else left_chopstick<br><br>    def run(self):<br>        while True:<br>            print(f&quot;{self.name} is thinking&quot;)<br>            self.left_chopstick.acquire()<br>            print(f&quot;{self.name} picked up lower-order chopstick ({self.left_chopstick.order})&quot;)<br>            self.right_chopstick.acquire()<br>            print(f&quot;{self.name} picked up higher-order chopstick ({self.right_chopstick.order}) and is eating&quot;)<br>            self.right_chopstick.release()<br>            print(f&quot;{self.name} put down higher-order chopstick ({self.right_chopstick.order})&quot;)<br>            self.left_chopstick.release()<br>            print(f&quot;{self.name} put down lower-order chopstick ({self.left_chopstick.order})&quot;)<br><br>class Chopsticks:<br>    def __init__(self, order):<br>        self.order = order<br>        self.lock = threading.Lock()<br><br>    def acquire(self):<br>        return self.lock.acquire()<br><br>    def release(self):<br>        return self.lock.release()<br><br>def main():<br>    chopsticks = [Chopsticks(i) for i in range(5)]<br>    philosophers = [Philosopher(f&quot;Philosopher {i+1}&quot;, chopsticks[i], chopsticks[(i+1)%5]) for i in range(5)]<br>    for p in philosophers:<br>        p.start()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>2. Solving deadlocks using Arbitrator</h4><p>An alternative approach to the Dining Philosophers problem is the <strong>Arbitrator method</strong>. The fundamental concept behind this strategy is to have a central arbiter who manages the resources.</p><p>In our example., Chopstick requests must be handled by the arbitrator, who also makes sure that each philosopher has access to the two chopsticks they require for eating.</p><p>In the context of our dining problem, the arbitrator acts as a third party who determines which resources are allocated to whom. For example, in this scenario, the <strong>Weighter </strong>takes on the role of the arbitrator by deciding which philosopher is allowed to do what.</p><ul><li>The first philosopher (p3) decides to stop thinking and start eating. Instead of picking up chopsticks, p3 asks an arbitrator to pick up C1 and C2.</li><li>Each Chopstick is assigned a unique ID number.</li><li>The arbitrator knows that C1 and C2 are not being used, and instructs p3 to pick them up and start eating.</li><li>The next philosopher (p2) stops and asks the arbitrator for C2 and C3.</li><li>However, C2 is being used by p3, so the arbitrator instructs p2 to wait until the Chopstick becomes available.</li><li>P2 can either go to sleep or wait until the arbitrator signals the resources are available.</li><li>Eventually, p3 finishes eating and puts down C1 and C2, notifying the arbitrator that the resources are now free.</li><li>The arbitrator wakes up p2 and tells them that the resources are available.</li><li>P2 starts eating.</li></ul><h4>Code implementation</h4><pre>import threading<br><br>class Philosopher(threading.Thread):<br>    def __init__(self, name, arbitrator):<br>        threading.Thread.__init__(self)<br>        self.name = name<br>        self.arbitrator = arbitrator<br><br>    def run(self):<br>        while True:<br>            print(f&quot;{self.name} is thinking&quot;)<br>            self.arbitrator.request_chopsticks(self)<br>            print(f&quot;{self.name} is eating&quot;)<br>            self.arbitrator.release_chopsticks(self)<br><br>class Arbitrator:<br>    def __init__(self):<br>        self.chopsticks = [threading.Lock() for i in range(5)]<br>        self.waiting_list = []<br><br>    def request_chopsticks(self, philosopher):<br>        while True:<br>            philosopher_num = int(philosopher.name.split()[-1])<br>            left_chopstick = philosopher_num % 5<br>            right_chopstick = (philosopher_num + 1) % 5<br>            if self.chopsticks[left_chopstick].locked() or self.chopsticks[right_chopstick].locked():<br>                self.waiting_list.append(philosopher)<br>                print(f&quot;{philosopher.name} is waiting for chopsticks&quot;)<br>                continue<br>            self.chopsticks[left_chopstick].acquire()<br>            self.chopsticks[right_chopstick].acquire()<br>            print(f&quot;{philosopher.name} picked up chopsticks {left_chopstick+1} and {right_chopstick+1}&quot;)<br>            break<br><br><br>    def release_chopsticks(self, philosopher):<br>        left_chopstick = philosopher.name % 5<br>        right_chopstick = (philosopher.name + 1) % 5<br>        self.chopsticks[left_chopstick].release()<br>        self.chopsticks[right_chopstick].release()<br>        print(f&quot;{philosopher.name} put down chopsticks {left_chopstick+1} and {right_chopstick+1}&quot;)<br>        if self.waiting_list:<br>            next_philosopher = self.waiting_list.pop(0)<br>            self.request_chopsticks(next_philosopher)<br><br>def main():<br>    arbitrator = Arbitrator()<br>    philosophers = [Philosopher(f&quot;Philosopher {i+1}&quot;, arbitrator) for i in range(5)]<br>    for p in philosophers:<br>        p.start()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>In conclusion,</strong> deadlock is a common issue in computer science and other fields that deal with concurrent processes.</p><p>Deadlocks can lead to significant performance problems and can even cause a system to crash or become unresponsive. Therefore, it’s important to understand the causes of deadlock and implement strategies to prevent or resolve them, such as resource allocation or by using Arbitrator. By addressing deadlock proactively, we can ensure that our systems operate smoothly and efficiently, and avoid the negative consequences of this pervasive problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b483dae376" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/understanding-deadlocks-b6b483dae376">Understanding Deadlocks</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Synchronization in Python]]></title>
            <link>https://medium.com/@13kaushik.k/thread-synchronization-in-python-eb92cbe9518a?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb92cbe9518a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 15:11:15 GMT</pubDate>
            <atom:updated>2023-04-02T15:11:15.794Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Mutex Locks and Joins for Safe and Effective Multithreading in Python</h4><h4>What is the importance of synchronization?</h4><p>Let’s say there is a shared bank account with a balance of $50 that belongs to both you and your dad.</p><blockquote><strong>NOTE:</strong></blockquote><blockquote>Dad earns money and saves it in the bank account without spending, whereas you, who do not earn any money, continue to spend it.</blockquote><p>If we put this into code, starting with an initial investment of $50, Dad makes a $10 deposit into the bank account, making the total amount $60. Meanwhile, you spend $10, resulting in a balance of $50 (60–10 = 50).</p><p>However, a complication arises when both Dad and you conduct transactions simultaneously.</p><p>Consider that if Dad adds $10, the result is 50+10=60, and if you spend $10, the result is 50–10=40. There would be a $10 missing!…</p><p>This is referred to as the <strong>race condition</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*RvCozkvzC2_nrLCv-FGq8w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YErx-4nWO4ynrZ5PELqsNA.jpeg" /></figure><blockquote>When there is poor programming and there are several processes and threads attempting to access the same resources, a <strong>race condition</strong> occurs.</blockquote><p><strong>This race condition is notoriously difficult to debug.</strong> We may have a code that has been operating for weeks without incident and then crashes one beautiful day due to this race condition.</p><h4>Let’s get started on the coding for this,</h4><pre>from threading import Thread<br>import time<br><br>class JointAccount:<br>  current_balance = 50<br><br>  def dad(self):<br>    for i in range(1000000):<br>      self.current_balance += 10<br>    print(&#39;Dad saved!&#39;)<br><br><br>  def son(self):<br>    for i in range(1000000):<br>      self.current_balance -= 10<br>    print(&#39;Son Spent!&#39;)<br><br><br>account = JointAccount()<br>Thread(target=account.dad, args=()).start()<br>Thread(target=account.son, args=()).start()<br>time.sleep(5) # Here we are letting both the threads to be done<br>print(f&quot;The current balance in the account is: {account.current_balance}&quot;)</pre><p>The output is:</p><pre>Dad saved!<br>Son Spent!<br>The current balance in the account is: -963810</pre><p>We can tell that there is a bug here! Our predicted result is <strong>60</strong>, but we observe <strong>-963810</strong>. If you try again, we keep obtaining various results.</p><p><strong>How can we make this right?</strong></p><p>We’ll make advantage of <em>synchronizatio</em>n.</p><p><strong>How do we use synchronization?</strong></p><p>There are 2 synchronization techniques. A <strong>mutex lock</strong> is one technique, while another is utilizing <strong>joins.</strong></p><h4>1. Mutex Lock</h4><p>In order to understand this.., Imagine a lock that safeguards a particular piece of code and permits only one thread to access it at a time.</p><p>To ensure that only one thread can access the bank account at any given moment, we must restrict access to the <strong>current_balance</strong> variable in our scenario.</p><p>Assuming that no one else has locked the <strong>current_balance</strong>, the dad would request to lock it following the regular procedure. The dad will receive a message that he is holding the mutex after making the locking call.</p><p>After the dad has finished updating the <strong>current_balance</strong>, he will unlock it so that other threads may access it. The son will follow a similar procedure.</p><p>If a thread is already holding a mutex, and another thread requests it, the thread requesting will be put to sleep and kept waiting until the mutex is released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*dMrwKF9dEFhqOE7pi9AqKA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*LJEdI8LmHpdjsmk8H2sIxg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*aXEosWJpevdduUWKQLTaFA.jpeg" /></figure><p><strong>It is guaranteed that only one thread will have access and lock it if both attempt to access at the same time.</strong></p><h4>Implementation for lock</h4><pre>from threading import Thread, Lock<br>import time<br><br>class JointAccount:<br>  current_balance = 50<br>  mutex = Lock()<br><br>  def dad(self):<br>    for i in range(1000000):<br>      self.mutex.acquire()<br>      self.current_balance += 10<br>      self.mutex.release()<br>    print(&#39;Dad saved! &#39;)<br><br><br>  def son(self):<br>    for i in range(1000000):<br>      self.mutex.acquire()<br>      self.current_balance -= 10<br>      self.mutex.release()<br>    print(&#39;Son spend!&#39;)<br><br><br>account = JointAccount()<br>Thread(target=account.dad, args=()).start()<br>Thread(target=account.son, args=()).start()<br>time.sleep(5) # Here we are letting both the threads to be done<br>print(&quot;current_balance remaining is: &quot;, account.current_balance)</pre><p><strong>The output is:</strong></p><pre>Dad saved! <br>Son spend!<br>current_balance remaining is:  50</pre><h4>2. Joins</h4><p><strong>What is a join?</strong></p><p>A join is a method that enables a thread to wait until another thread has finished executing.</p><p><strong>In practice,</strong></p><p>A main thread creates a subthread to perform a task. The subthread starts executing its task.</p><p>Before going into a sleep state, the main thread will call the join() function. The join() function will hold the main thread until the subthread finishes executing its task and terminates.</p><p>Once the subthread has finished executing, the join() function will release, and the main thread will awaken and resume execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqsFLVd-7y7yn3-2xompbw.png" /></figure><h4>Implementation of JOIN() for a single task</h4><pre>import time<br>from threading import Thread<br><br>def child():<br>  print(&quot;subThread is created!&quot;)<br>  print(&quot;subThread is doing work&quot;)<br>  time.sleep(10)<br>  print(&quot;subThread work&#39;s done&quot;)<br><br>def parent():<br>  t = Thread(target=child, args=([]))<br>  t.start()<br>  print(&quot;mainThread thread put to sleep&quot;)<br>  t.join() # Parent will be blocked until the child is terminated <br>  # t.join(timeout=10)<br>  print(&quot;mainThread is awaken&quot;)</pre><p>Use <strong>timeout</strong> if you just want the parent to wait for a certain period of time.</p><p>The output is:</p><pre>subThread is created!<br>subThread is doing work<br>mainThread thread put to sleep<br>subThread work&#39;s done<br>mainThread is awaken</pre><p>Let’s say I have a multitude of tasks on my plate, and one of them is rendering an image. I want to complete this task as swiftly as possible. How can I achieve that?</p><p>To accelerate the rendering process, I will partition the image into multiple segments and allocate distinct threads to each part. There will be a main thread that spawns numerous child threads. The main thread will have to wait for all the child threads to finish rendering.</p><p>It will link up with the first child thread to start rendering, followed by the second child thread, and so on until the entire image is generated. To achieve this, I will utilize a <strong>for loop</strong>.</p><p><strong>Any threads that have already been finished will render immediately.</strong></p><p>First we’ll try doing it without using threads:</p><p><strong>We’ll write a script to look up a word, then match its word number to the appropriate phrase.</strong></p><pre>matches = []<br><br>passage1 = &quot;&quot;&quot;This is a sample passage<br>with multiple lines and words.<br>It is meant to demonstrate how to<br>search for a specific word in Python.&quot;&quot;&quot;<br><br><br><br># loop through each line and word to find the specific word<br>def word_search(word, passage):<br>  # split the passage into lines<br>  lines = passage.split(&quot;\n&quot;)<br><br>  for i, line in enumerate(lines):<br>      words = line.split()<br>      for j, w in enumerate(words):<br>          if w == word:<br>              matches.append(i+1)<br>              matches.append(j+1)<br>    <br>if __name__ == &#39;__main__&#39;:<br>  word_search(&#39;demonstrate&#39;, passage1)<br>  print(&quot;matched!&quot;)<br>  print(&quot;Sentence is :&quot;, matches[0])<br>  print(&quot;Word is :&quot;, matches[1])</pre><p>Now we’ll implement <strong>join()</strong></p><pre>from threading import Lock, Thread<br><br>mutex = Lock()<br>matches = []<br><br>passage1 = &quot;&quot;&quot;This is a sample passage<br>with multiple lines and words.<br>It is meant to demonstrate how to<br>search for a specific word in Python.&quot;&quot;&quot;<br><br># loop through each line and word to find the specific word<br>def word_search(word, passage):<br>  # split the passage into lines<br>  lines = passage.split(&quot;\n&quot;)<br><br>  for i, line in enumerate(lines):<br>      words = line.split()<br>      for j, w in enumerate(words):<br>          if w == word:<br>              mutex.acquire()<br>              matches.append(i+1)<br>              matches.append(j+1)<br>              mutex.release()<br><br>if __name__ == &#39;__main__&#39;:<br>  t = Thread(target=word_search, args=([&#39;demonstrate&#39;, passage1]))<br>  t.start()<br>  t.join() # waiting for it to finish<br>  print(&quot;matched!&quot;)<br>  print(&quot;Sentence is :&quot;, matches[0])<br>  print(&quot;Word is :&quot;, matches[1])</pre><p><strong>Use a passage that is very lengthy; otherwise, it won’t make any sense. 😂</strong></p><p><strong>In conclusion</strong>, understanding mutex locks and joins is essential for safe and effective multithreading in Python.<strong> Mutex locks</strong> provide a way to ensure that only one thread accesses a shared resource at a time, preventing race conditions and other concurrency issues. <strong>Joins</strong> allow one thread to wait for another to finish before continuing, ensuring that all necessary work is completed before a program terminates. By incorporating these techniques into your multithreaded Python programs, you can improve their safety, efficiency, and reliability, leading to better overall performance and fewer errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb92cbe9518a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threads in python and Global Interpreter Lock(GIL)]]></title>
            <link>https://medium.com/@13kaushik.k/threads-in-python-and-global-interpreter-lock-gil-3e5832e8352e?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5832e8352e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 14:11:13 GMT</pubDate>
            <atom:updated>2023-02-18T18:25:09.982Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick article explaining GIL</h4><h4>How does the thread interact with the processor?</h4><p>Consider that I have a queue having 4 threads and 4 processors. The sort of scheduler you are using determines how threads are organised.</p><p>The first thread leaves at the beginning and is allocated to a processor; the remaining three threads are now active. The remaining threads are also allocated to one or more of the remaining 3 processors as they are free. (This is frequently found in C++, Java, GO, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAZkcrNKkbER_O3MTMgX_A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2K9wN52UZdIdaTS7AF1QA.jpeg" /><figcaption><strong>Left: Before, Right: After</strong></figcaption></figure><p><strong>Python uses a different style for this.</strong></p><p>Imagine once more that I have four processors and a queue (having 4 threads) called ready queue.</p><p>The operating system will now choose a thread from ready queue and transfer it to a processor. Python would lock the remaining thread of that programme at this point while the thread is being run.</p><p>This would now result in the waiting queue being populated with the remaining threads (i.e., they won’t be scheduled to execute on any of the processors).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1C4EK5_QZ7LWfviw7tqByw.jpeg" /></figure><p>The thread will eventually be interrupted, returning back to the ready queue along with all of the other threads from the waiting queue. A new thread will now be assigned to a processor, locking the others. so the cycle keeps on! The term for this is <strong>GIL</strong>, or <strong>Global Interpreter Lock</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kue3tebYIRNcgcQkm5BgNg.jpeg" /></figure><h4>Why is GIL in the picture?</h4><p>Python did so because it intended to make the interpretator’s implementation simpler. It was a decision made early on during the creation of the Python interpreter, and it was made in such a manner that the various libraries will be easier to implement (The majority of Python libraries are written in C/C++, which requires GIL for proper operation).</p><h4>What issue was resolved by the GIL?</h4><p>As was already discussed, Python’s GIL makes sure that only one thread is active at once. Therefore, we can promise that there won’t be any danger of race conditions even if a multi-threaded function accesses common data.</p><p>To further understand, let’s look at an example…</p><p>Imagine that Dad and his son have a bank account with $50 in it. Therefore, if we think about how dad constantly saves money and son always spends it. <br>We’ll have three conditions here!</p><ol><li>The father saves money here; the son spends it later</li></ol><pre>current_account_balance = 50<br><br># Dad saves<br>current_account_balance = current_account_balance + 10<br># we have current balance i.e. 50 + 10 = 60<br><br><br># Son spends<br>current_account_balance = current_account_balance - 10<br># we have current balance i.e. 60 -10 = 50</pre><p>2. Son spends the cash, and then the father saves it.</p><pre>current_account_balance = 50<br><br># Son spends<br>current_account_balance = current_account_balance - 10<br># we have current balance i.e. 50 -10 = 40<br><br># Dad saves<br>current_account_balance = current_account_balance + 10<br># we have current balance i.e. 40 + 10 = 50</pre><p>3. Both the father and son simultaneously save and spend money.</p><p>Then they will both read the starting value of <strong>current_account_balance</strong>, which is 50, and the ultimate value of <strong>current_account_balance</strong> will be determined by the thread that will alter <strong>current_account_balance</strong> at the end.</p><blockquote>As a result, we may define a <strong>race condition</strong> as an undesired and unmanageable circumstance that depends on the order in which statements are executed.</blockquote><p><strong>Because Python only allows one thread to run at a time, this circumstance(race condition) is avoided by the GIL.</strong></p><blockquote>Note:</blockquote><blockquote>When a programme is entirely CPU bound, adding threads to speed it up serves no purpose.</blockquote><h4>What is CPU bound?</h4><p>It is the point in the program’s execution cycle when the processor is used most often. This is often the case when there are several calculations to be made.</p><p>Like CPU-bound programmes that spend the majority of their time running on the processor. Gaming and visuals are the obvious topics. Games include a lot of arithmetic! Additional examples include software with image processing, machine learning, etc.</p><blockquote>IO-bound processes are the opposite of CPU-bound processes.</blockquote><h4>What is IO bound Process?</h4><p>This is the situation in which your process takes a long time to wait for input or output. (IP/OP may be used for a variety of things, including reading from the server, writing on it, and waiting for user input.)</p><p>E.g. this web page is currently being rendered while we wait for the photos to download; as a result, Due to the need to wait for the server, web servers consume a lot of IO!</p><p>The takeaway here is that using threads to boost speed if your CPU is constrained will not work at all.</p><p>However, if your process is IO-bound, like a web server, it’s OK to employ threads because they save time.</p><p>We can keep things moving throughout this by scheduling more threads.Other languages do not have these constraints, which are unique to Python.</p><h4><strong>How to Deal with Python’s GIL? and also </strong>how can I increase the CPU bound’s speed?</h4><p>We can say that the following approach will be effective for both problems.</p><ul><li><strong>Multiprocessing: </strong>It is among the most well-liked and successful methods of getting around the GIL. Since each process in Python has its own unique interpreter and memory space, GIL is not a problem when we employ multiple processes rather than numerous threads. Additionally, since using many processes its much more costlier than using numerous threads, it should be utilised wisely. because it requires time and individual memory.</li><li><strong>Choosing an alternative interpreter: </strong>Numerous interpreter versions of Python are available. The most well-known ones are respectively built in Python (PyPy), Java (Jython), C# (IronPython), and C (CPython).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5832e8352e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Seaborn]]></title>
            <link>https://medium.com/@13kaushik.k/introduction-to-seaborn-c24fa1ddd109?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c24fa1ddd109</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 05:17:55 GMT</pubDate>
            <atom:updated>2023-04-10T10:35:09.653Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick reference for Python Seaborn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*HjjxKlXte7MmsxK9HxXrWg.jpeg" /></figure><h3>Prerequisites:</h3><blockquote>It suffices to have a working understanding of Python.</blockquote><h4>Covered Topics</h4><h4>Chapter 1 - Seaborn</h4><ul><li><a href="#4e5f">What is Seaborn?</a></li><li><a href="#da5e">Seaborn Installation</a></li><li><a href="#491b">Importing Seaborn</a></li><li><a href="#1d80">Make your very first plot!</a></li></ul><h4>Chapter 2 - Figure-level vs. axes-level functions</h4><h4>Chapter 3 - Relplot (R<strong>elational Plot)</strong></h4><ul><li><a href="#3dff">Scatter Plot</a></li><li><a href="#4898"><em>Hue</em></a></li><li><a href="#9ce1">Style</a></li><li><a href="#2b36">LinePlot</a></li><li><a href="#996b">RelPlot</a></li></ul><h4>Chapter 4 - Changing the size of plots</h4><h4>Chapter 5 - Displot (D<strong>istribution Plot)</strong></h4><ul><li><a href="#3560">Histogram</a></li><li><a href="#048c">KDE plots (Kernel Density Estimation)</a></li><li><a href="#8165">Bivariate distribution plots</a></li><li><a href="#f0e7">Rugplots</a></li><li><a href="#fb65">Count plot</a></li><li><a href="#3e13">Displot</a></li></ul><h4>Chapter 6 - Catplot (Categorical Plots)</h4><ul><li><a href="#b93b">Strip and Swarm plots</a></li><li><a href="#0119">Box plot</a></li><li><a href="#e9b6">Violin plots</a></li><li><a href="#28c4">Bar plot</a></li><li><a href="#5803">Catplot</a></li></ul><h4>Chapter 7</h4><ul><li><a href="#7fe7">Setting theme in Seaborn</a></li><li><a href="#77c9">Changing the seaborn themes</a></li><li><a href="#6207">Customizing the style</a></li><li><a href="#e6f7">Changing the axes styles</a></li><li><a href="#b96c">Altering the spine with despine</a></li><li><a href="#0d86">Change the colout pallets</a></li></ul><h3>Chapter 1 - Seaborn</h3><h4>What is seaborn?</h4><ul><li>Seaborn is a data visualization library, Using Matplotlib as a foundation.</li><li>Provides an interface at a high level. With just one line of code, you can create complicated charts!</li><li>Creates stunning charts quickly and easily right out of the box!</li></ul><h4>Seaborn Installation</h4><p>Now, let’s install Seaborn on our machine.</p><blockquote>The process of installing seaborn on your computer is quite simple.<br>There are two approaches:<br>1. Using pip<br>2. Using conda</blockquote><ol><li><strong>Using pip:</strong></li></ol><pre>pip install seaborn</pre><p>2. <strong>Using Conda:</strong></p><pre>conda install -c anaconda seaborn</pre><h4>Importing Seaborn</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b78933177a797f0cec12306710e18e/href">https://medium.com/media/f6b78933177a797f0cec12306710e18e/href</a></iframe><h4>Make your very first plot!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34321a9c01412e5925c7124fc23f41d/href">https://medium.com/media/a34321a9c01412e5925c7124fc23f41d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ZoAa5obmpC6bGvNBCf6p1A.png" /></figure><p>Because X and Y lack data or because no data was supplied, we are given an empty graph.</p><h3>Chapter 2 - Figure-level and Axes-level functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3z85OyiKqLIoWr5Qx3YgA.png" /></figure><ul><li><strong>Axes-level</strong> functions, including scatterplot, lineplot, histplot,stripplot, swarmplotand many others</li><li><strong>Figure-level</strong> functions, including relplot, catplot, displot.</li></ul><h3>Chapter 3- Relplot (Relationship Plot)</h3><p>You can download the Dataset <a href="https://www.kaggle.com/datasets/brendan45774/test-file">HERE</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d970fd9fecbd95375339c6c47c84cc/href">https://medium.com/media/e4d970fd9fecbd95375339c6c47c84cc/href</a></iframe><h4>Scatter Plot</h4><p>A set of dots plotted on a horizontal and vertical axis is known as a scatter plot. Because they may demonstrate the degree of connection, if any, between the values of observed quantities or events, scatter plots are crucial in statistics.</p><p>To create a scatter plot</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b164bef7c0cd8a95c8588fc41bed47f/href">https://medium.com/media/0b164bef7c0cd8a95c8588fc41bed47f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*DrNIMUtaddqwEmia302JxQ.png" /></figure><h4>Hue</h4><p>The column in the data frame that should be utilised for colour encoding in Seaborn is determined by the <strong>hue</strong> parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4317d144b397707eb7067c75f87f3e0/href">https://medium.com/media/d4317d144b397707eb7067c75f87f3e0/href</a></iframe><p>Hue is used in various seaborn approaches, not only scatter plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*dbL37gRHhfb4C3l5xFsMLQ.png" /></figure><p>Now that we have three columns, we can create plots. Additionally, it reveals the sex!</p><h4>Style</h4><p>Style indicates marker</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85feaf06e5ff12a283e964568fe0dfa4/href">https://medium.com/media/85feaf06e5ff12a283e964568fe0dfa4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*jLrY6XnyuXRg3gwKg4KcbA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6be1b683885d34f19b243984ddac5b/href">https://medium.com/media/df6be1b683885d34f19b243984ddac5b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*TWcmuIAaMbqYXwTraw-yUw.png" /></figure><p>Since we utilise them to distinguish between the two groups, we may assume that <strong>Style</strong> and <strong>Hue</strong> might be similar.</p><h4>Line Plots</h4><p>When working on machine learning or data science projects, line plots, one of the simplest and most fundamental graphical analysis tools, are crucial for data analysis. The connection between two variables is expressed using them.</p><p>For this you may download the dataset <a href="https://github.com/mwaskom/seaborn-data/blob/master/flights.csv">HERE</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb71f17541c19417a88654a1187503b/href">https://medium.com/media/9bb71f17541c19417a88654a1187503b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*3ox0WnjTJF35jkffzBYhuQ.png" /></figure><p>The line plot in this example, by default, uses the data’s average.</p><p>If we don’t want that to happen, then we should pass the <strong>estimator</strong> argument.</p><blockquote><strong>Note</strong>: What is it doing in the background? or say how is it doing?</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6c028a6647682c3b0ee0e27362b7299/href">https://medium.com/media/f6c028a6647682c3b0ee0e27362b7299/href</a></iframe><h4>Relplot (Relational Plot)</h4><p>Seaborn has a tool called relplot, short for relationship plot, to simplify complicated comparisons. <strong>Relplot</strong> accepts some of the same parameters as scatterplot, including data, x, y, and colour etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f858350398e75911a5a55f98f49d1a1d/href">https://medium.com/media/f858350398e75911a5a55f98f49d1a1d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yzCakV_Qk0eNf_LqjC55w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*CVfNs0RRgLOwQfONTSGqyg.png" /></figure><p>Here, a line or scatter plot of a relationship might be used. We can refer to them as <strong>kind</strong>. Moreover, we may divide the plots into other sections, such as Sex in the argument <strong>col</strong>.</p><blockquote><strong>Note : </strong>We are unable to perform it in a scatterplot since it uses an axis level approach. However, the relplot uses a figure-level approach. We may therefore divide into relplot.</blockquote><p>We may also add colour. then separate columns, the graph will become much more informative.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec54bed8e08058c0dcb48481d3a867c/href">https://medium.com/media/3ec54bed8e08058c0dcb48481d3a867c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9-ioLNHDCKH46liInr06w.png" /></figure><p>The same may be done with <strong>lineplots</strong> as well!</p><h3>Chapter 4- Changing the size of plots</h3><p>The methods for altering the figure level and axis level varies.</p><p>We will first look at how to change the <strong>axis level</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ea6600dbd27b7d70d95f9d33b50201/href">https://medium.com/media/c5ea6600dbd27b7d70d95f9d33b50201/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*VQHtOEWBmXzjVvoj7FK-jQ.png" /></figure><p>Now for <strong>figure level.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d95cc83038633034f33788ed7698356c/href">https://medium.com/media/d95cc83038633034f33788ed7698356c/href</a></iframe><blockquote>Note:</blockquote><blockquote>Height governs each distinct subplot. Seaborn refers to it as an facet.</blockquote><blockquote>Length would be measured in inches.</blockquote><blockquote><strong>Aspect</strong> refers to <strong>width. Aspect = 1</strong> signifies that it is equal to height. If the A<strong>spect = 2,</strong> then its multiplied with height hence it’s twice as height.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*4oeUWXHJ37RrzTBG4kwinw.png" /></figure><h3>Chapter 5 - Displot (Distribution Plot)</h3><h4>Histogram</h4><p>A histogram categorises or organises the range of potential values in a data collection. A rectangle with a base length equal to the range of values in each group and a length equal to the number of observations falling into that group is created for each group.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f723145ee93065bdffaaeb8bc4c1c6cd/href">https://medium.com/media/f723145ee93065bdffaaeb8bc4c1c6cd/href</a></iframe><blockquote><strong>What is stack?</strong></blockquote><blockquote>Objects are shown in stacked graphs as either rows or columns of elements that are distinguished by coloured bars or strips. A stacked graph is helpful for examining changes in, for instance, cumulative spending over time across multiple goods or services.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*EiwtzyhunYRm_nabTFII_Q.png" /></figure><p>By default, the opaqueness is made transparent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e2862c348c83bdb6fbbd82b7d802b8/href">https://medium.com/media/b1e2862c348c83bdb6fbbd82b7d802b8/href</a></iframe><blockquote><strong>What is stack?</strong></blockquote><blockquote>Dodge is to create the graphs side-by-side.</blockquote><blockquote><strong>What is bins?</strong></blockquote><blockquote>You may modify the histogram’s bins using the bins argument (i.e., the number of bars)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*WY2__c_dDLsDmVNPNLwrLA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d87244639f851b9cef859bf41559c74e/href">https://medium.com/media/d87244639f851b9cef859bf41559c74e/href</a></iframe><p>Instead of turning it into distinct bars, we may give it a step-wise pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*8IY4_uPZdob-zsK6oVQsMg.png" /></figure><h4>KDE PLOTS (Kernel Density Estimation)</h4><p>Kernel density estimation (KDE) is a statistical technique that uses kernel smoothing to estimate probability density functions of random variables. It is a non-parametric approach that uses kernels as weights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ca736d635f0b6a2238ce7822a058242/href">https://medium.com/media/8ca736d635f0b6a2238ce7822a058242/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Jfsi0-XYBxAnKhfQ3U6i9w.png" /></figure><p>Another illustration using stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7621a192097ab919981f9d7065094aa/href">https://medium.com/media/a7621a192097ab919981f9d7065094aa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*nNlMq6C9bNZ7iBggCqEHBg.png" /></figure><h4>Bivariate distribution plots</h4><p>A bivariate histogram divides the data into the rectangular tiles that make up the plot, and the fill colour of each rectangle indicates the number of observations included inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b8b56f6d5dcb1cca7c44cdcfb7ffbc/href">https://medium.com/media/48b8b56f6d5dcb1cca7c44cdcfb7ffbc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*d64UrJGnNI-RfvpSN8WB5g.png" /></figure><h4>Rugplots</h4><p>A rug plot is a data plot with markings along an axis for a single quantitative variable. It is used to display the data’s dispersion. As a result, it is comparable to a one-dimensional scatter plot or a histogram with zero-width bins.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c0ff28a6cabfb57e4cf1fc829b7338a/href">https://medium.com/media/0c0ff28a6cabfb57e4cf1fc829b7338a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*BWSQ6b3riTJVsFofLvct0Q.png" /></figure><h4>Count plot</h4><p>The numbers of data in each category bin are displayed using bars in the count plot approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61195b64d3ce5ff240c877b5f40add4e/href">https://medium.com/media/61195b64d3ce5ff240c877b5f40add4e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*Pd8SmMN8Vlv-QfwZvsaD2w.png" /></figure><p>works well with categorical variables and is extremely similar to a histogram (non numeric values).</p><h4>Displot (Distribution Plot)</h4><p>This plot is at the figure level.</p><p>The change in the data distribution is shown by a distribution plot, or Displot. The total distribution of continuous data variables is represented by a Seaborn Displot.</p><p>The implementation for this would be same as we did with the <a href="#996b"><strong>relplots</strong></a></p><h3>Chapter 6 — Catplot (Categorical Plots)</h3><h4>Strip and Swarm plots</h4><p>In order to summarize a univariate data set, a <strong>strip plot</strong> is a visual data analysis approach.</p><p><strong>Swarm plots</strong> are a particular kind of scatter plot that are employed to display categorical values. Although it is fairly similar to the strip plot, it prevents point overlapping.</p><h4>Strip vs Swarm plot</h4><p>The primary distinction is that in a swarm plot, the data points are modified along the category axis without overlapping. On the other hand, by adjusting the alpha parameter that controls point transparency, the problem of point overlapping in a strip plot can be partially resolved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a37290d11e8cdcd256b288be947fe3/href">https://medium.com/media/f9a37290d11e8cdcd256b288be947fe3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*IkCKdrAcxJb94nb6qNV-fg.png" /></figure><p>The above illustration displays a scatter plot.</p><p>For both x and y numerical data, scatter graphs work well. Hence, As an alternative, we might utilize <strong>striplot</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa68c0b4fc39efa30b53136440bccc5/href">https://medium.com/media/daa68c0b4fc39efa30b53136440bccc5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*CikbtIEaEAAR9qHZQD02tg.png" /></figure><p>For both categorical and numerical variables, a<strong> strip plot </strong>works well.</p><p>The <strong>swarm plot</strong> is another method since we can observe dence at the bottom and we can’t tell them apart from the other numerical values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4f6cd8cee8489c63a2621ffe38be7c9/href">https://medium.com/media/d4f6cd8cee8489c63a2621ffe38be7c9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*DtRqnEyFvyuNp19_dGTDhw.png" /></figure><p><strong>Swarm plots</strong> cannot be used with enormous data sets, but they may be used with manageable data since they attempt to plot every conceivable depict.</p><h4>Box plot</h4><p>When displaying the distribution of data points over a given metric, <strong>box</strong> <strong>plots</strong> are an excellent graphic to employ. These graphs show the ranges of the measured variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3082f77e898467dfd1231590ee400f6/href">https://medium.com/media/c3082f77e898467dfd1231590ee400f6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*Wt6hTLMDBe5mOKIssqiiGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohRdfmoSiNycuw6lrwWpPQ.png" /></figure><h4><strong>Definitions</strong></h4><p><strong>Minimum Score</strong></p><p>Lowest score after removing outliers</p><p><strong>Lower Quartile</strong></p><p>25% of scores fall below the lower quartile value. (First Quartile)</p><p><strong>Median</strong></p><p>The line dividing the box into two portions represents the median, which is the midpoint of the data. Half of the scores are higher than or equal to this number, while the other half are lower. (Second Quartile)</p><p><strong>Upper Quartile</strong></p><p>75% of the scores are below the upper quartile value. 25% of the data are therefore over this value. quartile (Third Quartile)</p><p><strong>Maximum Score</strong></p><p>Highest score after removing outliers</p><p><strong>Whiskers</strong></p><p>Scores outside the middle 50% are represented by the upper and lower whiskers.</p><p><strong>The Interquartile Range (IQR)</strong></p><p>The middle 50% of scores are depicted in this box plot.</p><p><strong>Let’s combine the <em>swarm-plot</em> and <em>box-plo</em>t now to see what happens!</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157d1782f366f65e903c58076421bd5e/href">https://medium.com/media/157d1782f366f65e903c58076421bd5e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*oZtttKUPbBFyfPOsDHFPdQ.png" /></figure><h4>Violin plots</h4><p>Numeric data can be plotted using a technique called a <strong>violin plot</strong>, which is a hybrid of a box plot and a kernel density plot. The information found in box plots may also be found in the violin plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*6P_solhqZlhAsATb.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f83b29a8a5794d8818e49c63cb95a3b/href">https://medium.com/media/9f83b29a8a5794d8818e49c63cb95a3b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*gxlhFKq9EEFugWADIAIBUA.png" /></figure><h4>Bar plot</h4><p>A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart <a href="https://en.wikipedia.org/wiki/Bar_chart"><strong>(wikipedia)</strong></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62ab938c38a4ce3f522e4f0502e6121/href">https://medium.com/media/d62ab938c38a4ce3f522e4f0502e6121/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*_IFcbfjlugo9pmfwByOs0Q.png" /></figure><blockquote>The mean is originally provided by the bar graphs, but we may modify it.</blockquote><blockquote><strong>How?</strong></blockquote><blockquote>The parameter called estimator is used to do so.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46d85848b9f811820ed4235887567116/href">https://medium.com/media/46d85848b9f811820ed4235887567116/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Ra7zrcrZoQjZefFGnDJtjA.png" /></figure><blockquote>What does the top black line mean?</blockquote><blockquote>That is known as <strong>error</strong> <strong>bar.</strong></blockquote><blockquote><strong>On graphs, error bars are used to graphically show data variability and to denote error or uncertainty in reported measurements.</strong></blockquote><h4>Catplot</h4><p>This plot is at the figure level.</p><p>Creating categorical plots onto a FacetGrid using a figure-level interface. This feature gives users access to a number of axes-level functions that illustrate the connection between a numerical variable and one or more category variables using a variety of visual representations.</p><p>The implementation for this would be same as we did with the <a href="#996b"><strong>relplots</strong></a></p><h4>Styling the seaborn</h4><h4>Setting theme in Seaborn</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8e9f37f3b95d505f12bbab9755345c9/href">https://medium.com/media/d8e9f37f3b95d505f12bbab9755345c9/href</a></iframe><p>We didn’t specify the theme, thus it will be used by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*rD3BuRK09qjVt7JLy4zeVQ.png" /></figure><h4>Changing the seaborn themes</h4><p>To style its plots, Seaborn features five built-in themes.</p><ol><li>darkgrid</li><li>whitegrid</li><li>dark</li><li>white</li><li>ticks</li></ol><p>For its plots, Seaborn by default uses the darkgrid theme, however you may alter this design to better fit your presentation requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613558eeb2fa10ff6085ed78a555a42d/href">https://medium.com/media/613558eeb2fa10ff6085ed78a555a42d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*PL_cT_AZqVLS1xmjMkO19w.png" /></figure><h4>Customizing the style</h4><p>To get every style that the Seaborn has</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85bd77844e88a356478bdd8ff7c7fb19/href">https://medium.com/media/85bd77844e88a356478bdd8ff7c7fb19/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd141fb854d8a1be13808d08543729fd/href">https://medium.com/media/cd141fb854d8a1be13808d08543729fd/href</a></iframe><h4>Changing the axes styles</h4><p>Everything available in the <strong><em>sns.axes style()</em></strong> can be modified .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c33bc325975c9df1cb9d1ddf03d1b4e/href">https://medium.com/media/0c33bc325975c9df1cb9d1ddf03d1b4e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*2p1V62Wqn-p9CtJZ_4KoSg.png" /></figure><h4>Altering the spine with despine</h4><blockquote>WHAT is <strong>spine</strong>?</blockquote><blockquote>It is the borders fond in individual plots.</blockquote><p>To remove the spine from the top and right by general then use</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a26bb303809bc262561072eb18b84e38/href">https://medium.com/media/a26bb303809bc262561072eb18b84e38/href</a></iframe><p>If you need specific location, then</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d74cd5cd8e94273e4e6ddd0bc908fa/href">https://medium.com/media/a9d74cd5cd8e94273e4e6ddd0bc908fa/href</a></iframe><h4>Change the colour pallets</h4><p>Available style (deep, muted, bright, pastel, dark, colorblind)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d73e71c9db8ccaa86c3d8436ca917d/href">https://medium.com/media/12d73e71c9db8ccaa86c3d8436ca917d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_c32C4GHpxPnbCOEWPAeg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffa0af6b957d1fe27205137d9d8fe29f/href">https://medium.com/media/ffa0af6b957d1fe27205137d9d8fe29f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2BaD6iPIPuHSr-sDTO-PQ.png" /></figure><p>Setting the pallets with the graph,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e59769e2caa6013b1c8999d7e5e265fe/href">https://medium.com/media/e59769e2caa6013b1c8999d7e5e265fe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*VXdPLIbKo6xlNJT7rNFweA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c24fa1ddd109" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python visualization using Matplotlib]]></title>
            <link>https://medium.com/@13kaushik.k/python-visualization-using-matplotlib-823d18e04b64?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/823d18e04b64</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 17:22:35 GMT</pubDate>
            <atom:updated>2022-12-26T18:01:47.075Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive guide for using Matplotlib for visualising</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMAQo_DJl1Mbvq9KT6WYUw.jpeg" /></figure><h3>Prerequisites:</h3><blockquote>It is enough to have a fundamental knowledge of Python.</blockquote><h3>Covered Topics</h3><h4><strong>Chapter 1 - Matplotlib</strong></h4><ul><li><a href="#4e5f">What is matplotlib?</a></li><li><a href="#fe5e">Matplotlib Installation</a></li><li><a href="#434b">Importing Matplotlib</a></li><li><a href="#6344">Make your very first plot!</a></li></ul><h4>Chapter 2 - Basics of the plots</h4><ul><li><a href="#da6e">Figures</a></li><li><a href="#b30d">Resize the figure</a></li></ul><h4>Chapter 3 - Styling the plot</h4><ul><li><a href="#98c6">Get all of the existing stylesheets</a></li><li><a href="#a73b">Using the stylesheet</a></li><li><a href="#2707">Styling Manually</a></li><li><a href="#5925">Plot Markers</a></li></ul><h4>Chapter 4 - Plot labels and titles</h4><ul><li><a href="#b5c2">Giving titles</a></li><li><a href="#5c5d">Giving labels</a></li></ul><h4>Chapter 5 - Ticks and Legend</h4><ul><li><a href="#a2fd">Ticks</a></li><li><a href="#82a4">Legend</a></li></ul><h4>Chapter 6 — Different types of graph</h4><ul><li><a href="#b47e">Bar graph</a></li><li><a href="#bfcd">Scatter plot</a></li><li><a href="#707f">Pie chart</a></li></ul><h4>Chapter 7 - Sub-plots</h4><ul><li><a href="#6f00">Creating a sub-plot</a></li></ul><h3>Chapter 1 - Matplotlib</h3><h4>What is matplotlib?</h4><p><strong>Matplotlib</strong> is a comprehensive library for creating static, animated, and interactive visualizations in Python. Matplotlib makes easy things easy and hard things possible.(Source <a href="https://matplotlib.org/">Documentation</a>)</p><h4>Matplotlib Installation</h4><p>Now, let’s install matplotlib on our machine.</p><blockquote>The process of installing matplotlib on your computer is quite simple.<br>There are two approaches:<br>1. Using pip<br>2. Using conda</blockquote><ol><li><strong>Using pip:</strong></li></ol><pre>pip install matplotlib</pre><p>2. <strong>Using Conda:</strong></p><pre>conda install -c conda-forge matplotlib</pre><p>3. Additionally, Through their official <a href="https://matplotlib.org/">document</a>, you may also try it online <a href="https://mybinder.org/v2/gh/matplotlib/mpl-brochure-binder/main?labpath=MatplotlibExample.ipynb">here</a>.</p><h4><strong>Importing Matplotlib</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b4e38a7c7e5bb99001dbb40c46fc7a4/href">https://medium.com/media/3b4e38a7c7e5bb99001dbb40c46fc7a4/href</a></iframe><h4>Make your very first plot!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b735be3d1cebded551ab552673eb2d19/href">https://medium.com/media/b735be3d1cebded551ab552673eb2d19/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofQ2jeYvMGaOOnwD70rYoQ.png" /></figure><p>We receive an empty graph because X and Y have no data or because no data was provided.</p><p>Its using fake X and Y axes.</p><blockquote>The X and Y expects something like a series/ list etc</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4e61fad54e82c607a287732089df647/href">https://medium.com/media/e4e61fad54e82c607a287732089df647/href</a></iframe><blockquote>The array input is accepted for y by default, while for x it accepts an index array of 0 to N-1.</blockquote><blockquote><strong>Example :</strong></blockquote><blockquote>For the above example,</blockquote><blockquote>X → [0, 1, 2, 3]</blockquote><blockquote>y → [2, 4, 6, 8]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2OiUwymD2rj9PWQ5Jfyyw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ef4abec93176cc750bf5af0521edee/href">https://medium.com/media/e4ef4abec93176cc750bf5af0521edee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBnKrfYfz44J-yLKYAr_bg.png" /></figure><p><strong>Note:</strong> Everything we write will be visible since we are in the notebook! However, it could not be displayed if we are using another integrated development environment (IDE).</p><p>Hence we use, <strong>.show()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/951247614efd050526b91cf5ed12779f/href">https://medium.com/media/951247614efd050526b91cf5ed12779f/href</a></iframe><h3>Chapter 2 - Basics of the plots</h3><h4><strong>Figures</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f761e20cba8f27e78c5ca2bd8cd0efab/href">https://medium.com/media/f761e20cba8f27e78c5ca2bd8cd0efab/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PSI4ZG40tdn2NIR4XcQEQ.png" /></figure><blockquote>The graph shown above combines three separate plots into a single canvas or <strong>figure</strong>.</blockquote><blockquote><strong>Axes:</strong> comprised of the x and y axis and can be 2D or 3D. Axes are made with anything that has labels, including the data that displays the border, etc.</blockquote><blockquote>In the above figure, these axes are gathered together.</blockquote><p>To create the separate figure, we use <strong>.figure()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e070806314e1fbcdbef8bc13c88dd1/href">https://medium.com/media/92e070806314e1fbcdbef8bc13c88dd1/href</a></iframe><h4>Resize the figure</h4><p>Here, we may specify the figure’s size.</p><p>Use of <strong>.figsize()</strong> is made. The measures given are in inches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddb2433e4b51b8654550c255d593d26b/href">https://medium.com/media/ddb2433e4b51b8654550c255d593d26b/href</a></iframe><h3>Chapter 3 - Styling the plot</h3><h4><strong>Get all of the existing stylesheets</strong></h4><p>A style sheet is a document that instructs the IDE how to display a plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4ced19de9b716d7ebf48fb9ab21abc4/href">https://medium.com/media/f4ced19de9b716d7ebf48fb9ab21abc4/href</a></iframe><p>Here are some stylesheets</p><pre>[<br>    &#39;Solarize_Light2&#39;,<br>    &#39;_classic_test_patch&#39;,<br>    &#39;bmh&#39;,<br>    &#39;classic&#39;,<br>    &#39;dark_background&#39;,<br>    &#39;fast&#39;,<br>    &#39;fivethirtyeight&#39;,<br>    &#39;ggplot&#39;,<br>    &#39;grayscale&#39;,<br>    &#39;seaborn&#39;,<br>    &#39;seaborn-bright&#39;,<br>    &#39;seaborn-colorblind&#39;,<br>    &#39;seaborn-dark&#39;,<br>    &#39;seaborn-dark-palette&#39;,<br>    &#39;seaborn-darkgrid&#39;,<br>    &#39;seaborn-deep&#39;,<br>    &#39;seaborn-muted&#39;,<br>    &#39;seaborn-notebook&#39;,<br>    &#39;seaborn-paper&#39;,<br>    &#39;seaborn-pastel&#39;,<br>    &#39;seaborn-poster&#39;,<br>    &#39;seaborn-talk&#39;,<br>    &#39;seaborn-ticks&#39;,<br>    &#39;seaborn-white&#39;,<br>    &#39;seaborn-whitegrid&#39;,<br>    &#39;tableau-colorblind10&#39;,<br>    ]</pre><h4>Using the stylesheet</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c56e9d35e6fb9471701bd0d597406e/href">https://medium.com/media/92c56e9d35e6fb9471701bd0d597406e/href</a></iframe><p>From the list above, select any style you like.</p><p>Now plotting again,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab2bc2cc3299ea781dde1c880939c68d/href">https://medium.com/media/ab2bc2cc3299ea781dde1c880939c68d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLmIOYp9Cj1JHnG1Tk0jGg.png" /></figure><p><strong>Note:</strong> once we apply the style. Moving forwards, every plot will be impacted!</p><h4>Styling Manually</h4><p>We may also manually change the style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f5718704606ca06400a8318054f02c5/href">https://medium.com/media/5f5718704606ca06400a8318054f02c5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q52e9g896Akf9td5Gl2NJA.png" /></figure><h4>Plot Markers</h4><p>To place the plot markers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25336245b475405adaaa031208810f2/href">https://medium.com/media/f25336245b475405adaaa031208810f2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5chjfsQSdutSLVEvLaWNg.png" /></figure><h3>Chapter 4 - Plot labels and tiles</h3><h4>Giving titles</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7604f588eb7f3956bd3936507312ea99/href">https://medium.com/media/7604f588eb7f3956bd3936507312ea99/href</a></iframe><p>By using the <strong>loc=</strong> parameter, we can select where the title will appear (left, right, centre)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWrMwRPB34qutBpTVKAP3A.png" /></figure><h4>Giving labels</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b04fd8b974630d8ff580dabc5769b06/href">https://medium.com/media/9b04fd8b974630d8ff580dabc5769b06/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1E1U_wEH1Mx8h5vkQ6Uclg.png" /></figure><h3>Chapter 5 - Ticks and Legend</h3><h4><strong>Ticks</strong></h4><p>On axes, data points are marked with ticks, which are also known as tick labels. The data points are automatically marked on the axes by matplotlib, but we can also establish our own axes with ticks and tick labels of our choosing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e05f8825f33e465447b56560612fd3/href">https://medium.com/media/74e05f8825f33e465447b56560612fd3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJwdSXXqPZcYG-xOg6b9Yw.png" /></figure><h4><strong>Legend</strong></h4><p>Plot <strong>legends</strong> give meaning to a visualization, assigning meaning to the various plot elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/662373f364764bd536fe176094992e87/href">https://medium.com/media/662373f364764bd536fe176094992e87/href</a></iframe><blockquote>You may see the legend by default on the upper left. It shows every label that was assigned to each plot. Nevertheless, we may adjust the position.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGsdV7hzlgriI_iALvqBqQ.png" /></figure><h3>Chapter 6 - Different types of graph</h3><h4>Bar Graph</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f6b6601cc16a6c958b2eb9a4668617/href">https://medium.com/media/c1f6b6601cc16a6c958b2eb9a4668617/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfyR2h9S2kwXerzeHmF6Cw.png" /></figure><blockquote>In this instance, the plots actually cross across. consequently, alter the width of the bar graph to make the plots visible.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc90819d13d3ea4a7dfc69343a60d92/href">https://medium.com/media/4dc90819d13d3ea4a7dfc69343a60d92/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gkQOcq2sJZzkpPMqfI-og.png" /></figure><p>We can see that the plots do not overlap right now! and it is very evident.</p><p>To get horizontal bar graph,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d928a4ca822d5f450f315c228d89ef9e/href">https://medium.com/media/d928a4ca822d5f450f315c228d89ef9e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5YW9hlPdW9eVmiLNNJNdA.png" /></figure><h4>Scatter plot</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/294b84246a5c1078cd8677d449016f1b/href">https://medium.com/media/294b84246a5c1078cd8677d449016f1b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1z6Z1sugnVFpJE-q8VPjgQ.png" /></figure><h4>Pie chart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c2c6398e57ee140aa0216ff9f028e80/href">https://medium.com/media/7c2c6398e57ee140aa0216ff9f028e80/href</a></iframe><blockquote><strong>autopct</strong> is used to get the percentage</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*mLpfbe5235ycCXTwlJMlWw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d728df531556eea7ffc9de35f9484028/href">https://medium.com/media/d728df531556eea7ffc9de35f9484028/href</a></iframe><blockquote>Explode is a tool for separating values in pie charts.</blockquote><blockquote>Value 0 is <strong>No Explode</strong></blockquote><blockquote>Value greater than 0 means <strong>Explode</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pw0rMJLu-76nN-VzmBu0uQ.png" /></figure><h3>Chapter 7 — Sub-plots</h3><h4>Creating a sub-plot</h4><p>A subplot is a collection of smaller axes that can coexist in a single figure<strong>(Example:</strong> <strong>Perhaps you wish to layout three plots consecutively or something similar.)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071e2e602f1bb95450814c7236cc46fd/href">https://medium.com/media/071e2e602f1bb95450814c7236cc46fd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpjZJnk2aLrnE5RVQEfc0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823d18e04b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Web APIs in Go with Gin | GORM | Docker]]></title>
            <link>https://medium.com/@13kaushik.k/build-a-web-apis-in-go-with-gin-gorm-docker-9374612f977f?source=rss-9b52cf17847f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9374612f977f</guid>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[grom]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Kaushik K]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 05:51:40 GMT</pubDate>
            <atom:updated>2022-11-02T05:51:40.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comprehensive Guide for building Web APIs with Go and Gin</h4><p>Go is a statically typed, compiled programming language designed at Google.It resembles something from C-Language. It is a quick and effective programming language that was launched in 2012.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*za7LC8zdr5Vxn_Q_SjJJyQ.png" /><figcaption>source: Go’s <a href="https://go.dev/solutions/#case-studies">Documentation</a></figcaption></figure><p>As a result, I’ll be demonstrating how to create an API using GO, Gin, and Docker in this article. I’ll be utilising Postgre SQL in this instance.</p><p>From the <a href="https://github.com/gin-gonic/gin"><em>documentation</em></a></p><blockquote>Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to <a href="https://github.com/julienschmidt/httprouter">http router</a>. If you need performance and good productivity, you will love Gin.</blockquote><h4>What are we going to build?</h4><p>It will be a really vintage project. A basic User API will be created by us. Simple CRUD operations would be implemented.</p><h4><strong>Installation</strong></h4><p>Install Postgres using</p><pre><a href="https://www.enterprisedb.com/downloads/postgres-postgresql-downloads"><em>https://www.enterprisedb.com/downloads/postgres-postgresql-downloads</em></a></pre><p>Install Go using</p><pre><a href="https://go.dev/doc/install">https://go.dev/doc/install</a></pre><p>Install Docker using</p><pre><a href="https://docs.docker.com/desktop/install/mac-install/">https://docs.docker.com/desktop/install/mac-install/</a></pre><h4>Project Setup</h4><p>We will start our project and install the necessary components first.</p><pre>$ mkdir go_api<br>$ cd go_api<br>$ code .<br>$ go mod init github.com/YOUR_GIT_USERNAME/go_api</pre><blockquote><strong><em>NOTE:</em></strong><em> Replace YOUR_GIT_USERNAME with your Github username.</em></blockquote><blockquote>You don’t have to create the git repository right away; you may do it whenever you like.</blockquote><p>Now let’s install Gin; do so using the vs-code terminal.</p><pre>go get -u github.com/gin-gonic/gin</pre><h4>Minimal Gin App</h4><p>Make a new file called main.go.</p><blockquote>main.go as a file is not required.</blockquote><blockquote>However, executables need a main package containing a function named func main().</blockquote><blockquote>You may name your file whatever you wish.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21e7315c6f7dfc4de5659e47410cd57e/href">https://medium.com/media/21e7315c6f7dfc4de5659e47410cd57e/href</a></iframe><p>Typing go run main.go(or go run .)(i.e go run &lt;filename&gt;.go) in the terminal will start the programme.</p><p>This is what you should see:</p><pre>[GIN-debug] Listening and serving HTTP on :8080</pre><p>Go to http://localhost:8080/ in any web browser once it has been launched to observe how the app works.</p><h4><strong>File structure</strong></h4><p>Let’s proceed with the project’s final organisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Y0pRghC22oUAWLAfmbP_qA.png" /><figcaption>File structure</figcaption></figure><p>Now, coding time has arrived.</p><pre>config/db.go</pre><blockquote>Here, we usually do the database configurations.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f64d7ba52fcaf215971389075c84b97/href">https://medium.com/media/1f64d7ba52fcaf215971389075c84b97/href</a></iframe><pre>models/user.go</pre><blockquote>Here, we define the database’s architecture.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e84507338684035ba862965278ee8dd7/href">https://medium.com/media/e84507338684035ba862965278ee8dd7/href</a></iframe><pre>docker-compose.yml</pre><blockquote>A Docker application’s services, networks, and volumes are specified in the Compose file, which is a YAML file.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe1f97bd585e7a4570eeb7159c662845/href">https://medium.com/media/fe1f97bd585e7a4570eeb7159c662845/href</a></iframe><p>Now, Run the command in the terminal</p><pre>sudo docker-compose up --build</pre><p>Now, we will code other files as well</p><pre>controller/user.go</pre><blockquote>Here, functions like create, remove, and update are created.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e62eafe03fa44797077906a7c54aa3a/href">https://medium.com/media/5e62eafe03fa44797077906a7c54aa3a/href</a></iframe><pre>routes/db.go</pre><blockquote>The routes for calling the functions are defined here.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1731481701da3a8c7d61b04b033eb39/href">https://medium.com/media/b1731481701da3a8c7d61b04b033eb39/href</a></iframe><pre>main.go</pre><blockquote>The main function at which the programme begins!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebb43d06b3e250b0a71be0d3c8427d1e/href">https://medium.com/media/ebb43d06b3e250b0a71be0d3c8427d1e/href</a></iframe><p>Hurray !! Finally, we are finished, and we can execute our code.</p><blockquote>Open your terminal and enter the following command to run the code:</blockquote><pre>go run main.go</pre><p>we get something like,</p><pre>[GIN-debug] Listening and serving HTTP on :8080</pre><p>You may now enter the URL in Postman.</p><pre>1. To get all user&#39;s:<a href="http://127.0.0.1:8080/getalluser"><br>http://127.0.0.1:8080/getalluser</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWiLZe93D3GhG1qrjaJl3g.png" /><figcaption>To get all users</figcaption></figure><pre>2. To create user&#39;s:<br><a href="http://127.0.0.1:8080/createuser">http://127.0.0.1:8080/getalluser</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piOK71B0L2WOvtUP-wmHgQ.png" /></figure><pre>3. To delete user&#39;s:<br>http://127.0.0.1:8080/deleteuser/1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKPOeu0d2PMUep0BJ8yYRg.png" /><figcaption>To delete user’s</figcaption></figure><pre>4. To get specific user:<br>http://127.0.0.1:8080/getspecificuser/3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-E8jnNSHxaLeY5QNDQ4KIA.png" /><figcaption>To get specific user</figcaption></figure><pre>5. To update user:<br>http://127.0.0.1:8080/updateuser/3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yA7MrN4BsYESLGSveA3x3A.png" /><figcaption>To update user</figcaption></figure><p>I hope you enjoyed reading this post on how to create a straightforward API using GO and GIN.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9374612f977f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>