<?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"><channel><title><![CDATA[chopcoding]]></title><description><![CDATA[🔥 Created BlogToNFT(Featured at Product Hunt) | 💼 Product Management |Solutions Consultant @ Aurochs|Minted deck of tux NFT]]></description><link>https://blog.krtk.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 21:47:53 GMT</lastBuildDate><atom:link href="https://blog.krtk.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How Repomix Made My AI Coding Workflow So Much Easier]]></title><description><![CDATA[Repomix: The Tool That Helps Me Talk to AI Better
Lately, I’ve been using a tool called Repomix a lot—and it’s quickly become a regular part of how I work. If you ever try to explain your codebase to an AI assistant like ChatGPT or Claude, you know h...]]></description><link>https://blog.krtk.dev/how-repomix-made-my-ai-coding-workflow-so-much-easier</link><guid isPermaLink="true">https://blog.krtk.dev/how-repomix-made-my-ai-coding-workflow-so-much-easier</guid><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[aitools]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Fri, 21 Mar 2025 09:41:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742550071184/8b5bc064-49dd-473d-bb97-d6b60ecbdfd1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-repomix-the-tool-that-helps-me-talk-to-ai-better">Repomix: The Tool That Helps Me Talk to AI Better</h2>
<p>Lately, I’ve been using a tool called <a target="_blank" href="https://repomix.com/"><strong>Repomix</strong></a> a lot—and it’s quickly become a regular part of how I work. If you ever try to explain your codebase to an AI assistant like ChatGPT or Claude, you know how hard it can be to give proper context. That’s where Repomix shines.</p>
<h3 id="heading-what-is-repomix">What Is Repomix?</h3>
<p>Repomix is a small command-line tool that <strong>packs your codebase into a format that’s easy for AI to understand</strong>. You just point it to your repository (or even a remote GitHub repo), and it creates a clean, structured file that includes your code, directory structure, and even file summaries—if you want.</p>
<p>You can choose to:</p>
<ul>
<li><p>Include or ignore certain files</p>
</li>
<li><p>Show or hide line numbers</p>
</li>
<li><p>Remove comments and empty lines</p>
</li>
<li><p>Output in <strong>XML</strong>, <strong>Markdown</strong>, or <strong>Plain text</strong></p>
</li>
</ul>
<p>This makes it really easy to <strong>share the full picture of your project with an AI</strong>. Whether you’re asking for a code review, help refactoring, or debugging support—Repomix gives the AI everything it needs to help you better.</p>
<h3 id="heading-how-i-use-it">How I Use It</h3>
<p>Before Repomix, I used to copy-paste random files into the chat window when asking for help from AI. That approach rarely worked well, because the AI didn’t know the full story—it missed out on other files, related components, or helper functions.</p>
<p>Now, I just run:</p>
<pre><code class="lang-bash">npx repomix
</code></pre>
<p>And it creates a file called <code>repomix-output.txt</code> in my project folder. I upload that to the AI tool with a simple message like:</p>
<blockquote>
<p>“This file contains all the files in the repository combined into one. I want to refactor the code, so please review it first.”</p>
</blockquote>
<p>After that, the AI gives me a <strong>complete review</strong>, not just of one file—but the entire project. It feels like I’m finally speaking the AI’s language.</p>
<h3 id="heading-why-it-works-so-well">Why It Works So Well</h3>
<ul>
<li><p>✅ <strong>AI-Optimized Output</strong>: The packed file includes structure and summaries that make it easy for AI to process.</p>
</li>
<li><p>✅ <strong>Git-Aware</strong>: It respects your <code>.gitignore</code>, so it doesn’t include files you wouldn’t commit.</p>
</li>
<li><p>✅ <strong>Security-Focused</strong>: It checks for secrets using Secretlint, which gives me peace of mind.</p>
</li>
<li><p>✅ <strong>Token Counting</strong>: It shows token usage, so I know if my prompt might be too long.</p>
</li>
</ul>
<h3 id="heading-bonus-you-dont-even-have-to-install-it">Bonus: You Don’t Even Have to Install It</h3>
<p>If you’re in a hurry, you can just run:</p>
<pre><code class="lang-bash">npx repomix
</code></pre>
<p>It will pull and process your remote GitHub repo—<strong>no setup required</strong>.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>As someone who uses AI tools daily, <strong>Repomix saves me time and effort</strong>. It bridges the gap between messy, scattered prompts and clear, structured communication with AI. If you’re building anything with code and want better help from AI assistants, <strong>give Repomix a try</strong>. It might just become your favorite sidekick too.  </p>
<p>Check out <a target="_blank" href="https://repomix.com/">https://repomix.com/</a></p>
]]></content:encoded></item><item><title><![CDATA[Using clickhouse to transform tick data into OHLC]]></title><description><![CDATA[Introduction
In the world of finance, tick data represents the heartbeat of the market, capturing every price change and transaction that occurs. This granular data is invaluable for high-frequency trading strategies, market analysis, and understandi...]]></description><link>https://blog.krtk.dev/using-clickhouse-to-transform-tick-data-into-ohlc</link><guid isPermaLink="true">https://blog.krtk.dev/using-clickhouse-to-transform-tick-data-into-ohlc</guid><category><![CDATA[ClickHouse]]></category><category><![CDATA[dataanalytics]]></category><category><![CDATA[SQL]]></category><category><![CDATA[newbie]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Wed, 14 Feb 2024 07:14:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707894722793/2da7fb10-5216-44e9-9d7e-cff02c0e9ea1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In the world of finance, tick data represents the heartbeat of the market, capturing every price change and transaction that occurs. This granular data is invaluable for high-frequency trading strategies, market analysis, and understanding liquidity and volatility. Processing and analyzing tick data, however, requires powerful data management solutions. This is where ClickHouse, an open-source columnar database optimized for fast, real-time analytics, shines. In this article, we'll explore how to leverage ClickHouse to process and analyze tick data to extract Open, High, Low, Close (OHLC) values—a fundamental component of financial analysis.</p>
<h3 id="heading-understanding-tick-data">Understanding Tick Data</h3>
<p>Tick data is composed of individual trades or quote changes including details such as price, volume, and transaction time. Unlike aggregated data, such as daily summaries, tick data provides a microscopic view of market behavior, enabling analysts to uncover patterns and trends not visible at higher levels of aggregation.</p>
<h3 id="heading-generating-sample-tick-data">Generating Sample Tick Data</h3>
<p>To demonstrate the process of analyzing tick data with ClickHouse, we first generate a sample dataset. Our dataset simulates a single trading day's activity, capturing the price and volume for each second of an 8-hour trading session. This results in approximately 28,800 data points, offering a detailed canvas to illustrate our analysis.<br />You can download the file <a target="_blank" href="https://gist.github.com/kartikpuri95/93ec6b6683b794fda603559f53b0233f">here</a></p>
<h3 id="heading-loading-data-into-clickhouse">Loading Data into ClickHouse</h3>
<p>With our sample tick data in hand, the next step is to load it into ClickHouse for analysis. First, we define a table schema and create the table that matches our data's structure:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> tick_data 
( <span class="hljs-built_in">Time</span> DateTime, Price Float64, Volume UInt32 ) 
<span class="hljs-keyword">ENGINE</span> = MergeTree() <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-built_in">Time</span>;
</code></pre>
<p>This schema is designed to efficiently store and query our tick data. To import the data, we use the following command, which pipes our CSV file directly into the ClickHouse client, connecting securely to our ClickHouse instance:</p>
<pre><code class="lang-sql">cat sample_tick_data_updated.csv | ./clickhouse client <span class="hljs-comment">--host &lt;your-cloud-url&gt;.aws.clickhouse.cloud --secure --password 'your_password'</span>
</code></pre>
<h3 id="heading-querying-ohlc-values">Querying OHLC Values</h3>
<p>Once the data is loaded, we can proceed to extract OHLC values for desired time intervals. The following SQL query calculates these values for each minute of trading activity:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  toStartOfMinute(<span class="hljs-built_in">Time</span>) <span class="hljs-keyword">as</span> data_captured_datetime,
  argMin(Price, <span class="hljs-built_in">Time</span>) <span class="hljs-keyword">as</span> <span class="hljs-keyword">open</span>,
  <span class="hljs-keyword">max</span>(Price) <span class="hljs-keyword">as</span> <span class="hljs-keyword">high</span>,
  <span class="hljs-keyword">min</span>(Price) <span class="hljs-keyword">as</span> <span class="hljs-keyword">low</span>,
  argMax(Price, <span class="hljs-built_in">Time</span>) <span class="hljs-keyword">as</span> <span class="hljs-keyword">close</span>,
  <span class="hljs-keyword">sum</span>(Volume) <span class="hljs-keyword">as</span> total_volume
<span class="hljs-keyword">FROM</span> tick_data
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> data_captured_datetime
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> data_captured_datetime;
</code></pre>
<p>This query groups the data into one-minute intervals, then calculates the opening price, highest price, lowest price, closing price, and total volume for each interval.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1707894442246/9bb3ebe9-c56c-45e5-a2bf-d2a46a8cddac.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-understanding-the-query">Understanding the Query</h3>
<ul>
<li><p><code>toStartOfMinute(Time)</code>: This function rounds down the transaction time to the start of the minute, serving as our grouping mechanism.</p>
</li>
<li><p><code>argMin</code> and <code>argMax</code>: These functions identify the opening and closing prices within each minute by finding the earliest and latest transactions, respectively.</p>
</li>
<li><p><code>max</code> and <code>min</code>: These aggregate functions calculate the highest and lowest prices within each interval.</p>
</li>
<li><p><code>sum(Volume)</code>: Summarizes the total trading volume for each minute, providing insight into market activity.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Analyzing tick data with ClickHouse provides a powerful toolkit for financial analysts and traders. By leveraging ClickHouse's efficient data storage and fast querying capabilities, we can uncover detailed insights into market dynamics, support decision-making processes, and develop sophisticated trading strategies. This article has demonstrated the process from data preparation to analysis, highlighting the ease and efficiency of using ClickHouse for financial data analytics.  </p>
<p>You can connect me on :</p>
<p>💼 Linkedin: <a target="_blank" href="https://www.linkedin.com/in/kartikchop/">https://www.linkedin.com/in/kartikchop/</a></p>
<p>🐦 Twitter: <a target="_blank" href="https://twitter.com/chopcoding">https://twitter.com/chopcoding</a></p>
]]></content:encoded></item><item><title><![CDATA[Boosting JSON Performance in Python: A Deep Dive into orjson]]></title><description><![CDATA[Introduction
Background on JSON in Python
JSON, short for JavaScript Object Notation, has become a ubiquitous data interchange format, owing to its simplicity and lightweight nature. In Python, the standard library provides a module aptly named json ...]]></description><link>https://blog.krtk.dev/boosting-json-performance-in-python-a-deep-dive-into-orjson</link><guid isPermaLink="true">https://blog.krtk.dev/boosting-json-performance-in-python-a-deep-dive-into-orjson</guid><category><![CDATA[Python]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[python projects]]></category><category><![CDATA[Flask Framework]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Fri, 03 Nov 2023 07:01:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698927601970/19ef7ce1-7cae-49ec-839a-b048ab1955d8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction"><strong>Introduction</strong></h1>
<h2 id="heading-background-on-json-in-python"><strong>Background on JSON in Python</strong></h2>
<p>JSON, short for JavaScript Object Notation, has become a ubiquitous data interchange format, owing to its simplicity and lightweight nature. In Python, the standard library provides a module aptly named <code>json</code> to encode and decode JSON data. It's widely used due to its easy integration and familiar syntax. Developers often lean on it to parse and produce JSON content for tasks ranging from simple data storage to API communication.</p>
<p>However, while the standard <code>json</code> module is sufficient for many applications, there are instances where performance bottlenecks or specific feature needs arise. As data processing demands grow, with applications handling large volumes of data or requiring faster serialization and deserialization, the limitations of the standard library can become apparent.</p>
<h2 id="heading-the-need-for-alternatives-introduction-to-orjson"><strong>The Need for Alternatives: Introduction to orjson</strong></h2>
<p>Enter <code>orjson</code>, a modern, performance-oriented JSON library written in Rust and designed to interface seamlessly with Python. It doesn't merely bring performance improvements to the table; <code>orjson</code> also introduces new features and enhanced flexibility, addressing many of the pain points developers might encounter with the standard <code>json</code> module. For instance, <code>orjson</code> offers support for serializing dataclasses, datetimes, and even numpy arrays, all while being stringent about compliance with the JSON specification.</p>
<p>In essence, <code>orjson</code> emerges as a compelling alternative for those looking to push the boundaries of JSON processing in Python, marrying the speed of Rust with the expressiveness and dynamism of Python. As we dive deeper into this article, we'll explore why and how one might consider migrating to <code>orjson</code> and the benefits it brings.</p>
<h1 id="heading-why-migrate-to-orjson"><strong>Why Migrate to orjson?</strong></h1>
<h2 id="heading-performance-benchmarks"><strong>Performance Benchmarks</strong></h2>
<p>One of the most significant selling points of <code>orjson</code> is its impressive performance. Leveraging the power and efficiency of Rust, <code>orjson</code> offers serialization and deserialization speeds that often surpass those of the standard <code>json</code> module. In various benchmarks, <code>orjson</code> consistently outperforms not just the standard library, but also other third-party JSON libraries in Python.</p>
<p>For instance, in tests involving large datasets, <code>orjson</code> has been shown to serialize data up to 3x faster than the standard <code>json</code> library and deserialize even quicker. For applications where millisecond-level differences matter – such as real-time data processing systems, high-frequency trading platforms, or intensive web services – this performance boost can be a game-changer.</p>
<h2 id="heading-features-and-benefits-over-standard-json-library"><strong>Features and Benefits Over Standard JSON Library</strong></h2>
<p>Beyond raw speed, <code>orjson</code> also offers a suite of features that make it stand out:</p>
<ol>
<li><p><strong>Extended Serialization Support:</strong> Out of the box, <code>orjson</code> supports serializing many Python standard library types that the default <code>json</code> library doesn't. This includes but is not limited to, dataclasses, datetimes, and UUIDs.</p>
</li>
<li><p><strong>Strict Compliance:</strong> While being feature-rich, <code>orjson</code> remains strict about compliance with the JSON specification, ensuring that the data it handles remains universally interpretable.</p>
</li>
<li><p><strong>Option Flags:</strong> Developers can use option flags to customize serialization and deserialization behavior. For example, you can opt to use the <code>ORJSON</code> option to serialize datetimes in RFC 3339 format or use the <code>STRICT_INTEGER</code> option to prevent any accidental float serialization of integers.</p>
</li>
<li><p><strong>Compact Representation:</strong> By default, <code>orjson</code> outputs a more compact JSON representation by omitting whitespace, which can result in faster network transmission and reduced storage costs.</p>
</li>
<li><p><strong>Memory Efficiency:</strong> Given its Rust underpinnings, <code>orjson</code> exhibits better memory management, especially beneficial when dealing with large data payloads.</p>
</li>
<li><p><strong>Safety:</strong> Rust's strong safety guarantees translate into fewer runtime errors and crashes, making <code>orjson</code> not just fast but also reliable.</p>
</li>
</ol>
<p>In summary, while the standard <code>json</code> module serves many applications adequately, there's a clear case to be made for migrating to <code>orjson</code>. Whether you're after speed, richer features, or both, <code>orjson</code> offers a compelling package that can elevate your JSON processing capabilities in Python.</p>
<h1 id="heading-migration-steps"><strong>Migration Steps:</strong></h1>
<p>Migrating to <code>orjson</code> is a straightforward process. Here’s a step-by-step guide to ensure a smooth transition:</p>
<h2 id="heading-installation-and-setup"><strong>Installation and Setup</strong></h2>
<p>Before using <code>orjson</code>, it must first be installed. It’s as simple as running:</p>
<pre><code class="lang-python">pip install orjson
</code></pre>
<p>Once installed, you can start incorporating it into your code by importing it, just as you would with the standard <code>json</code> library:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> orjson
</code></pre>
<p><strong>Converting Serialization (dumps)</strong></p>
<p>If you're used to serializing objects into JSON strings using the standard library's <code>dumps</code> method, the transition is quite seamless:</p>
<p><em>Standard JSON Library:</em></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
json_string = json.dumps(obj)
</code></pre>
<p><em>With orjson:</em></p>
<pre><code class="lang-python">json_string = orjson.dumps(obj).decode(<span class="hljs-string">'utf-8'</span>)
</code></pre>
<p>Note: <code>orjson.dumps()</code> returns bytes, so if you need a string, you'll need to decode it.</p>
<p><strong>Converting Deserialization (loads)</strong></p>
<p>Similarly, deserializing JSON strings into Python objects is just as intuitive:</p>
<p><em>Standard JSON Library:</em></p>
<pre><code class="lang-python">obj = json.loads(json_string)
</code></pre>
<p><em>With orjson:</em></p>
<pre><code class="lang-python">obj = orjson.loads(json_string)
</code></pre>
<p><strong>Handling Edge Cases or Differences in Behavior</strong></p>
<p>While <code>orjson</code> aims to be as compatible as possible with the standard <code>json</code> library, there are certain differences and edge cases you should be aware of:</p>
<ol>
<li><p><strong>Datetime Serialization:</strong> As mentioned, <code>orjson</code> can serialize datetimes out of the box, but the format might differ from what you're used to. You might need to adjust the option flags or post-process the resulting string if a specific format is required.</p>
</li>
<li><p><strong>Non-string Keys in Dictionaries:</strong> The standard <code>json</code> library raises a <code>TypeError</code> when it encounters non-string keys in dictionaries. <code>orjson</code> will serialize integer keys but will still raise errors for other non-string types.</p>
</li>
<li><p><strong>Handling of Large Integers:</strong> Large integers, which can't be precisely represented by JavaScript's Number type, are serialized as strings by <code>orjson</code>. This behavior ensures data fidelity but may be unexpected if you're not prepared for it.</p>
</li>
<li><p><strong>Custom Encoders:</strong> If you use custom encoders with the standard <code>json</code> library's <code>dumps</code> method, you'll need to adjust your approach, as <code>orjson</code> doesn't support the <code>default</code> argument. Instead, preprocess the data to make it serializable by <code>orjson</code>.</p>
</li>
</ol>
<p>To address these differences, always thoroughly test the new setup with a variety of your application's typical payloads before fully committing to the transition. This proactive approach will help you identify and resolve any behavioral differences or edge cases that might arise during the migration.</p>
<h1 id="heading-potential-pitfalls-and-how-to-overcome-them"><strong>Potential Pitfalls and How to Overcome Them</strong></h1>
<p>Switching to a new library, even one as performant as <code>orjson</code>, comes with its own set of challenges. Awareness of these pitfalls is the first step in addressing them. Here we'll explore some of these potential issues and provide solutions to ensure a seamless migration.</p>
<h2 id="heading-differences-in-default-behaviors"><strong>Differences in Default Behaviors</strong></h2>
<p><em>1. Datetime Handling:</em><br />By default, <code>orjson</code> handles datetime objects differently than the standard <code>json</code> library.</p>
<p><em>Standard JSON Library:</em> Throws an error unless you provide a custom handler.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json, datetime
date = datetime.datetime.now()
<span class="hljs-comment"># This will raise an error</span>
json.dumps(date)
</code></pre>
<p><em>orjson:</em> Serializes datetime objects by default.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> orjson, datetime
date = datetime.datetime.now()
<span class="hljs-comment"># This works out of the box</span>
orjson_string = orjson.dumps(date)
</code></pre>
<p><em>Solution:</em> If you want a specific datetime format, preprocess datetime objects before serialization or post-process the serialized data.</p>
<p><em>2. Handling of Large Integers:</em><br />As previously mentioned, <code>orjson</code> will serialize very large integers as strings to ensure JavaScript compatibility.</p>
<p><em>Solution:</em> If your application expects integers to always be serialized as numbers, you may need to post-process and convert strings back to integers in contexts where large numbers are used.</p>
<p><strong>Special Considerations for Custom Objects</strong></p>
<p><em>1. Custom Encoders:</em><br />Many developers use the <code>default</code> argument in the standard library's <code>dumps</code> method to handle custom objects. Since <code>orjson</code> doesn't support this, an alternative approach is required.</p>
<p><em>Example with standard JSON:</em></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomClass</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, value</span>):</span>
        self.value = value

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">encode_custom</span>(<span class="hljs-params">obj</span>):</span>
    <span class="hljs-keyword">if</span> isinstance(obj, CustomClass):
        <span class="hljs-keyword">return</span> {<span class="hljs-string">"value"</span>: obj.value}
    <span class="hljs-keyword">raise</span> TypeError(<span class="hljs-string">"Unknown type"</span>)

json_string = json.dumps(CustomClass(<span class="hljs-number">42</span>), default=encode_custom)
</code></pre>
<p><em>Solution with orjson:</em> Preprocess the data.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">to_serializable</span>(<span class="hljs-params">obj</span>):</span>
    <span class="hljs-keyword">if</span> isinstance(obj, CustomClass):
        <span class="hljs-keyword">return</span> {<span class="hljs-string">"value"</span>: obj.value}
    <span class="hljs-keyword">return</span> obj

data = to_serializable(CustomClass(<span class="hljs-number">42</span>))
orjson_string = orjson.dumps(data)
</code></pre>
<p><em>2. Non-string Dictionary Keys:</em><br />While <code>orjson</code> can handle integer dictionary keys, it will raise errors for other non-string types, much like the standard library.</p>
<p><em>Solution:</em> Convert non-string keys to strings (or integers when suitable) before serialization.</p>
<p><strong><em>Original Dictionary with Mixed Key Types:</em></strong></p>
<pre><code class="lang-python">data = {
    <span class="hljs-number">42</span>: <span class="hljs-string">"Integer key"</span>,
    (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>): <span class="hljs-string">"Tuple key"</span>,
    datetime.datetime.now(): <span class="hljs-string">"Datetime key"</span>
}
</code></pre>
<p><strong>Converting Non-string Keys to Strings:</strong></p>
<p>You can use a dictionary comprehension to process the keys:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> datetime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">convert_key</span>(<span class="hljs-params">key</span>):</span>
    <span class="hljs-comment"># Convert tuple keys to a string representation</span>
    <span class="hljs-keyword">if</span> isinstance(key, tuple):
        <span class="hljs-keyword">return</span> <span class="hljs-string">'_'</span>.join(map(str, key))
    <span class="hljs-comment"># Convert datetime keys to a string representation</span>
    <span class="hljs-keyword">elif</span> isinstance(key, datetime.datetime):
        <span class="hljs-keyword">return</span> key.isoformat()
    <span class="hljs-comment"># Convert all other non-string keys to strings</span>
    <span class="hljs-keyword">elif</span> <span class="hljs-keyword">not</span> isinstance(key, str):
        <span class="hljs-keyword">return</span> str(key)
    <span class="hljs-keyword">return</span> key

processed_data = {convert_key(k): v <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> data.items()}
</code></pre>
<p>After this processing step, the <code>processed_data</code> dictionary will have string keys:</p>
<pre><code class="lang-python">{
    <span class="hljs-string">'42'</span>: <span class="hljs-string">'Integer key'</span>,
    <span class="hljs-string">'1_2'</span>: <span class="hljs-string">'Tuple key'</span>,
    <span class="hljs-string">'2023-11-02T14:45:26.845123'</span>: <span class="hljs-string">'Datetime key'</span>
}
</code></pre>
<p>Now, you can serialize this processed data with <code>orjson</code> without any errors:</p>
<pre><code class="lang-python">orjson_string = orjson.dumps(processed_data)
</code></pre>
<p>Note: The <code>convert_key</code> function provides a general approach to handle various non-string key types, but you might want to adjust or expand it based on the specific types of keys you expect in your dictionaries.</p>
<p><strong>In Conclusion,</strong> while <code>orjson</code> provides significant performance improvements, it's essential to be aware of these nuances and adjust your code accordingly. A well-thought-out migration plan, backed by thorough testing, will ensure you reap the benefits of <code>orjson</code> without compromising on data integrity or encountering unexpected behaviors.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>The realm of data serialization and deserialization in Python has evolved considerably with the introduction of libraries like <code>orjson</code>. While Python's standard JSON library has served the community reliably for years, the rapidly changing demands of modern applications necessitate looking into high-performance alternatives.</p>
<p><strong>Benefits of Migrating to orjson:</strong></p>
<ol>
<li><p><strong>Performance</strong>: As highlighted in earlier sections, <code>orjson</code> markedly outperforms the standard library in serialization and deserialization tasks, which can be especially crucial for high-throughput applications.</p>
</li>
<li><p><strong>Extended Data Type Support</strong>: <code>orjson</code> goes beyond the standard library in supporting a broader range of Python data types natively, which can simplify code and reduce custom serialization needs.</p>
</li>
<li><p><strong>Precision</strong>: With its default decimal serialization for numbers, <code>orjson</code> offers enhanced precision, a vital feature for applications where accuracy is non-negotiable, such as in financial systems.</p>
</li>
</ol>
<p><strong>Challenges of the Migration:</strong></p>
<ol>
<li><p><strong>Learning Curve</strong>: Like adopting any new library or tool, there's an initial overhead in terms of understanding <code>orjson</code>'s nuances and features.</p>
</li>
<li><p><strong>Handling Edge Cases</strong>: Developers might encounter certain edge cases where <code>orjson</code> behaves differently than the standard library. Proper testing and awareness of these differences are essential.</p>
</li>
<li><p><strong>Custom Objects and Default Behaviors</strong>: While <code>orjson</code> supports a broader range of types, there might still be a need for custom serialization methods for certain objects. Being cognizant of the default behaviors and differences is vital.</p>
</li>
</ol>
<p>In conclusion, while <code>orjson</code> presents numerous advantages, it's paramount for developers to weigh these benefits against the challenges. The decision to migrate should stem from a clear understanding of a project's specific needs and a thorough evaluation of how the library aligns with those requirements. Every tool has its unique strengths, and <code>orjson</code> is no exception. By carefully considering the project's demands and testing the waters before a full-fledged migration, developers can make the most of what <code>orjson</code> has to offer.  </p>
<p>orjson link : <a target="_blank" href="https://github.com/ijl/orjson">https://github.com/ijl/orjson</a></p>
<p>You can connect me on :</p>
<p>💼 Linkedin: <a target="_blank" href="https://www.linkedin.com/in/kartikchop/">https://www.linkedin.com/in/kartikchop/</a></p>
<p>🐦 Twitter: <a target="_blank" href="https://twitter.com/chopcoding">https://twitter.com/chopcoding</a></p>
]]></content:encoded></item><item><title><![CDATA[Python Functions: Writing Better Code with Ease]]></title><description><![CDATA[Introduction
Programming is all about functions. They help you organize and reuse code. Python is a popular programming language that has a lot of tools for working with functions. In this guide, we're going to explore Python functions from the basic...]]></description><link>https://blog.krtk.dev/python-functions-writing-better-code-with-ease</link><guid isPermaLink="true">https://blog.krtk.dev/python-functions-writing-better-code-with-ease</guid><category><![CDATA[Python]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[python projects]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Thu, 21 Sep 2023 05:59:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695275682287/547bc47d-d944-4510-9496-29e935156523.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<p>Programming is all about functions. They help you organize and reuse code. Python is a popular programming language that has a lot of tools for working with functions. In this guide, we're going to explore Python functions from the basics to advanced techniques. We'll give you some tips to make it more interesting!</p>
<h2 id="heading-python-function-fundamentals"><strong>Python Function Fundamentals</strong></h2>
<h3 id="heading-how-to-define-a-function"><strong>How to define a function?</strong></h3>
<p>In the Python programming language, functions are defined using the def keyword. As an example, we have already demonstrated a simple case:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> random

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">animal_sound</span>():</span>
    sounds = [<span class="hljs-string">"Meow"</span>, <span class="hljs-string">"Woof"</span>, <span class="hljs-string">"Moo"</span>, <span class="hljs-string">"Quack"</span>, <span class="hljs-string">"Oink"</span>]
    <span class="hljs-keyword">return</span> random.choice(sounds)
</code></pre>
<p>This article explores the topic of defining functions in Python, including parameters and return values. The code sample demonstrates the use of the 'def' keyword to define a function called 'sum()', and the keyword 'return' is used to indicate that the function returns a value.</p>
<h3 id="heading-parameterized-functions">Parameterized Functions</h3>
<p>Function parameters in Python are like these little placeholders that you can use to pass data into a function. They're really helpful for making your functions more versatile and customizable. Here's how to use them!</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">birthday_wish</span>(<span class="hljs-params">name, age</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">f"🎉 Happy <span class="hljs-subst">{age}</span> Birthday, <span class="hljs-subst">{name}</span>! May your day be filled with joy and your year with adventures! 🎂🎈"</span>

message = birthday_wish(<span class="hljs-string">"Chop"</span>, <span class="hljs-number">25</span>)
print(message)  <span class="hljs-comment"># 🎉 Happy 25th Birthday, Emma! May your day be filled with joy and your year with adventures! 🎂🎈</span>
</code></pre>
<p>The <code>birthday_wish</code> function takes two parameters: <code>name</code> and <code>age</code>, It then combines these parameters to create a personalized birthday wish.</p>
<p>Now, when you call <code>birthday_wish("Chop", "25th")</code>, the first argument "Chop" is assigned to <code>name</code>, and the second argument "25th" is assigned to <code>age</code>, resulting in a customized birthday message.</p>
<h3 id="heading-ia"> </h3>
<p>Flexible function <strong>Parameters with Defaults</strong></p>
<p>In Python, you have the flexibility to specify default values for function parameters. This feature makes parameters optional when calling the function. If no value is provided for an optional parameter, it automatically adopts the default value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">order_pizza</span>(<span class="hljs-params">pizza_size, toppings=[]</span>):</span>
    pizza = {<span class="hljs-string">"size"</span>: pizza_size, <span class="hljs-string">"toppings"</span>: toppings}
    <span class="hljs-keyword">return</span> pizza
</code></pre>
<p>In this example, the <code>order_pizza</code> function takes two parameters: <code>pizza_size</code> and <code>toppings</code>. The <code>toppings</code> parameter has a default value of an empty list, indicating that if no toppings are specified, the pizza will be ordered plain.</p>
<p>Now, let's see how this function is used:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Ordering a plain pizza with the default toppings</span>
plain_pizza = order_pizza(<span class="hljs-string">"large"</span>)
print(plain_pizza)

<span class="hljs-comment"># Ordering a customized pizza with extra toppings</span>
custom_pizza = order_pizza(<span class="hljs-string">"medium"</span>, [<span class="hljs-string">"pepperoni"</span>, <span class="hljs-string">"mushrooms"</span>])
print(custom_pizza)
</code></pre>
<p>In the first call to <code>order_pizza("large")</code>, no toppings are specified, so the function defaults to ordering a plain pizza with an empty toppings list. In the second call to <code>order_pizza("medium", ["pepperoni", "mushrooms"])</code>, custom toppings are provided, resulting in a customized pizza order.</p>
<p>This example showcases how default parameters can make a function more versatile by allowing users to provide additional information when needed while providing sensible default behaviour when information is missing.</p>
<h3 id="heading-keyword-arguments-in-python-functions"><strong>Keyword Arguments in Python Functions</strong></h3>
<p>Python provides a powerful feature known as keyword arguments that allows you to pass arguments to a function by specifying parameter names as keywords. This feature not only enhances code readability but also offers flexibility when dealing with functions that have multiple parameters.</p>
<p>Consider the following example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">order_pizza</span>(<span class="hljs-params">pizza_size, toppings=[]</span>):</span>
    pizza = {<span class="hljs-string">"size"</span>: pizza_size, <span class="hljs-string">"toppings"</span>: toppings}
    <span class="hljs-keyword">return</span> pizza
</code></pre>
<p>In this function, <code>order_pizza</code>, we have two parameters: <code>pizza_size</code> and <code>toppings</code>. The <code>toppings</code> parameter has a default value of an empty list.</p>
<p>Now, let's explore how we can use keyword arguments to make pizza orders more explicit and clear:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Ordering a plain pizza with the default toppings using keyword arguments</span>
plain_pizza = order_pizza(pizza_size=<span class="hljs-string">"large"</span>)
print(plain_pizza)

<span class="hljs-comment"># Ordering a customized pizza with extra toppings using keyword arguments</span>
custom_pizza = order_pizza(pizza_size=<span class="hljs-string">"medium"</span>, toppings=[<span class="hljs-string">"pepperoni"</span>, <span class="hljs-string">"mushrooms"</span>])
print(custom_pizza)
</code></pre>
<p>By using keyword arguments, we explicitly specify which value corresponds to each parameter when calling the <code>order_pizza</code> function. This not only improves code clarity but also allows us to provide arguments out of order if needed.</p>
<p>Keyword arguments are especially valuable when dealing with functions that have many parameters or when you want to make it crystal clear which argument corresponds to which parameter. They offer a powerful way to write more readable and maintainable code in Python.</p>
<h3 id="heading-variable-length-argument-lists-in-python-functions"><strong>Variable-Length Argument Lists in Python Functions</strong></h3>
<p>In some situations, you might encounter scenarios where you don't know in advance how many arguments will be passed to a function. Python provides a flexible solution for such cases using the <code>*args</code> and <code>**kwargs</code> syntax.</p>
<ul>
<li><p><code>*args</code> collects positional arguments into a tuple.</p>
</li>
<li><p><code>**kwargs</code> collects keyword arguments into a dictionary.</p>
</li>
</ul>
<p>Let's illustrate this with an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_args</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
    print(<span class="hljs-string">"Positional arguments:"</span>, args)
    print(<span class="hljs-string">"Keyword arguments:"</span>, kwargs)

print_args(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, a=<span class="hljs-string">"apple"</span>, b=<span class="hljs-string">"banana"</span>)
</code></pre>
<p>In this example, the <code>print_args</code> function accepts both positional arguments (1, 2, 3) and keyword arguments (a="apple", b="banana"). The <code>*args</code> notation gathers the positional arguments into a tuple, and <code>**kwargs</code> collects the keyword arguments into a dictionary. When you run this function, you get the following output:</p>
<pre><code class="lang-python">Positional arguments: (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
Keyword arguments: {<span class="hljs-string">'a'</span>: <span class="hljs-string">'apple'</span>, <span class="hljs-string">'b'</span>: <span class="hljs-string">'banana'</span>}
</code></pre>
<p>This flexibility is incredibly valuable when you want to create functions that can handle different numbers of arguments without having to define a fixed set of parameters. It allows you to design more versatile and adaptable functions.</p>
<p>Consider a simple function like <code>sum</code>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-keyword">return</span> x + y
</code></pre>
<p>In this case, <code>a</code> and <code>b</code> are parameters, and you pass specific values to the function. However, in scenarios where you need to handle varying numbers of arguments, <code>*args</code> and <code>**kwargs</code> become indispensable tools in your Python programming arsenal.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In the world of Python programming, functions are like the Swiss Army knives of your code. They allow you to encapsulate logic, promote reusability, and make your code more organized and readable. In this article, we've explored the fundamental concepts of Python functions and their various features, showcasing their versatility through engaging examples.</p>
<p>You can connect me on :</p>
<p>💼 Linkedin: <a target="_blank" href="https://www.linkedin.com/in/kartikchop/">https://www.linkedin.com/in/kartikchop/</a></p>
<p>🐦 Twitter: <a target="_blank" href="https://twitter.com/chopcoding">https://twitter.com/chopcoding</a></p>
]]></content:encoded></item><item><title><![CDATA[Spread the Word: Exploring JavaScript's Spread Syntax]]></title><description><![CDATA[As a person who regularly codes in JavaScript, one of my most preferred and frequently used features in the language is the spread syntax. The beauty of this operator lies in its simplicity, versatility, and the clean and intuitive code that it enabl...]]></description><link>https://blog.krtk.dev/spread-the-word-exploring-javascripts-spread-syntax</link><guid isPermaLink="true">https://blog.krtk.dev/spread-the-word-exploring-javascripts-spread-syntax</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Spread operator]]></category><category><![CDATA[full stack]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 07 Aug 2023 06:42:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1691390420358/54315616-fe43-40a7-8f77-3be2b1fddfde.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a person who regularly codes in JavaScript, one of my most preferred and frequently used features in the language is the spread syntax. The beauty of this operator lies in its simplicity, versatility, and the clean and intuitive code that it enables us to write.</p>
<p>For the uninitiated, the spread syntax, denoted by three dots (<code>...</code>), is a nifty feature in JavaScript that "spreads" out elements of an iterable (such as an array or a string) into places where multiple arguments (for function calls) or elements (for array literals), or even key-value pairs (for object literals) are expected. Despite its simplicity, it's an incredibly powerful tool that can significantly streamline your code and make it more readable and maintainable.</p>
<p>Before we delve deeper, let's take a quick look at what the spread syntax looks like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-built_in">console</span>.log(...numbers); <span class="hljs-comment">// Outputs: 1 2 3</span>
</code></pre>
<p>Notice how each element in the array <code>numbers</code> is logged individually, thanks to the spread operator.</p>
<ol>
<li><strong>Unpacking the Spread Syntax in Function Calls</strong></li>
</ol>
<p>The spread syntax really comes into its own when used in function calls. Let's consider a situation where you have an array of numbers and you want to find the maximum number.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">15</span>, <span class="hljs-number">21</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>];
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.max(...numbers)); <span class="hljs-comment">// Outputs: 21</span>
</code></pre>
<p>Using the spread syntax, we can easily pass an array of numbers to the <code>Math.max()</code> function, which expects multiple arguments, not an array.</p>
<ol>
<li><strong>Merging Arrays</strong></li>
</ol>
<p>The spread syntax allows us to perform complex array operations with remarkable ease. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> arr2 = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">let</span> arr3 = [...arr1, ...arr2]; <span class="hljs-comment">// [1, 2, 3, 4, 5, 6]</span>
</code></pre>
<p>This operation, which would otherwise require the use of the <code>concat</code> function or a loop, is reduced to a simple one-liner with the spread syntax.</p>
<ol>
<li><strong>Merging objects</strong></li>
</ol>
<p>Spread syntax also makes merging objects a breeze. Consider the following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj1 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>};
<span class="hljs-keyword">let</span> obj2 = {<span class="hljs-attr">country</span>: <span class="hljs-string">'USA'</span>, <span class="hljs-attr">occupation</span>: <span class="hljs-string">'Engineer'</span>};
<span class="hljs-keyword">let</span> mergedObj = {...obj1, ...obj2}; 
<span class="hljs-comment">// Outputs: { name: 'John', age: 25, country: 'USA', occupation: 'Engineer' }</span>
</code></pre>
<p>The spread operator seamlessly merges <code>obj1</code> and <code>obj2</code> into a new object, <code>mergedObj</code>. Note that this operation creates a shallow copy of the objects, not a deep copy.</p>
<ol>
<li><strong>Converting a string into an array of characters</strong></li>
</ol>
<p>A simple use of the spread operator is to convert a string into an array of characters.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Hello!"</span>;
<span class="hljs-keyword">let</span> chars = [...str];

<span class="hljs-built_in">console</span>.log(chars); <span class="hljs-comment">// Outputs: ['H', 'e', 'l', 'l', 'o', '!']</span>
</code></pre>
<ol>
<li><strong>Using Rest Parameters in Functions</strong></li>
</ol>
<p>While the spread syntax 'unpacks' the contents of an iterable, the rest parameters do the exact opposite - they 'pack' elements back into an array. This concept becomes extremely useful when we deal with functions that are expected to have a variable number of arguments.</p>
<p>Imagine a function that takes two numbers and prints their sum:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSum</span>(<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-built_in">console</span>.log(num1 + num2)
}

printSum(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>) <span class="hljs-comment">// 8</span>
</code></pre>
<p>But what if we wanted to make a more generalized function that can take any number of inputs and then print their sum? That's where rest comes in.</p>
<p>We can use the rest pattern to pack the comma-separated list of arguments into a single array:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSum</span>(<span class="hljs-params">...operands</span>) </span>{
    <span class="hljs-built_in">console</span>.log(operands)
}

printSum(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> ,<span class="hljs-number">100</span>) <span class="hljs-comment">// [1, 3, 4, 100]</span>
</code></pre>
<p>Notice how the comma-separated list of arguments has now been packed into an array. Now, we can use a loop to iterate over the operands array and calculate their sum:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSum</span>(<span class="hljs-params">...operands</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> num <span class="hljs-keyword">of</span> operands)
    sum += num;
  <span class="hljs-built_in">console</span>.log(sum);
}

printSum(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">100</span>) <span class="hljs-comment">// 108</span>
</code></pre>
<p>A function parameter that uses the spread syntax to pack incoming comma-separated items into a single array is called the rest parameter.</p>
<p>The rest parameter can be used in combination with regular parameters as well. But remember:</p>
<ol>
<li><p>The rest parameter should be the last parameter in the parameter list.</p>
</li>
<li><p>There should only be one rest parameter for a given function.</p>
</li>
</ol>
<p>Here are the correct and incorrect examples:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// INCORRECT</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunction</span> (<span class="hljs-params">a, ...rest, b</span>) </span>{
 <span class="hljs-comment">//</span>
}

<span class="hljs-comment">// CORRECT </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunction</span> (<span class="hljs-params">a, b, ...rest</span>) </span>{
 <span class="hljs-comment">//</span>
}

<span class="hljs-comment">// INCORRECT</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunction</span> (<span class="hljs-params">a, ...rest, ...someMore</span>) </span>{
 <span class="hljs-comment">//</span>
}

<span class="hljs-comment">// CORRECT </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunction</span> (<span class="hljs-params">a, ...rest</span>) </span>{
 <span class="hljs-comment">//</span>
}
</code></pre>
<p>And finally, here's an example of using a rest parameter in conjunction with regular parameters:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printGreeting</span>(<span class="hljs-params">greeting, ...names</span>) </span>{
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> names)
        <span class="hljs-built_in">console</span>.log(greeting + <span class="hljs-string">', '</span> + name)
}

printGreeting(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Doe"</span>, <span class="hljs-string">"Smith"</span>);
<span class="hljs-comment">/*
Hello, John
Hello, Doe
Hello, Smith
*/</span>
</code></pre>
<p>In this example, the function <code>printGreeting</code> takes a variable number of names as arguments and greets each of them.</p>
<p>As you can see, the rest parameters provide a flexible way to handle function parameters, making our functions more adaptable and cleaner.</p>
<h2 id="heading-spread-syntax-a-cautionary-note"><strong>Spread Syntax: A Cautionary Note</strong></h2>
<p>While the spread syntax can be a potent tool, it does come with a caveat. It only performs a shallow copy, not a deep copy. This means that for nested arrays or objects, the references are copied, not the actual nested objects themselves.</p>
<p>Despite this limitation, the spread syntax still holds a place of pride in my JavaScript toolbox. It's one of those features that not only simplifies code, but also makes it more intuitive and elegant. The next time you find yourself wrestling with complex operations involving arrays or objects, remember to 'spread' your wings and make the most of this dynamic operator.</p>
<h2 id="heading-a-quick-recap"><strong>A quick recap</strong></h2>
<ol>
<li><p><strong>Definition</strong>: The spread syntax is a feature in JavaScript that allows an iterable such as an array or string to be expanded in places where zero or more arguments (for function calls), elements (for array literals), or key-value pairs (for object literals) are expected.</p>
</li>
<li><p><strong>Array Concatenation</strong>: Spread syntax makes array concatenation simple and clean, without mutating the original arrays.</p>
</li>
<li><p><strong>Copying Arrays and Objects</strong>: The spread syntax allows us to create copies of arrays or objects quickly, preserving the immutability of data, which is an essential aspect of modern JavaScript.</p>
</li>
<li><p><strong>Spread in Function Arguments</strong>: The spread syntax can be used to pass an array to a function that expects separate arguments, leading to more flexible function calls.</p>
</li>
<li><p><strong>Object Spread</strong>: Just like with arrays, the spread syntax can be used with objects to combine, copy, or overwrite properties.</p>
</li>
<li><p><strong>Rest in Function Parameters</strong>: The rest parameter, closely related to the spread syntax, allows a function to accept any number of arguments and access them as an array. This enables us to create flexible functions that can take a varying number of arguments.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Learning RQ Scheduler in Flask by Building a Virtual Pet Game]]></title><description><![CDATA[Introduction
In this article, we are about to embark on a fantastic journey to understand the Redis Queue (RQ) Scheduler within the Flask framework, powered by Python. We are going to do this by creating a simple, yet highly educational game - a "Vir...]]></description><link>https://blog.krtk.dev/learning-rq-scheduler-in-flask-by-building-a-virtual-pet-game</link><guid isPermaLink="true">https://blog.krtk.dev/learning-rq-scheduler-in-flask-by-building-a-virtual-pet-game</guid><category><![CDATA[Python]]></category><category><![CDATA[Flask Framework]]></category><category><![CDATA[python projects]]></category><category><![CDATA[rq]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 31 Jul 2023 08:26:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690791895749/14c4a5cc-ad10-452f-8e48-fedbab9b3ff5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>In this article, we are about to embark on a fantastic journey to understand the Redis Queue (RQ) Scheduler within the Flask framework, powered by Python. We are going to do this by creating a simple, yet highly educational game - a "Virtual Pet". Why a game, you might ask? Games are not only fun but they can also provide a highly interactive learning experience. This will help us better understand the role of an RQ Scheduler in managing asynchronous tasks in our Flask applications. Let's dive in!</p>
<h3 id="heading-understanding-the-virtual-pet-game">Understanding the Virtual Pet Game</h3>
<p>The Virtual Pet Game is designed to help understand the capabilities of the RQ Scheduler, by making certain tasks in the game occur in real-time and others at scheduled intervals.</p>
<p>The game revolves around taking care of a pet with three main actions: feeding it, playing with it, and letting it sleep. Each action affects the pet's state, namely, its hunger and energy levels.</p>
<h4 id="heading-game-mechanics">Game Mechanics:</h4>
<ol>
<li><p><strong>Feeding:</strong> This action decreases the pet's hunger level immediately. However, the pet's hunger gradually increases over time. We schedule a task to increase the pet's hunger every hour using RQ Scheduler.</p>
</li>
<li><p><strong>Playing:</strong> Playing with the pet increases its hunger and decreases its energy. This action occurs instantly when the user chooses to play with the pet.</p>
</li>
<li><p><strong>Sleeping:</strong> Putting the pet to sleep increases its energy level, but the pet cannot do anything else while asleep. We schedule a task to wake up the pet after a certain period (20 minutes in our case). While the pet is asleep, the user can't play with it or feed it.</p>
</li>
</ol>
<h4 id="heading-user-interaction">User Interaction:</h4>
<p>The user interacts with the game through a web interface, with buttons for each of the three main actions. Clicking on these buttons triggers the corresponding action on the server.</p>
<p>For example, if the user clicks on the 'Feed' button, a request is sent to the '/feed_pet/&lt;name&gt;' route, where the 'name' is the pet's name. The server then immediately executes the 'feed' function for that pet.</p>
<p>The 'Play' and 'Sleep' actions work similarly. The 'Sleep' action additionally schedules a task to wake the pet up after 20 minutes.</p>
<p>With this setup, the game mimics a real-life pet scenario where a pet gets hungry over time, needs to rest after play, and needs to wake up after enough sleep.</p>
<h3 id="heading-getting-started">Getting Started</h3>
<p>Before we start, we'll need a few tools in our arsenal. Make sure you have the following installed:</p>
<ul>
<li><p>Python 3</p>
</li>
<li><p>Flask</p>
</li>
<li><p>Redis</p>
</li>
<li><p>RQ Scheduler</p>
</li>
</ul>
<p>For this tutorial, we are assuming that you have a basic understanding of Python, Flask and Redis.</p>
<h3 id="heading-setting-up-rq-scheduler-with-flask">Setting up RQ Scheduler with Flask</h3>
<p>We'll start by setting up Flask with RQ Scheduler. You can create a Flask application and configure it with Redis as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask
<span class="hljs-keyword">from</span> redis <span class="hljs-keyword">import</span> Redis
<span class="hljs-keyword">from</span> rq_scheduler <span class="hljs-keyword">import</span> Scheduler

app = Flask(__name__)
app.redis = Redis()
app.scheduler = Scheduler(connection=app.redis)
</code></pre>
<h3 id="heading-creating-the-virtual-pet-model">Creating the Virtual Pet Model</h3>
<p>Next, let's create our Virtual Pet model. The model will include methods for each of the user's possible interactions, which modify the pet's state:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VirtualPet</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name</span>):</span>
        self.name = name
        self.hunger = <span class="hljs-number">0</span>
        self.energy = <span class="hljs-number">10</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">feed</span>(<span class="hljs-params">self</span>):</span>
        self.hunger -= <span class="hljs-number">5</span>
        <span class="hljs-keyword">if</span> self.hunger &lt; <span class="hljs-number">0</span>:
            self.hunger = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">play</span>(<span class="hljs-params">self</span>):</span>
        self.hunger += <span class="hljs-number">1</span>
        self.energy -= <span class="hljs-number">2</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">self</span>):</span>
        self.energy += <span class="hljs-number">5</span>
</code></pre>
<h3 id="heading-scheduling-tasks">Scheduling Tasks</h3>
<p>Now that we have our pet, let's create some tasks that need to be scheduled:</p>
<ul>
<li><p>Increase pet's hunger over time.</p>
</li>
<li><p>Wake up the pet after some time has passed since it went to sleep.</p>
</li>
</ul>
<p>This can be done using RQ Scheduler as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> timedelta

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increase_hunger</span>(<span class="hljs-params">pet</span>):</span>
    pet.hunger += <span class="hljs-number">1</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wake_up</span>(<span class="hljs-params">pet</span>):</span>
    pet.energy = <span class="hljs-number">10</span>

<span class="hljs-meta">@app.route('/feed_pet/&lt;name&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">feed_pet</span>(<span class="hljs-params">name</span>):</span>
    pet = get_pet(name)
    pet.feed()
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Fed the pet'</span>

<span class="hljs-meta">@app.route('/play_with_pet/&lt;name&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">play_with_pet</span>(<span class="hljs-params">name</span>):</span>
    pet = get_pet(name)
    pet.play()
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Played with the pet'</span>

<span class="hljs-meta">@app.route('/put_pet_to_sleep/&lt;name&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">put_pet_to_sleep</span>(<span class="hljs-params">name</span>):</span>
    pet = get_pet(name)
    pet.sleep()
    app.scheduler.enqueue_in(timedelta(minutes=<span class="hljs-number">20</span>), wake_up, pet)
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Put the pet to sleep'</span>

<span class="hljs-comment"># Scheduled task to increase hunger every hour</span>
app.scheduler.schedule(
    scheduled_time=datetime.utcnow(), <span class="hljs-comment"># Time for first execution</span>
    func=increase_hunger, <span class="hljs-comment"># Function to be queued</span>
    args=(pet,), <span class="hljs-comment"># Arguments passed into function when executed</span>
    interval=<span class="hljs-number">3600</span>, <span class="hljs-comment"># Time before the function is called again, in seconds</span>
    repeat=<span class="hljs-literal">None</span>, <span class="hljs-comment"># Repeat this number of times (None means repeat indefinitely)</span>
)
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Through the Virtual Pet game, we have explored the workings of the RQ Scheduler within a Flask application. By using a fun, interactive setting, we've demonstrated how RQ Scheduler can handle tasks that need to be executed at later time points, ensuring our application remains efficient and user-friendly. As we've seen, it is a powerful tool that can greatly enhance your web applications, making it easier to manage and execute asynchronous tasks.</p>
<h3 id="heading-further-reading">Further Reading</h3>
<p>RQ Scheduler offers many more features, such as the ability to retry failed jobs, schedule jobs to be run at certain times of day, and more. Be sure to check out the <a target="_blank" href="https://github.com/rq/rq-scheduler">RQ Scheduler documentation</a> to explore these features.</p>
<h3 id="heading-future-steps">Future Steps</h3>
<p>In our exploration so far, we've built the backend of our Virtual Pet Game. However, the game is not just about scheduled tasks and server responses; it's also about the player's experience and interaction with the pet.</p>
<p>If you're interested, I can take this tutorial a step further by wiring up an actual front end to this backend. We could design a simple and intuitive UI with a cute virtual pet that users can interact with. This way, we'll bring our virtual pet to life, not just in code but in a more visual and interactive sense!</p>
<p>So, let me know! If there's enough interest, I would be more than happy to guide you through the process of connecting a front end to our Flask application and making our game even more engaging.</p>
<p>Remember, learning is a community journey. Your feedback and engagement can shape the direction we take in our subsequent tutorials. So, don't hesitate to leave your comments, questions, and suggestions.</p>
<p>Until next time, happy coding!</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Automating Tasks in Flask: A Comprehensive Guide to Apscheduler Integration]]></title><description><![CDATA[Are you looking to automate tasks in your Flask application and store the results in MongoDB? Look no further than apscheduler. This powerful Python library enables you to schedule and run tasks at specific intervals or times. By combining apschedule...]]></description><link>https://blog.krtk.dev/automating-tasks-in-flask-a-comprehensive-guide-to-apscheduler-integration</link><guid isPermaLink="true">https://blog.krtk.dev/automating-tasks-in-flask-a-comprehensive-guide-to-apscheduler-integration</guid><category><![CDATA[scheduler]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[apscheduler]]></category><category><![CDATA[Redis]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 03 Jul 2023 08:34:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684985656986/427c08a6-691c-40fe-80bc-d7d25a616f43.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you looking to automate tasks in your Flask application and store the results in MongoDB? Look no further than apscheduler. This powerful Python library enables you to schedule and run tasks at specific intervals or times. By combining apscheduler with Flask and MongoDB, you can create a robust system for automating routine processes and storing the output in a reliable database. In this article, we'll explore how to integrate apscheduler with Flask and connect it to MongoDB, unlocking a world of possibilities for task automation.</p>
<h2 id="heading-1-introduction-to-apscheduler"><strong>1. Introduction to apscheduler</strong></h2>
<p>apscheduler is a widely used Python library for scheduling and running tasks in the background. It provides a flexible and intuitive API to define and manage scheduled jobs. With apscheduler, you can execute functions at fixed intervals, specific times, or based on complex cron-like expressions. Its simplicity and versatility make it a perfect choice for automating tasks in Flask applications.</p>
<h2 id="heading-2-benefits-of-using-apscheduler-with-flask"><strong>2. Benefits of using apscheduler with Flask</strong></h2>
<p>Integrating apscheduler with Flask offers several advantages. Here are a few key benefits:</p>
<ul>
<li><p><strong>Efficiency</strong>: apscheduler allows you to run tasks asynchronously in the background, ensuring your Flask application remains responsive and performs optimally.</p>
</li>
<li><p><strong>Task automation</strong>: You can schedule repetitive or time-sensitive tasks to be executed automatically, reducing manual effort and improving efficiency.</p>
</li>
<li><p><strong>Flexible scheduling</strong>: apscheduler provides various scheduling options, including fixed intervals, specific times, and complex cron-like expressions, allowing you to tailor the execution of tasks to your specific needs.</p>
</li>
<li><p><strong>Integration with Flask</strong>: Seamlessly integrating apscheduler with Flask enables you to leverage the power of both frameworks and build feature-rich applications.</p>
</li>
</ul>
<h2 id="heading-3-setting-up-flask-and-apscheduler"><strong>3. Setting up Flask and apscheduler</strong></h2>
<p>Before we dive into the integration, let's set up a Flask application and install the necessary packages.</p>
<h3 id="heading-installing-the-necessary-packages"><strong>Installing the necessary packages</strong></h3>
<p>To get started, make sure you have Python and pip installed on your system. Then, open your terminal and create a new virtual environment for your Flask project. Activate the virtual environment and install the required packages using the following commands:</p>
<pre><code class="lang-javascript">shellCopy code$ python3 -m venv myenv
$ source myenv/bin/activate
$ pip install flask apscheduler pymongo
</code></pre>
<h3 id="heading-creating-a-flask-app"><strong>Creating a Flask app</strong></h3>
<p>Once the packages are installed, let's create a simple Flask application. Create a new file called <a target="_blank" href="http://app.py"><code>app.py</code></a> and add the following code:</p>
<pre><code class="lang-javascript">pythonCopy codefrom flask <span class="hljs-keyword">import</span> Flask

app = Flask(__name__)

@app.route(<span class="hljs-string">'/'</span>)
def hello_world():
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, Flask!'</span>
</code></pre>
<p>Save the file and run the Flask application using the following command:</p>
<pre><code class="lang-bash">flask run
</code></pre>
<p>Visit <a target="_blank" href="http://localhost:5000"><code>http://localhost:5000</code></a> in your web browser, and you should see the message "Hello, Flask!" displayed.</p>
<h2 id="heading-4-connecting-flask-and-mongodb"><strong>4. Connecting Flask and MongoDB</strong></h2>
<p>To connect Flask with MongoDB, we need to install the <code>pymongo</code> package and configure the MongoDB connection.</p>
<h3 id="heading-installing-pymongo"><strong>Installing pymongo</strong></h3>
<p>Install <code>pymongo</code> using the following command:</p>
<pre><code class="lang-bash">pip install pymongo
</code></pre>
<h3 id="heading-configuring-the-mongodb-connection"><strong>Configuring the MongoDB connection</strong></h3>
<p>To establish a connection to your MongoDB database, you'll need the connection URL. Replace the <code>&lt;connection_url&gt;</code> placeholder in the code below with your actual MongoDB connection URL:</p>
<pre><code class="lang-python">pythonCopy codefrom flask <span class="hljs-keyword">import</span> Flask
<span class="hljs-keyword">from</span> pymongo <span class="hljs-keyword">import</span> MongoClient

app = Flask(__name__)

<span class="hljs-comment"># Replace &lt;connection_url&gt; with your MongoDB connection URL</span>
client = MongoClient(<span class="hljs-string">"&lt;connection_url&gt;"</span>)
db = client.mydatabase
</code></pre>
<p>With this configuration in place, your Flask application is now connected to MongoDB.</p>
<h2 id="heading-5-integrating-apscheduler-with-flask"><strong>5. Integrating apscheduler with Flask</strong></h2>
<p>Now that we have our Flask app and MongoDB connection set up, let's integrate apscheduler into the mix.</p>
<h3 id="heading-importing-the-necessary-modules"><strong>Importing the necessary modules</strong></h3>
<p>In your <a target="_blank" href="http://app.py"><code>app.py</code></a> file, add the following import statements at the top:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> apscheduler.schedulers.background <span class="hljs-keyword">import</span> BackgroundScheduler
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
</code></pre>
<h3 id="heading-defining-scheduled-tasks"><strong>Defining scheduled tasks</strong></h3>
<p>Next, let's define a simple scheduled task that prints a message every 10 seconds. Add the following code to your <a target="_blank" href="http://app.py"><code>app.py</code></a> file:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_message</span>():</span>
    print(<span class="hljs-string">f"Message printed at <span class="hljs-subst">{datetime.now()}</span>"</span>)

scheduler = BackgroundScheduler()
scheduler.add_job(print_message, <span class="hljs-string">'interval'</span>, seconds=<span class="hljs-number">10</span>)
</code></pre>
<h3 id="heading-starting-the-scheduler"><strong>Starting the scheduler</strong></h3>
<p>To start the scheduler and begin executing the scheduled tasks, add the following code after the job definition:</p>
<pre><code class="lang-python">scheduler.start()
</code></pre>
<h2 id="heading-6-creating-scheduled-jobs"><strong>6. Creating scheduled jobs</strong></h2>
<p>Now that we have the basic integration in place, let's create a more practical example by scheduling a job to fetch data from an external API and store it in MongoDB.</p>
<h3 id="heading-defining-a-job-function"><strong>Defining a job function</strong></h3>
<p>First, let's define a function that fetches data from an API and stores it in MongoDB. Add the following code to your <a target="_blank" href="http://app.py"><code>app.py</code></a> file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pymongo <span class="hljs-keyword">import</span> MongoClient
<span class="hljs-keyword">import</span> requests

<span class="hljs-comment"># ...</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_and_store_data</span>():</span>
    response = requests.get(<span class="hljs-string">"https://api.example.com/data"</span>)
    data = response.json()

    <span class="hljs-comment"># Store the data in MongoDB</span>
    db.my_collection.insert_one(data)
</code></pre>
<h3 id="heading-scheduling-the-job"><strong>Scheduling the job</strong></h3>
<p>To schedule the job, add the following code after the function definition:</p>
<pre><code class="lang-python">scheduler.add_job(fetch_and_store_data, <span class="hljs-string">'interval'</span>, minutes=<span class="hljs-number">30</span>)
</code></pre>
<p>This job will execute every 30 minutes, fetching data from the API and storing it in the <code>my_collection</code> collection of your MongoDB database.</p>
<h2 id="heading-7-managing-scheduled-jobs"><strong>7. Managing scheduled jobs</strong></h2>
<p>apscheduler provides a set of tools to manage and control scheduled jobs. Let's explore some common management tasks.</p>
<h3 id="heading-listing-existing-jobs"><strong>Listing existing jobs</strong></h3>
<p>To list all the existing jobs in the scheduler, you can use the <code>get_jobs()</code> method:</p>
<pre><code class="lang-python">jobs = scheduler.get_jobs()

<span class="hljs-keyword">for</span> job <span class="hljs-keyword">in</span> jobs:
    print(job)
</code></pre>
<h3 id="heading-pausing-and-resuming-jobs"><strong>Pausing and resuming jobs</strong></h3>
<p>You can pause and resume individual jobs using the <code>pause()</code> and <code>resume()</code> methods:</p>
<pre><code class="lang-python">scheduler.pause_job(job_id)
scheduler.resume_job(job_id)
</code></pre>
<h3 id="heading-modifying-job-schedules"><strong>Modifying job schedules</strong></h3>
<p>If you need to modify the schedule of a job, you can use the <code>reschedule_job()</code> method:</p>
<pre><code class="lang-python">scheduler.reschedule_job(job_id, trigger=<span class="hljs-string">'cron'</span>, hour=<span class="hljs-string">'23'</span>)
</code></pre>
<p>This example changes the schedule of the job with the given <code>job_id</code> to execute every day at 11 PM.</p>
<h2 id="heading-8-handling-job-errors"><strong>8. Handling job errors</strong></h2>
<p>When working with scheduled tasks, it's essential to handle potential errors gracefully and ensure the stability of your application. Here are some best practices for handling job errors:</p>
<h3 id="heading-implementing-error-handling-mechanisms"><strong>Implementing error-handling mechanisms</strong></h3>
<p>Wrap your job function code in a try-except block to catch and handle any exceptions that may occur:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_and_store_data</span>():</span>
    <span class="hljs-keyword">try</span>:
        response = requests.get(<span class="hljs-string">"https://api.example.com/data"</span>)
        data = response.json()

        <span class="hljs-comment"># Store the data in MongoDB</span>
        db.my_collection.insert_one(data)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{str(e)}</span>"</span>)
</code></pre>
<h3 id="heading-logging-job-failures"><strong>Logging job failures</strong></h3>
<p>It's recommended to log job failures to track any issues that may arise. You can use Python's built-in <code>logging</code> module for this purpose:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging

<span class="hljs-comment"># ...</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_and_store_data</span>():</span>
    <span class="hljs-keyword">try</span>:
        response = requests.get(<span class="hljs-string">"https://api.example.com/data"</span>)
        data = response.json()

        <span class="hljs-comment"># Store the data in MongoDB</span>
        db.my_collection.insert_one(data)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        logging.error(<span class="hljs-string">f"Job failed: <span class="hljs-subst">{str(e)}</span>"</span>)
</code></pre>
<p>By logging job failures, you can easily monitor and troubleshoot any errors that occur during execution.</p>
<h2 id="heading-9-conclusion"><strong>9. Conclusion</strong></h2>
<p>In this article, we explored the powerful combination of apscheduler, Flask, and MongoDB for automating tasks in your Flask applications. We covered the process of setting up Flask and connecting it to MongoDB, integrating apscheduler into your Flask app, creating scheduled jobs, managing and modifying jobs, and handling job errors. By leveraging this integration, you can streamline your application's workflow, automate routine tasks, and store the output in a reliable database.</p>
<p>Get started with apscheduler, Flask, and MongoDB today, and unlock the potential for efficient and automated task execution in your applications.</p>
]]></content:encoded></item><item><title><![CDATA[Flask + Docker + VSCode: How to Simplify Debugging and Improve Your Development Experience]]></title><description><![CDATA[Introduction
Debugging Flask Python applications can be challenging, and things get even more complicated when running Flask inside a Docker container. Fortunately, with the right setup, debugging Flask running inside Docker locally in VSCode can be ...]]></description><link>https://blog.krtk.dev/flask-docker-vscode-how-to-simplify-debugging-and-improve-your-development-experience</link><guid isPermaLink="true">https://blog.krtk.dev/flask-docker-vscode-how-to-simplify-debugging-and-improve-your-development-experience</guid><category><![CDATA[Flask Framework]]></category><category><![CDATA[vscode extensions]]></category><category><![CDATA[Python]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 13 Mar 2023 04:24:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678516372196/70a40226-161b-49d1-abb2-bfb979c3dbc9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>Debugging Flask Python applications can be challenging, and things get even more complicated when running Flask inside a Docker container. Fortunately, with the right setup, debugging Flask running inside Docker locally in VSCode can be made much easier. In this article, we'll guide you through the process of setting up your Flask Python application to run inside a Docker container and show you how to leverage VSCode's powerful debugging features to troubleshoot any issues that arise. With our step-by-step instructions, you'll be able to streamline your development workflow and solve even the most complex bugs in no time!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678516397356/59ed9009-eace-4825-8177-bb1c1e0784ca.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-is-debugpy"><strong>What is debugpy?</strong></h2>
<p>Debugpy is a Python debugger that provides a simple way to debug Python code remotely. It can be used to debug Python code running inside a Docker container, as well as code running on a remote machine. Debugpy can be used with a variety of editors and IDEs, including VSCode.</p>
<h2 id="heading-step-1-create-a-flask-app"><strong>Step 1: Create a Flask app</strong></h2>
<p>Before we can start debugging, we need a Flask app to work with. Here is a simple Flask app that we will use as an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask

app = Flask(__name__)

<span class="hljs-meta">@app.route('/')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, World!'</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run()
</code></pre>
<h2 id="heading-step-2-create-a-dockerfile"><strong>Step 2: Create a Dockerfile</strong></h2>
<p>Next, we need to create a Dockerfile that will define the Docker image for our Flask app. Here is an example Dockerfile:</p>
<pre><code class="lang-bash">FROM --platform=linux/amd64 ubuntu:latest

COPY . /app

WORKDIR /app

RUN apt-get update \
  &amp;&amp; apt-get install -y python3-pip python3-dev \
  &amp;&amp; <span class="hljs-built_in">cd</span> /usr/<span class="hljs-built_in">local</span>/bin \
  &amp;&amp; ln -s /usr/bin/python3 python \
  &amp;&amp; pip3 install --upgrade pip

RUN pip install -r requirements.txt
EXPOSE 5000

RUN pip install debugpy

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV DEBIAN_FRONTEND=noninteractive
CMD [<span class="hljs-string">"python"</span>, <span class="hljs-string">"-m"</span>, <span class="hljs-string">"debugpy"</span>, <span class="hljs-string">"--listen"</span>, <span class="hljs-string">"0.0.0.0:5679"</span>, <span class="hljs-string">"app.py"</span>]
</code></pre>
<p>In this Dockerfile, we start with an Ubuntu base image and copy the contents of our current directory to the <code>/app</code> directory inside the Docker image. We install the necessary dependencies, including debugpy, and expose port 5000. Finally, we start debugpy and set it to listen on port 5679.</p>
<h2 id="heading-step-3-create-a-docker-compose-file"><strong>Step 3: Create a docker-compose file</strong></h2>
<p>We will use a docker-compose file to simplify the process of running our Docker container. Here is an example docker-compose file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>
<span class="hljs-attr">services:</span>
  <span class="hljs-attr">api:</span>
    <span class="hljs-attr">container_name:</span> <span class="hljs-string">api</span>
    <span class="hljs-attr">command:</span> <span class="hljs-string">python</span> <span class="hljs-string">-u</span> <span class="hljs-string">app.py</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">context:</span> <span class="hljs-string">./api</span>
      <span class="hljs-attr">dockerfile:</span> <span class="hljs-string">Dockerfile</span>
    <span class="hljs-attr">restart:</span> <span class="hljs-string">unless-stopped</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">frontend</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">backend</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-number">12005</span><span class="hljs-string">:5000</span>
      <span class="hljs-bullet">-</span> <span class="hljs-number">5679</span><span class="hljs-string">:5679</span> 
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">./api:/app</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">/etc/localtime:/etc/localtime</span>
    <span class="hljs-attr">entrypoint:</span> [ <span class="hljs-string">"python"</span>, <span class="hljs-string">"-m"</span>, <span class="hljs-string">"debugpy"</span>, <span class="hljs-string">"--listen"</span>, <span class="hljs-string">"0.0.0.0:5679"</span>, <span class="hljs-string">"-m"</span>, <span class="hljs-string">"app"</span>,  <span class="hljs-string">"--wait-for-client"</span>, <span class="hljs-string">"--multiprocess"</span>, <span class="hljs-string">"-m"</span>, <span class="hljs-string">"flask"</span>, <span class="hljs-string">"run"</span>, <span class="hljs-string">"-h"</span>, <span class="hljs-string">"0.0.0.0"</span>, <span class="hljs-string">"-p"</span>, <span class="hljs-string">"5000"</span> ]
<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">frontend:</span>
    <span class="hljs-attr">driver:</span> <span class="hljs-string">bridge</span>
  <span class="hljs-attr">backend:</span>
    <span class="hljs-attr">driver:</span> <span class="hljs-string">bridge</span>
</code></pre>
<p>In this docker-compose file, we define a <code>networks</code> section to specify the communication between containers. In this case, we define two networks: <code>frontend</code> and <code>backend</code>. The <code>frontend</code> network will allow communication between the <code>web</code> container and any other container in the <code>frontend</code> network, while the <code>backend</code> network will allow communication between the <code>web</code> container and any other container in the <code>backend</code> network.</p>
<p>Lastly, we define the <code>volumes</code> section to mount the application code directory (<code>./app</code>) on the host to the <code>/app</code> directory in the container. This allows us to make changes to the application code on the host and have those changes reflected in the container immediately without needing to rebuild the container.</p>
<p>Now that we have our <code>docker-compose.yml</code> file set up, we can use the following command to start our application:</p>
<pre><code class="lang-bash">docker-compose up
</code></pre>
<p>This will start the <code>api</code> container, along with any other containers specified in the <code>docker-compose.yml</code> file.</p>
<h2 id="heading-debugging-the-flask-application-with-vscode-and-docker"><strong>Debugging the Flask application with VSCode and Docker</strong></h2>
<p>Now that we have our Flask application running inside a Docker container, let's see how we can debug it using VSCode.</p>
<p>The first thing we need to do is to add a <code>.vscode/launch.json</code> configuration file to our project. This file specifies the configuration for the debugger, such as the type of debugger, the port to connect to, and the source code location. Here is an example <code>launch.json</code> configuration file:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.2.0"</span>,
    <span class="hljs-attr">"configurations"</span>: [
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Python: Remote Attach"</span>,
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"python"</span>,
            <span class="hljs-attr">"request"</span>: <span class="hljs-string">"attach"</span>,
            <span class="hljs-attr">"port"</span>: <span class="hljs-number">5679</span>,
            <span class="hljs-attr">"host"</span>: <span class="hljs-string">"0.0.0.0"</span>,
            <span class="hljs-attr">"pathMappings"</span>: [
                {
                    <span class="hljs-attr">"localRoot"</span>: <span class="hljs-string">"${workspaceFolder}/app"</span>,
                    <span class="hljs-attr">"remoteRoot"</span>: <span class="hljs-string">"/app"</span>
                }
            ]
        }
    ]
}
</code></pre>
<p>In this configuration file, we specify that we want to attach to a remote Python process on port 5679, which is the same port that we exposed in our <code>docker-compose.yml</code> file. We also specify the <code>pathMappings</code> property to map the local source code directory (<code>${workspaceFolder}/app</code>) to the <code>/app</code> directory in the container.</p>
<p>With our <code>launch.json</code> configuration file set up, we can now start the Flask application with the <code>--wait-for-client</code> option and the <code>debugpy</code> module. This will start the application in debug mode and wait for a debugger to connect before executing any code.</p>
<p>Now that we have our application running in debug mode, we can go back to VSCode and start the debugger by selecting the <code>Python: Remote Attach</code> configuration from the VSCode debugger dropdown menu and clicking the green "play" button.</p>
<p>This will attach the VSCode debugger to the running Flask application inside the Docker container, allowing us to set breakpoints</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've walked through the process of debugging a Flask application running inside a Docker container in VSCode. By leveraging the power of debugpy, we're able to connect the VSCode debugger to our running container, set breakpoints, and step through our code as if it were running locally.</p>
<p>With the use of a Dockerfile, we've created a containerized environment with all the necessary dependencies to run our Flask application, including debugpy. We've also updated our docker-compose file to include debugpy as the entrypoint for our container and created a new port mapping for the debugger to connect to.</p>
<p>By following these steps, we can easily debug our Flask application running inside a Docker container in VSCode, making it easier to identify and resolve any issues that may arise during development.</p>
<p>If you'd like to try this out for yourself, you can check out our example repository at <a target="_blank" href="https://github.com/kartikpuri95/flask-vscode-debug">repo</a>(<a target="_blank" href="https://github.com/kartikpuri95/flask-vscode-debug">https://github.com/kartikpuri95/flask-vscode-debug</a>) and see how we've implemented these techniques to debug a Flask application inside a Docker container using VSCode.</p>
]]></content:encoded></item><item><title><![CDATA[Git Beyond the Basics: 5 Advanced Commands for Power Users]]></title><description><![CDATA[Git is a powerful version control system that can help you manage your projects effectively. It has many useful commands that can save you time and increase your productivity. Here are some of the top Git commands that you should know:
Updating the l...]]></description><link>https://blog.krtk.dev/git-beyond-the-basics-5-advanced-commands-for-power-users</link><guid isPermaLink="true">https://blog.krtk.dev/git-beyond-the-basics-5-advanced-commands-for-power-users</guid><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[GitLab]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Wed, 08 Mar 2023 06:29:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677555613322/96343d47-212d-4764-8ad0-864df6ae2678.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Git is a powerful version control system that can help you manage your projects effectively. It has many useful commands that can save you time and increase your productivity. Here are some of the top Git commands that you should know:</p>
<h2 id="heading-updating-the-last-commit-message">Updating the last commit message</h2>
<p>If you want to update the message of your last commit, you can use the following command to edit it:</p>
<pre><code class="lang-bash">git commit --amend -m <span class="hljs-string">"Updated message"</span>
</code></pre>
<h2 id="heading-checking-the-total-number-of-commits">Checking the total number of commits</h2>
<p>To check the total number of commits on a particular branch, you can use the following command:</p>
<pre><code class="lang-bash">git rev-list --count &lt;branch-name&gt;
</code></pre>
<p>For example, if you want to check the number of commits on the main branch, you can use the following command:</p>
<pre><code class="lang-bash">git rev-list --count main
</code></pre>
<h2 id="heading-staging-and-committing-changes-in-a-single-command">Staging and committing changes in a single command</h2>
<p>Instead of using <code>git add</code> and <code>git commit</code> separately, you can use the following command to stage and commit changes in a single step:</p>
<pre><code class="lang-bash">git commit -am <span class="hljs-string">"message"</span>
</code></pre>
<h2 id="heading-checking-files-from-a-different-branch">Checking files from a different branch</h2>
<p>If you want to view files from a different branch while working on a different branch, you can use the following command:</p>
<pre><code class="lang-bash">git show &lt;branch-name&gt;:&lt;file-name&gt;
</code></pre>
<p>For example, if you are working on the test branch and want to see the <a target="_blank" href="http://README.md">README.md</a> file of the main branch, you can use the following command:</p>
<pre><code class="lang-bash">git show main:README.md
</code></pre>
<h2 id="heading-blank-commit">Blank Commit</h2>
<p>Sometimes you may need a blank commit, such as when you want to initialize a repository or trigger an action. You can use the following command to create a blank commit:</p>
<pre><code class="lang-bash">git commit --allow-empty -m <span class="hljs-string">"blank commit message"</span>
</code></pre>
<p>This command creates a commit with no changes added or deleted.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/chopcoding/status/1630092913739960320">https://twitter.com/chopcoding/status/1630092913739960320</a></div>
]]></content:encoded></item><item><title><![CDATA[How to Build a Blog with Gatsby: A Beginner's Guide]]></title><description><![CDATA[Introduction
Gatsby is a popular open-source framework for building fast and modern websites and applications. At its core, Gatsby uses React and GraphQL to generate static HTML, CSS, and JavaScript files that can be deployed to any hosting provider....]]></description><link>https://blog.krtk.dev/how-to-build-a-blog-with-gatsby-a-beginners-guide</link><guid isPermaLink="true">https://blog.krtk.dev/how-to-build-a-blog-with-gatsby-a-beginners-guide</guid><category><![CDATA[Gatsby]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 27 Feb 2023 06:20:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677401040838/1f60e6de-0efc-448c-84bb-93cb9d7a94e0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Gatsby is a popular open-source framework for building fast and modern websites and applications. At its core, Gatsby uses React and GraphQL to generate static HTML, CSS, and JavaScript files that can be deployed to any hosting provider. With Gatsby, you can build websites and applications that are optimized for performance, accessibility, and search engine rankings.</p>
<p>One of the great things about Gatsby is that it can be used for building a wide range of websites and applications, including blogs. In fact, Gatsby provides a Starter Blog template that makes it easy to get started with building a blog. With the Starter Blog template, you get a fully functional blog with features like pagination, tags, and search out of the box. You can customize the look and feel of your blog by editing the code and adding new components.</p>
<p>So why is Gatsby a great choice for building a blog? Here are a few reasons:</p>
<ul>
<li><p>Speed: Gatsby generates static HTML files that load faster than dynamic websites built with traditional CMSs. This means your blog will load quickly and provide a better user experience for your readers.</p>
</li>
<li><p>SEO: Gatsby generates SEO-friendly markup out of the box, which means your blog posts are more likely to be discovered by search engines.</p>
</li>
<li><p>Customization: Gatsby provides a flexible and extensible platform for building your blog. You can customize the look and feel of your blog by editing the code, adding new pages, and integrating with third-party services.</p>
</li>
<li><p>Cost: Gatsby is a free and open-source framework, which means you can build and deploy your blog without any upfront costs. In fact, you can deploy your Gatsby blog to a hosting provider like GitHub Pages or Netlify for free.</p>
</li>
</ul>
<p>In this article, we'll walk you through the steps for building a blog with Gatsby, from installation to deployment. By the end of this article, you'll have a fully functional blog that you can customize and deploy to your favorite hosting provider. Let's get started!</p>
<h3 id="heading-getting-started-with-gatsby">Getting Started with Gatsby</h3>
<ul>
<li><p>Before you can start building a blog with Gatsby, there are a few prerequisites you'll need to meet. First and foremost, you'll need to have Node.js and npm installed on your machine. If you don't already have these tools installed, you can download them from the Node.js website (<a target="_blank" href="https://nodejs.org">https://nodejs.org</a>).</p>
</li>
<li><p>Once you have Node.js and npm installed, you're ready to install Gatsby. You can do this by running the following command in your terminal or command prompt:</p>
</li>
</ul>
<pre><code class="lang-bash">npm install -g gatsby-cli
</code></pre>
<p>This command will install the Gatsby command-line interface (CLI), which you can use to create and manage Gatsby sites.</p>
<p>With Gatsby installed, you're ready to create your blog. Fortunately, Gatsby provides a Starter Blog template that makes it easy to get started with building a blog. You can create a new Gatsby site using the Starter Blog template by running the following command in your terminal or command prompt:</p>
<pre><code class="lang-bash">gatsby new my-blog https://github.com/gatsbyjs/gatsby-starter-blog
</code></pre>
<p>This command will create a new Gatsby site in a directory called <code>my-blog</code>, based on the Starter Blog template. The <code>gatsby-starter-blog</code> template includes all the necessary files and configuration to get your blog up and running quickly.</p>
<p>Once the command completes, you can navigate to the <code>my-blog</code> directory and start the development server by running the following command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> my-blog
gatsby develop
</code></pre>
<p>This command will start a local development server at <a target="_blank" href="http://localhost:8000"><code>http://localhost:8000</code></a>, where you can preview your blog and make changes to the code. When you make changes to the code, Gatsby will automatically rebuild the site and refresh the page in your browser.</p>
<p>That's it! You now have a fully functional blog running locally on your machine. In the next section, we'll look at how you can customize your Gatsby blog to make it your own.</p>
<h3 id="heading-customize-your-gatsby-blog-to-make-it-your-own">Customize Your Gatsby Blog to Make it Your Own</h3>
<p>Now that you have a basic Gatsby blog up and running, it's time to customize it to fit your needs. There are a number of ways you can customize your blog, including:</p>
<ol>
<li><p>Editing the content: You can edit the content of your blog by modifying the markdown files located in the <code>content/blog</code> directory. Each markdown file represents a blog post, and you can add new posts by creating new markdown files.</p>
</li>
<li><p>Customizing the layout: The layout of your blog is defined by the React components located in the <code>src/components</code> directory. You can customize the layout by modifying these components, or by creating new components of your own.</p>
</li>
<li><p>Styling your blog: The styles for your blog are defined in the <code>src/styles</code> directory. You can customize the styles by modifying the existing files or by adding new stylesheets.</p>
</li>
<li><p>Adding new features: Gatsby provides a number of plugins and APIs that you can use to add new features to your blog. For example, you can add support for comments using a third-party service like Disqus, or add a contact form using a plugin like <code>gatsby-plugin-netlify-forms</code>.</p>
</li>
</ol>
<p>Let's take a closer look at how you can customize the layout of your blog. The layout of your blog is defined by a series of React components, including the header, footer, and individual blog posts. You can modify these components by editing the files located in the <code>src/components</code> directory.</p>
<p>For example, if you want to add a new section to the header of your blog, you can modify the <code>Header.js</code> component located in the <code>src/components</code> directory. You can add new elements to the header by modifying the <code>render</code> method of the component, like this:</p>
<pre><code class="lang-javascript">render() {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/about"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/contact"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/tags"</span>&gt;</span>Tags<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/search"</span>&gt;</span>Search<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/new-section"</span>&gt;</span>New Section<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> // <span class="hljs-tag">&lt;<span class="hljs-name">--</span> <span class="hljs-attr">New</span> <span class="hljs-attr">section</span>
        &lt;/<span class="hljs-attr">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
  )
}</span>
</code></pre>
<p>In this example, we've added a new link to the header that points to a new section of the site called "New Section". When you save this file and refresh your browser, you should see the new link appear in the header of your blog.</p>
<p>That's just one example of how you can customize the layout of your Gatsby blog. With a little bit of knowledge of React and CSS, you can create a fully customized blog that looks and functions exactly the way you want it to.</p>
<p>In the next section, we'll look at how you can deploy your Gatsby blog to the web.</p>
<h3 id="heading-deploy-your-gatsby-blog-to-the-web">Deploy Your Gatsby Blog to the Web</h3>
<p>Now that you have a customized Gatsby blog, it's time to deploy it to the web so that others can see it. Luckily, deploying a Gatsby blog is a straightforward process, and there are several free options available.</p>
<ol>
<li>Netlify: Netlify is a cloud-based platform that makes it easy to deploy Gatsby blogs and other static websites. With Netlify, you can deploy your blog with just a few clicks, and you can also set up automatic deployments so that your site is updated every time you make a change.</li>
</ol>
<p>To deploy your blog with Netlify, first sign up for a free account. Then, connect your account to your Gatsby repository by linking your GitHub or GitLab account. Finally, follow the steps on the Netlify website to deploy your site. You'll need to specify the build command as <code>gatsby build</code>, and the publish directory as <code>public</code>.</p>
<ol>
<li><p>GitHub Pages: If you're already using GitHub to host your Gatsby repository, you can deploy your site to GitHub Pages for free. To do this, first build your site by running the <code>gatsby build</code> command in your terminal. Then, create a new branch in your repository called <code>gh-pages</code>. Finally, copy the contents of the <code>public</code> directory into the root of the <code>gh-pages</code> branch and push the changes to GitHub. Your site should now be live at <a target="_blank" href="https://yourusername.github.io/your-repo-name"><code>https://yourusername.github.io/your-repo-name</code></a>.</p>
</li>
<li><p>Vercel: Vercel is a cloud-based platform that makes it easy to deploy Gatsby blogs and other static websites. With Vercel, you can deploy your blog with just a few clicks, and you can also set up automatic deployments so that your site is updated every time you make a change.</p>
</li>
</ol>
<p>To deploy your blog with Vercel, first sign up for a free account. Then, connect your account to your Gatsby repository by linking your GitHub or GitLab account. Finally, follow the steps on the Vercel website to deploy your site. You'll need to specify the build command as <code>gatsby build</code>, and the output directory as <code>public</code>.</p>
<p>Once you've deployed your blog, you can share it with the world by sharing the URL with your friends and followers. Congratulations, you now have a fully customized Gatsby blog that's live on the web!</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article, we've seen how easy and flexible it is to build a blog with Gatsby. With its powerful features like hot-reloading, fast page rendering, and GraphQL data layer, Gatsby is a great choice for building static websites, including blogs.</p>
<p>We started by installing Gatsby and using the Gatsby Starter Blog template to create a basic blog. Then, we customized the blog by modifying the layout, adding new pages, and installing plugins.</p>
<p>Finally, we deployed the blog to the web using free hosting platforms like Netlify, GitHub Pages, and Vercel. Now, your blog is accessible to anyone with an internet connection.</p>
<p>If you're new to Gatsby or building a blog, this guide should help you get started. With Gatsby, you have the power to create a fully customizable and performant blog, all without having to worry about complex server infrastructure or back-end code.</p>
<p>So what are you waiting for? Start building your own Gatsby blog today and share your ideas with the world!</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/chopcoding/status/1628990655749033986">https://twitter.com/chopcoding/status/1628990655749033986</a></div>
]]></content:encoded></item><item><title><![CDATA[SQL-S3 combination for handling images like a pro]]></title><description><![CDATA[Introduction
In this tutorial, we will explore how to use the combination of SQL and S3 to efficiently handle images. We will be using Python, Flask, and SQLAlchemy to accomplish this task. Specifically, we will be using the Flask-SQLAlchemy library,...]]></description><link>https://blog.krtk.dev/sql-s3-combination-for-handling-images-like-a-pro</link><guid isPermaLink="true">https://blog.krtk.dev/sql-s3-combination-for-handling-images-like-a-pro</guid><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Flask Framework]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Wed, 11 Jan 2023 05:56:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0DJHJcpwN9Q/upload/9448ff6f6feae99593b4967564f579cc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In this tutorial, we will explore how to use the combination of SQL and S3 to efficiently handle images. We will be using Python, Flask, and SQLAlchemy to accomplish this task. Specifically, we will be using the Flask-SQLAlchemy library, which is a convenient wrapper for SQLAlchemy that makes it easy to use in a Flask application.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li><p>A basic understanding of Python</p>
</li>
<li><p>Familiarity with Flask and SQLAlchemy</p>
</li>
<li><p>An S3 bucket set up with appropriate access credentials</p>
</li>
<li><p>MySQL installed and set up on your system</p>
</li>
</ul>
<h3 id="heading-step-1-setting-up-the-database">Step 1: Setting up the Database</h3>
<p>First, we need to set up the database. We will use MySQL for this tutorial. Create a new database and table in MySQL. You could use any SQL database like postgres, sqlite etc.</p>
<pre><code class="lang-python">Copyfrom flask <span class="hljs-keyword">import</span> Flask
<span class="hljs-keyword">from</span> flask_sqlalchemy <span class="hljs-keyword">import</span> SQLAlchemy

app = Flask(__name__)
app.config[<span class="hljs-string">'SQLALCHEMY_DATABASE_URI'</span>] = <span class="hljs-string">'mysql://username:password@host:port/dbname'</span>
db = SQLAlchemy(app)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Image</span>(<span class="hljs-params">db.Model</span>):</span>
    id = db.Column(db.Integer, primary_key=<span class="hljs-literal">True</span>)
    link = db.Column(db.String(<span class="hljs-number">255</span>), nullable=<span class="hljs-literal">False</span>)

db.create_all()
</code></pre>
<p>In this step, we are just creating the database connection and creating a table to store the images.</p>
<h3 id="heading-step-2-storing-images-on-s3">Step 2: Storing Images on S3</h3>
<p>Next, we will create a function to store images on S3. For this, we will use the boto3 library, which is a Python SDK for AWS.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload_to_s3</span>(<span class="hljs-params">image_file</span>):</span>
    s3 = boto3.client(<span class="hljs-string">'s3'</span>, aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY)
    <span class="hljs-keyword">try</span>:
        s3.upload_fileobj(image_file, BUCKET_NAME, image_file.filename)
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"https://<span class="hljs-subst">{BUCKET_NAME}</span>.s3.amazonaws.com/<span class="hljs-subst">{image_file.filename}</span>"</span>
    <span class="hljs-keyword">except</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Upload failed"</span>
</code></pre>
<p>Here, we are using the <code>upload_fileobj</code> method to upload the image file to our S3 bucket. The function returns the URL of the image on S3, which we will use to store in the database.</p>
<h3 id="heading-step-3-storing-image-urls-in-the-database">Step 3: Storing Image URLs in the Database</h3>
<p>Once we have the image stored on S3, we can store its URL in the database.</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.route("/upload", methods=["POST"])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload</span>():</span>
    image_file = request.files[<span class="hljs-string">"image"</span>]
    s3_url = upload_to_s3(image_file)
    <span class="hljs-keyword">if</span> s3_url != <span class="hljs-string">"Upload failed"</span>:
        image = Image(link=s3_url)
        db.session.add(image)
        db.session.commit()
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Image uploaded and URL saved to database"</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Upload failed"</span>
</code></pre>
<p>We are using a Flask route to handle the image upload and database insertion. This route will handle the POST request from the client side and it will store the image to s3 and stores its url in the database using the SQLAlchemy session object.</p>
<h3 id="heading-step-4-retrieving-images-from-the-database">Step 4: Retrieving Images from the Database</h3>
<p>Now that we have our images stored in S3 and their URLs stored in the database, we can retrieve them whenever we need to. Here's an example of how to retrieve an image by its ID:</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.route("/image/&lt;int:id&gt;")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">image</span>(<span class="hljs-params">id</span>):</span>
    image = Image.query.get(id)
    <span class="hljs-keyword">if</span> image:
        <span class="hljs-keyword">return</span> redirect(image.link)
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Image not found"</span>, <span class="hljs-number">404</span>
</code></pre>
<p>This route takes an ID as a parameter, and it uses the SQLAlchemy query object to retrieve the image from the database by its ID. If the image is found, it returns the image by redirecting to the S3 url, otherwise returns 404</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this tutorial, we have learned how to use SQL and S3 together to handle images efficiently. We have learned how to store images on S3 and store their URLs in the database using SQLAlchemy, and how to retrieve images from the database and serve them to the client. This method is highly scalable, and it will allow you to handle large amounts of image data easily.</p>
<p>You could also delete the image from s3 once it's deleted from the database. This would complete the lifecycle of the image. Please keep in mind that the provided code is only a skeleton and you might need to adjust it to your specific use case.</p>
<p>This kind of architecture is useful if you need to access images frequently or if you don't want to use expensive server storage for storing images. And using s3 storage you could take advantage of the many features it provides like, data replication, data transfer acceleration, Content delivery network(CDN), etc.</p>
]]></content:encoded></item><item><title><![CDATA[Using Prompt Engineering to Tell Engaging Bedtime Stories]]></title><description><![CDATA[Recently, I have been diving deep into the world of AI and machine learning and have discovered some truly amazing concepts. One that really stood out to me was the idea of prompt engineering.
For those unfamiliar with prompt engineering, it's a tech...]]></description><link>https://blog.krtk.dev/using-prompt-engineering-to-tell-engaging-bedtime-stories</link><guid isPermaLink="true">https://blog.krtk.dev/using-prompt-engineering-to-tell-engaging-bedtime-stories</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[ai prompt writer]]></category><category><![CDATA[openai]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 02 Jan 2023 07:22:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672644096364/e078c268-bd94-4ee0-a42a-7475e204ee1f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, I have been diving deep into the world of AI and machine learning and have discovered some truly amazing concepts. One that really stood out to me was the idea of prompt engineering.</p>
<p>For those unfamiliar with prompt engineering, it's a technique used in natural language processing to generate text. In this article, I'll explain what it is and provide an example of using it to generate bedtime stories. Trust me, it's a mind-blowing concept that you won't want to miss!</p>
<h2 id="heading-what-is-prompt-engineering">What is prompt engineering?</h2>
<p>So, what is prompt engineering exactly? At its core, it's the process of designing and creating prompts that are used to help machines produce natural language text. These prompts are carefully crafted to elicit a specific response or to guide the machine toward a particular type of language output.</p>
<p>For example, imagine you are building a chatbot to assist with customer service inquiries. One of the prompts you might use is: "Hello, how can I help you today?" This prompt is designed to elicit a response from the customer, such as "I have a question about my order" or "I need help with my account login." The chatbot can then use this information to provide the appropriate assistance to the customer.</p>
<p>Or, consider the case of machine translation. In this scenario, the prompt might be a piece of text in one language that the machine translation system is intended to translate into another language. The prompt is carefully crafted to guide the machine toward a specific translation outcome.</p>
<p>In short, prompt engineering is a crucial tool for creating natural language text in the fields of AI and machine learning. By designing and creating prompts that are tailored to elicit specific responses or guide language output, it is possible to create engaging and accurate language output from machines.</p>
<h2 id="heading-prompt-engineering-for-bedtime-stories-a-case-study">Prompt Engineering for Bedtime Stories: A Case Study</h2>
<p>One application of prompt engineering is in the generation of bedtime stories. Bedtime stories are a traditional and beloved way to entertain and soothe children before sleep. However, coming up with new and engaging bedtime stories can be a challenge, especially for busy parents.</p>
<p>By carefully crafting prompts that include key elements of traditional bedtime stories, it is possible to stimulate the production of compelling and engaging narratives that are perfect for tucking children into bed</p>
<p>For example, consider the following prompt: <em><mark>"Once upon a time, in a land far, far away, there was a kind and brave princess who lived in a beautiful castle. One day, she set out on a journey to save her kingdom from an evil dragon.</mark></em><mark>"</mark></p>
<p>Using this prompt as a starting point, a chatbot or machine language system might generate the following bedtime story:</p>
<p><em><mark>The princess knew that she had to be brave if she was going to defeat the dragon and save her kingdom. She gathered her courage and set out on a journey, traveling through forests and over mountains, facing many dangers along the way.</mark></em></p>
<p><em><mark>Finally, she reached the dragon's lair, where she found the beast sleeping soundly. She drew her sword and, with a fierce cry, charged at the dragon.</mark></em></p>
<p><em><mark>The dragon woke with a start and breathed flames at the princess, but she was quick and agile, dodging the flames and striking at the dragon with her sword. After a fierce battle, the princess emerged victorious, having defeated the dragon and saved her kingdom.</mark></em></p>
<p><em><mark>The people of the kingdom rejoiced and hailed the princess as their hero. And she lived happily ever after, ruling justly and with kindness.</mark></em></p>
<p>Using prompt engineering one can literally craft the stories.  </p>
<p>For example, instead of using the prompt "<em>There was a kind and brave princess," we could use a prompt like "There was a clever and resourceful princess" to elicit a different type of story. In this case, the princess might be depicted as solving problems and coming up with creative solutions to overcome challenges, rather than relying on physical bravery</em></p>
<p>Alternatively, we could use a prompt like "There was a mischievous and adventurous princess" to stimulate the production of a story about a princess who is always getting into trouble and going on exciting escapades.</p>
<p>By carefully designing the prompts to include different characteristics or traits, it is possible to change the nature of the princess and the overall tone and theme of the story.</p>
<p>All the above examples are the actually prompts from the open AI playground <a target="_blank" href="https://beta.openai.com/playground">https://beta.openai.com/playground</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, prompt engineering is a powerful tool for generating natural language text in the fields of AI and machine learning. By carefully designing and creating prompts that are tailored to elicit specific responses or guide language output, it is possible to create engaging and accurate language output from machines.</p>
<p>As the example of generating bedtime stories demonstrates, prompt engineering can be used to create a wide variety of language outputs, from customer service chatbot responses to machine translations to engaging narratives. Whether you are a beginner or a seasoned professional in the field of AI and machine learning, understanding and mastering the art of prompt engineering is sure to be a valuable skill.</p>
<p>I hope this article has provided a helpful introduction to the concept of prompt engineering and inspired you to explore its potential applications further. Happy language generation!</p>
]]></content:encoded></item><item><title><![CDATA[Creating a search engine using Python and Elasticsearch]]></title><description><![CDATA[Introduction
In this tutorial, we will be creating a search engine using Python and Elasticsearch. Elasticsearch is a distributed search engine built on top of the Apache Lucene library. It is a powerful tool for indexing, searching, and analyzing la...]]></description><link>https://blog.krtk.dev/creating-a-search-engine-using-python-and-elasticsearch</link><guid isPermaLink="true">https://blog.krtk.dev/creating-a-search-engine-using-python-and-elasticsearch</guid><category><![CDATA[Python 3]]></category><category><![CDATA[elasticsearch]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[python projects]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Wed, 28 Dec 2022 03:59:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1f04f023f270645f57ffa456896067b6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In this tutorial, we will be creating a search engine using Python and Elasticsearch. Elasticsearch is a distributed search engine built on top of the Apache Lucene library. It is a powerful tool for indexing, searching, and analyzing large volumes of data quickly and in near real-time.</p>
<p>Prerequisites:</p>
<p>Before we begin, you'll need to make sure you have the following prerequisites installed:</p>
<ul>
<li><p>Python 3: You can download the latest version of Python from the official website (<a target="_blank" href="https://www.python.org/downloads/"><strong>https://www.python.org/downloads/</strong></a>).</p>
</li>
<li><p>Elasticsearch: You can download Elasticsearch from the official website (<a target="_blank" href="https://www.elastic.co/downloads/elasticsearch"><strong>https://www.elastic.co/downloads/elasticsearch</strong></a>) and follow the installation instructions for your operating system.</p>
</li>
</ul>
<h2 id="heading-step-1-load-data-into-elasticsearch">Step 1: Load data into Elasticsearch</h2>
<p>The first step is to load your data into Elasticsearch. This can be done using the Elasticsearch API or by using a tool like Logstash to import data from a variety of sources. You can also use the Elasticsearch Python client to load data directly from Python.</p>
<p>Here's an example of how you can use the Elasticsearch Python client to load data from a JSON file:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Import the necessary libraries</span>
<span class="hljs-keyword">from</span> elasticsearch <span class="hljs-keyword">import</span> Elasticsearch
<span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Connect to Elasticsearch</span>
es = Elasticsearch()

<span class="hljs-comment"># Open the JSON file</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">'data.json'</span>, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
    <span class="hljs-comment"># Load the data into a Python dictionary</span>
    data = json.load(f)

<span class="hljs-comment"># Iterate through the dictionary and index each document</span>
<span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> data:
    <span class="hljs-comment"># Index the document</span>
    es.index(index=<span class="hljs-string">'index_name'</span>, doc_type=<span class="hljs-string">'doc_type'</span>, body=doc)
</code></pre>
<p>This code will open the 'data.json' file, load the data into a Python dictionary, and index each document in the 'index_name' index with the 'doc_type' type.</p>
<h2 id="heading-step-2-create-a-python-script-to-query-elasticsearch">Step 2: Create a Python script to query Elasticsearch</h2>
<p>Once your data is loaded into Elasticsearch, you can use Python to query the data and retrieve the results. The Elasticsearch Python client provides a convenient way to search and filter your data using the Elasticsearch Query DSL (Domain Specific Language).</p>
<p>Here's an example of how you can use Python to search for documents containing the term "search_term" in the "field_name" field:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Import the necessary libraries</span>
<span class="hljs-keyword">from</span> elasticsearch <span class="hljs-keyword">import</span> Elasticsearch
<span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Connect to Elasticsearch</span>
es = Elasticsearch()

<span class="hljs-comment"># Set up the search query</span>
query = {
    <span class="hljs-string">"query"</span>: {
        <span class="hljs-string">"match"</span>: {
            <span class="hljs-string">"field_name"</span>: <span class="hljs-string">"search_term"</span>
        }
    }
}

<span class="hljs-comment"># Execute the search</span>
results = es.search(index=<span class="hljs-string">"index_name"</span>, body=query)

<span class="hljs-comment"># Print the results</span>
print(json.dumps(results, indent=<span class="hljs-number">2</span>))
</code></pre>
<p>This code will search for documents in the 'index_name' index that contain the term 'search_term' in the 'field_name' field, and print the results as a JSON object.</p>
<p>Step 3: Display the search results</p>
<p>Finally, you'll need to display the search results to the user. This can be done using a simple HTML form or AJAX request and a Python script to handle the search request and display the results.</p>
<p>Here's an example of how you can write a search endpoint using python flask:</p>
<pre><code class="lang-python">
<span class="hljs-comment"># Import the necessary libraries</span>
<span class="hljs-keyword">from</span> elasticsearch <span class="hljs-keyword">import</span> Elasticsearch
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template, request

<span class="hljs-comment"># Connect to Elasticsearch</span>
es = Elasticsearch()

<span class="hljs-comment"># Set up the Flask app</span>
app = Flask(__name__)

<span class="hljs-comment"># Set up the search route</span>
<span class="hljs-meta">@app.route('/search', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>():</span>
    <span class="hljs-comment"># Get the search term from the form</span>
    search_term = request.form[<span class="hljs-string">'search_term'</span>]

    <span class="hljs-comment"># Set up the search query</span>
    query = {
        <span class="hljs-string">"query"</span>: {
            <span class="hljs-string">"match"</span>: {
                <span class="hljs-string">"field_name"</span>: search_term
            }
        }
    }

    <span class="hljs-comment"># Execute the search</span>
    results = es.search(index=<span class="hljs-string">"index_name"</span>, body=query)

    <span class="hljs-comment"># Extract the search hits from the results</span>
    search_hits = results[<span class="hljs-string">'hits'</span>][<span class="hljs-string">'hits'</span>]

    <span class="hljs-comment"># Render the search results template</span>
    <span class="hljs-keyword">return</span> flask.jsonify(search_hits=search_hits)

<span class="hljs-comment"># Run the app</span>
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run()
</code></pre>
<p>This code will set up a Flask app with a '/search' route that handles POST requests. When the search form is submitted, the search term is extracted from the form and used to build a search query. The search query is then executed and the search hits are extracted from the results.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we learned how to create a search engine using Python and Elasticsearch. We covered how to load data into Elasticsearch, how to use Python to query Elasticsearch and retrieve search results, and how to display the search results to the user.</p>
<p>Elasticsearch is a powerful and flexible search engine that can be easily integrated into a variety of applications. By following the steps outlined in this tutorial, you should now have a basic understanding of how to set up and use Elasticsearch in your own projects.</p>
<p>I hope this tutorial has been helpful and that you're now able to use Elasticsearch to power search functionality in your own applications. If you have any questions or feedback, please don't hesitate to leave a comment below. Happy searching!</p>
]]></content:encoded></item><item><title><![CDATA[Converting JSON to CSV with Python]]></title><description><![CDATA[JSON (JavaScript Object Notation) is a popular data format used for storing data in a structured manner. CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database.
If you have data stored in a ...]]></description><link>https://blog.krtk.dev/converting-json-to-csv-with-python</link><guid isPermaLink="true">https://blog.krtk.dev/converting-json-to-csv-with-python</guid><category><![CDATA[json parser]]></category><category><![CDATA[Python]]></category><category><![CDATA[json-schema]]></category><category><![CDATA[jsonwebtoken]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Tue, 27 Dec 2022 04:12:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cab145855c60960faac73727ffeedc22.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JSON (JavaScript Object Notation) is a popular data format used for storing data in a structured manner. CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database.</p>
<p>If you have data stored in a JSON file that you want to use in a spreadsheet or other data analysis tool, you can convert the JSON file to CSV using Python. This can be done using the <code>json</code> and <code>csv</code> modules, which are included in the Python standard library.</p>
<p>Here's a simple Python script that converts a JSON file to CSV:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> csv

<span class="hljs-comment"># Open the JSON file and load the data</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"data.json"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> f:
    data = json.load(f)

<span class="hljs-comment"># Open a new CSV file for writing</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"data.csv"</span>, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
    <span class="hljs-comment"># Create a CSV writer</span>
    writer = csv.DictWriter(f, fieldnames=data[<span class="hljs-number">0</span>].keys())
    <span class="hljs-comment"># Write the header row</span>
    writer.writeheader()
    <span class="hljs-comment"># Write the data rows</span>
    <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> data:
        writer.writerow(row)
</code></pre>
<p>This script reads in a JSON file called <code>data.json</code>, converts the data to a list of dictionaries, and then writes this data to a CSV file called <code>data.csv</code>. The field names for the CSV file are taken from the keys in the first dictionary in the list.</p>
<p>You can customize this script to fit your specific needs. For example, you could add command-line arguments to allow the user to specify the input and output filenames, or you could add error handling to handle cases where the JSON file is improperly formatted.</p>
]]></content:encoded></item><item><title><![CDATA[How to upload an image from VueJS to MongoDB using Python]]></title><description><![CDATA[Introduction
As a tech lead in a company, I have noticed that many people starting out in their careers struggle with uploading images to a database. There is so much information available online that it can be overwhelming and difficult to determine...]]></description><link>https://blog.krtk.dev/how-to-upload-an-image-from-vuejs-to-mongodb-using-python</link><guid isPermaLink="true">https://blog.krtk.dev/how-to-upload-an-image-from-vuejs-to-mongodb-using-python</guid><category><![CDATA[Python]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[axios]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Sun, 25 Dec 2022 05:01:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/314fc078fa4fea9974ea88ed01aeadc2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>As a tech lead in a company, I have noticed that many people starting out in their careers struggle with uploading images to a database. There is so much information available online that it can be overwhelming and difficult to determine the best way to do it. Personally, I believe in simplicity and keeping code simple and concise. With that in mind, I want to share the simplest way to upload an image in Vue.js.</p>
<p>In this tutorial, we will learn how to upload an image from a Vue.js frontend to a Python backend and store it in a MongoDB database. We will use the Flask web framework and the PyMongo library to create a simple server and connect to the database.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before starting this tutorial, you should have the following installed on your development machine:</p>
<ul>
<li><p>Node.js and npm (the Node.js package manager)</p>
</li>
<li><p>Python 3 and pip (the Python package manager)</p>
</li>
<li><p>MongoDB</p>
</li>
</ul>
<p>You should also have some basic knowledge of Vue.js and Python.</p>
<h3 id="heading-step-1-set-up-the-vuejs-frontend">Step 1: Set up the Vue.js frontend</h3>
<p>First, create a new Vue.js project using the Vue CLI. Open a terminal and run the following command:</p>
<pre><code class="lang-bash">vue create my-project
</code></pre>
<p>Follow the prompts to create a new Vue.js project.</p>
<p>Next, we will create a form to allow the user to select an image to upload. Open the <code>src/components/HelloWorld.vue</code> file and update it with the following code:</p>
<pre><code class="lang-javascript">&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"file"</span>&gt;</span>Select an image:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"fileInput"</span> @<span class="hljs-attr">change</span>=<span class="hljs-string">"uploadImage"</span>/&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
&lt;/template&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">methods</span>: {
    uploadImage() {
      <span class="hljs-keyword">const</span> file = <span class="hljs-built_in">this</span>.$refs.fileInput.files[<span class="hljs-number">0</span>]
      <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData()
      formData.append(<span class="hljs-string">'file'</span>, file)

      fetch(<span class="hljs-string">'/upload'</span>, {
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">body</span>: formData
      }).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(response)
      })
    }
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This code creates a form with a file input. When the user selects a file and clicks the "Open" button, the <code>uploadImage</code> method is called. This method creates a <code>FormData</code> object and appends the selected file to it. It then sends a <code>POST</code> request to the <code>/upload</code> endpoint with the <code>FormData</code> object as the request body.</p>
<h3 id="heading-step-2-set-up-the-python-backend">Step 2: Set up the Python backend</h3>
<p>Next, we will create the Python backend to handle the image upload. Create a new directory for the backend, and then create and activate a virtual environment:</p>
<pre><code class="lang-bash">mkdir backend
<span class="hljs-built_in">cd</span> backend
python3 -m venv venv
<span class="hljs-built_in">source</span> venv/bin/activate
</code></pre>
<p>Install the Flask and PyMongo libraries:</p>
<pre><code class="lang-bash">pip install flask pymongo
</code></pre>
<p>Create a new file <a target="_blank" href="http://app.py"><code>app.py</code></a> and add the following code to it:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request
<span class="hljs-keyword">from</span> pymongo <span class="hljs-keyword">import</span> MongoClient

app = Flask(__name__)
client = MongoClient()
db = client.mydatabase

<span class="hljs-meta">@app.route('/upload', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload</span>():</span>
    file = request.files[<span class="hljs-string">'file'</span>]
    <span class="hljs-keyword">if</span> file:
        db.images.insert_one({<span class="hljs-string">'image'</span>: file.read()})
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Success'</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'No file uploaded'</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run()
</code></pre>
<p>This code creates a Flask app and a MongoClient object. It defines a route <code>/upload</code> that accepts <code>POST</code> requests. When a request is received, it reads the image data from the <code>request.files</code> object and stores it</p>
<p>I hope you found this tutorial helpful. If you have any questions or would like me to cover a specific topic, please leave a comment below.</p>
]]></content:encoded></item><item><title><![CDATA[A quick recap on flask python]]></title><description><![CDATA[Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-...]]></description><link>https://blog.krtk.dev/a-quick-recap-on-flask-python</link><guid isPermaLink="true">https://blog.krtk.dev/a-quick-recap-on-flask-python</guid><category><![CDATA[Python 3]]></category><category><![CDATA[Flask Framework]]></category><category><![CDATA[python beginner]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Tue, 20 Dec 2022 02:50:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671504579948/filJ9PnTxE.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.</p>
<p>Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python programming language. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.</p>
<p>One of the key features of Flask is its simplicity. The framework is easy to set up and get started with, and it doesn't require any particular tools or libraries. This makes it an ideal choice for developers who want to get a web application up and running quickly.</p>
<p>Another key feature of Flask is its extensibility. The framework is built in such a way that it can be easily extended with additional functionality. This is done through the use of extensions, which are Python packages that add specific functionality to Flask. For example, there are extensions available for adding support for databases, handling user authentication, and working with templates.</p>
<p>In addition to its simplicity and extensibility, Flask is also known for its flexibility. It can be used to build a wide range of web applications, from small personal projects to large, complex applications. It is also a popular choice for building RESTful APIs, which are used to provide access to data and functionality over the internet.</p>
<p>Overall, Flask is a powerful and easy-to-use Python web framework that is well-suited for a wide range of web development projects. Whether you are a beginner looking to get started with web development or an experienced developer looking for a lightweight framework, Flask is a great choice.</p>
]]></content:encoded></item><item><title><![CDATA[Create an intent classification chatbot using python]]></title><description><![CDATA[Python is one of my favourite programming languages, it's easier to code and comes with a fantastic community. Recently I had a requirement to build a chatbot, primarily an intent classification chatbot.
What is an intent classification chatbot
Chatb...]]></description><link>https://blog.krtk.dev/create-an-intent-classification-chatbot-using-python</link><guid isPermaLink="true">https://blog.krtk.dev/create-an-intent-classification-chatbot-using-python</guid><category><![CDATA[Python]]></category><category><![CDATA[chatbot]]></category><category><![CDATA[coding]]></category><category><![CDATA[python projects]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 31 Oct 2022 06:52:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/2EJCSULRwC8/upload/v1667199099082/SfgI-BIqY.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Python is one of my favourite programming languages, it's easier to code and comes with a fantastic community. Recently I had a requirement to build a chatbot, primarily an intent classification chatbot.</p>
<h2 id="heading-what-is-an-intent-classification-chatbot">What is an intent classification chatbot</h2>
<p>Chatbot which can identify what the user is trying to say and based on that return output is nothing but an intent classification chatbot. In this type of chatbot, all the functions are predefined in the backend and based on the identified intent we execute the function. </p>
<p>For example, A food delivery app can have a chatbot and one of the questions can be </p>
<blockquote>
<p>What is my total expenditure on food in the month of January?</p>
</blockquote>
<p>Here the intent is to find the total amount spend in the month of January by User X, so once the intent is identified we will fire the function getTotalExpenditure(month)
Let's start building our chatbot for the food delivery app</p>
<p>I have created a flask project and will be using the <a target="_blank" href="https://snips-nlu.readthedocs.io/en/latest/tutorial.html">snipsnlu</a> library to build our chatbot. Snips NLU is a Natural Language Understanding python library that allows parsing sentences written in natural language, and extracting structured information.</p>
<h2 id="heading-training-dataset">Training Dataset</h2>
<p>Before starting with our code, we first need to train a basic dataset so that our system is tuned for most of the random questions. To train the dataset we need to create a 
<em>food_delivery_intent.yml</em> file</p>
<p>Which will look like following </p>
<pre><code class="lang-yaml"><span class="hljs-attr">type:</span> <span class="hljs-string">intent</span>
<span class="hljs-attr">name:</span> <span class="hljs-string">getTotalExpenditure</span>
<span class="hljs-attr">slots:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">month</span>
    <span class="hljs-attr">entity:</span> <span class="hljs-string">snips/datePeriod</span>
<span class="hljs-attr">utterances:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Give</span> <span class="hljs-string">me</span> <span class="hljs-string">my</span> <span class="hljs-string">total</span> <span class="hljs-string">spend</span> <span class="hljs-string">for</span> [<span class="hljs-string">month</span>]
  <span class="hljs-bullet">-</span> <span class="hljs-string">Get</span> <span class="hljs-string">my</span> <span class="hljs-string">current</span> [<span class="hljs-string">month</span>] <span class="hljs-string">expenditure</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">How</span> <span class="hljs-string">much</span> <span class="hljs-string">i</span> <span class="hljs-string">have</span> <span class="hljs-string">spent</span> <span class="hljs-string">on</span> <span class="hljs-string">food</span> <span class="hljs-string">in</span> [<span class="hljs-string">month</span>]
  <span class="hljs-bullet">-</span> <span class="hljs-string">What</span> <span class="hljs-string">is</span> <span class="hljs-string">my</span> <span class="hljs-string">total</span> <span class="hljs-string">expenditure</span> <span class="hljs-string">on</span> <span class="hljs-string">food</span> <span class="hljs-string">for</span> [<span class="hljs-string">month</span>]
</code></pre>
<p>The above files seem pretty clear but let's go through them step by step</p>
<ol>
<li>Here the type of the file is intent</li>
<li>getTotalExpenditure is the name of the intent, this name can be anything but for the sake of simplicity I have made this look like a function name so that once our intent is identified we execute the function</li>
<li>Slots are the section in the utterances which can be dynamic for example they can be a place, month, date, etc.</li>
<li>The utterances are the sample utterances which have slots in square brackets. Slots can have any of the 12 months so we write them inside the square bracket.</li>
</ol>
<p>You can read more about the training dataset here <a target="_blank" href="https://snips-nlu.readthedocs.io/en/latest/dataset.html">https://snips-nlu.readthedocs.io/en/latest/dataset.html</a>.</p>
<p>Now it's time to parse the YAML file into JSON using the CLI provided by snipsnlu </p>
<pre><code class="lang-ssh">snips-nlu generate en /path-to-food-delivery-yaml

snips-nlu generate-dataset en sampledataset/food_delivery_intent.yml &gt; food_delivery_intent.json
</code></pre>
<h2 id="heading-time-to-run-the-code">Time to run the code.</h2>
<p>I have created a flask app to demonstrate the chatbot properly below is the code for my app</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> io
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> flask
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, jsonify

<span class="hljs-keyword">from</span> snips_nlu <span class="hljs-keyword">import</span> SnipsNLUEngine

app = Flask(__name__)
<span class="hljs-keyword">with</span> io.open(<span class="hljs-string">"food_delivery_intent.json"</span>) <span class="hljs-keyword">as</span> f:
    sample_dataset = json.load(f) <span class="hljs-comment">#loading the food delivery intent json that we created using cli</span>

nlu_engine = SnipsNLUEngine() <span class="hljs-comment">##Sninluengine object</span>

nlu_engine.fit(sample_dataset) <span class="hljs-comment">## Loading the dataset in the snipnlu object</span>

<span class="hljs-meta">@app.route("/parse/", methods=["GET"])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">parse</span>():</span>
    sample_text=flask.request.json[<span class="hljs-string">'sample_text'</span>] <span class="hljs-comment">## sample text from our postman request</span>
    parsing = nlu_engine.parse(sample_text) <span class="hljs-comment"># Parsing the utterence sent from postman request</span>
    <span class="hljs-keyword">return</span> flask.jsonify(data=parsing)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
  app.run(debug=<span class="hljs-literal">True</span>, host=<span class="hljs-string">'0.0.0.0'</span>, port=<span class="hljs-number">5000</span>)
</code></pre>
<p>I have commented on most parts of the code, still, you can access the whole code here and let me know if you have any doubts in the comment section. </p>
<h2 id="heading-lets-send-the-request-using-the-postman">Let's send the request using the postman</h2>
<p>Using postman we will send sample utterances and have a look a the response generated from our flask app using nlu engine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667198061190/Zy8V4gkyW.png" alt="Screenshot 2022-10-31 at 12.03.55 PM.png" /></p>
<p>In the above screenshot, you can see that, we have passed a sample utterance <em>"How much did I spend in march" </em>. 
On the right side, you can see the response, where the intent was successfully identified as getTotalExpenditure with a probability of 69% along with that, we can also see a slot as march which is useful for running our code in the backend with the month as the March.</p>
<p>There is an endless possibility using a chatbot and one can fine-tune the chatbot based on the inputs, Above code, just demonstrate how easy it is to make an intent classification chatbot just using python. </p>
<p>I am attaching a link to the above repository <a target="_blank" href="https://github.com/kartikpuri95/chatbot-intent">here</a> which is a docker project here, you can simply compose up the docker image and run the project.</p>
<p>I hope you found this article to be useful do share and comment if you like it</p>
<p>https://github.com/kartikpuri95/chatbot-intent</p>
]]></content:encoded></item><item><title><![CDATA[Let's create a Micro Twitter site on Blockchain]]></title><description><![CDATA[Web3 and Blockchain is a hot topic in town, how about creating a micro Twitter site on blockchain where users can come and post a small message which will be visible to all the visitors on the site.

Stop talking show me the code!!

The Tech stack we...]]></description><link>https://blog.krtk.dev/lets-create-a-micro-twitter-site-on-blockchain</link><guid isPermaLink="true">https://blog.krtk.dev/lets-create-a-micro-twitter-site-on-blockchain</guid><category><![CDATA[webdev]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Web3]]></category><category><![CDATA[Ethereum]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Mon, 28 Mar 2022 04:24:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1648441413954/fUo8MYGFP.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Web3 and Blockchain is a hot topic in town, how about creating a micro Twitter site on blockchain where users can come and post a small message which will be visible to all the visitors on the site.</p>
<blockquote>
<p>Stop talking show me the code!!</p>
</blockquote>
<p>The Tech stack we will be using to build this project will </p>
<ul>
<li>Solidity -: For building a smart contract that will store messages on blockchain</li>
<li>ReactJS -: For building are frontend which will also be interacting with our smart contract</li>
<li>TailwindCSS-: Tailwind is my goto CSS library, I will be using tailwind to make my microsite more beautiful</li>
<li>Hardhat-: We will be using hardhat for the development environment to compile, deploy, test, and debug your Ethereum software. You can find more about it  <a target="_blank" href="https://hardhat.org/getting-started/#overview">here</a> </li>
</ul>
<h1 id="heading-lets-create-our-solidity-contract">Let's create our solidity contract</h1>
<p>We are using solidity to write our smart contract which will also be reading and writing messages on the blockchain.</p>
<pre><code>mkdir micro_twitter
cd micro_twitter
npm init <span class="hljs-operator">-</span>y
npm install <span class="hljs-operator">-</span><span class="hljs-operator">-</span>save<span class="hljs-operator">-</span>dev hardhat
</code></pre><p>Cool, now we should have Hardhat. Let's get a sample project going.</p>
<p>Run:</p>
<pre><code><span class="hljs-attribute">npx</span> hardhat
</code></pre><p>This will create a sample project with hello_world contract, let's update that contract with our micro Twitter code and name our contract as MicroTwitter.sol. I have commented on most of the code, but feel free to reach out to me to understand any part of it</p>
<pre><code><span class="hljs-comment">// SPDX-License-Identifier: UNLICENSED</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.8.4;</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"hardhat/console.sol"</span>;
<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">MicroTwitter</span> </span>{
    <span class="hljs-keyword">uint256</span> totalTweet;
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">private</span> seed;
    <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">payable</span></span></span>{
        console.log(<span class="hljs-string">"Hi from contract console"</span>);
        seed <span class="hljs-operator">=</span> (<span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span> <span class="hljs-operator">+</span> <span class="hljs-built_in">block</span>.<span class="hljs-built_in">difficulty</span>) <span class="hljs-operator">%</span> <span class="hljs-number">100</span>;

    }
    <span class="hljs-comment">// Unlike any other evnts </span>
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">NewTweet</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> <span class="hljs-keyword">from</span>, <span class="hljs-keyword">uint256</span> timestamp,<span class="hljs-keyword">string</span> message</span>)</span>;
    <span class="hljs-comment">// Struct wave</span>
    <span class="hljs-keyword">struct</span> <span class="hljs-title">Tweet</span>{
        <span class="hljs-keyword">address</span> twitters_address;
        <span class="hljs-keyword">string</span> tweet;
        <span class="hljs-keyword">uint256</span> timestamp;
    }
    <span class="hljs-comment">// Decalare variable tweets from new struct Tweet</span>
    Tweet[] tweets;
       <span class="hljs-comment">/*
     * This is an address =&gt; uint mapping, meaning I can associate an address with a number!
     * In this case, I'll be storing the address with the last time the user twitted at us.
     * just to avoid spam tweets as this is blockchain
     */</span>
    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">uint256</span>) <span class="hljs-keyword">public</span> lastTweetAt;


    <span class="hljs-comment">/*
    This tweet function stores the tweet into the variables tweet
    */</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tweet</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> <span class="hljs-keyword">memory</span> _message</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span></span>{
         <span class="hljs-built_in">require</span>(
            lastTweetAt[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">+</span> <span class="hljs-number">15</span> <span class="hljs-literal">minutes</span> <span class="hljs-operator">&lt;</span> <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>,
            <span class="hljs-string">"Wait 15m"</span>
        );
        lastTweetAt[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">=</span> <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>;
        totalTweet<span class="hljs-operator">+</span><span class="hljs-operator">=</span><span class="hljs-number">1</span>;
        console.log(<span class="hljs-string">"%s has twitted!"</span>, <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>);
        tweets.<span class="hljs-built_in">push</span>(Tweet(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>,_message,<span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>));
        console.log(<span class="hljs-string">"Random number! %d"</span>, seed);
         <span class="hljs-keyword">emit</span> NewTweet(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>, _message);

    }
    <span class="hljs-comment">// get all waves</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllTweets</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params">Tweet[] <span class="hljs-keyword">memory</span></span>)</span>{
        <span class="hljs-keyword">return</span> tweets;
    }
    <span class="hljs-comment">// kind of a get request</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTotalTweets</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint256</span></span>)</span>{
        console.log(<span class="hljs-string">"We have %d total waves"</span>,totalTweet);
        <span class="hljs-keyword">return</span> totalTweet;
    }

}
</code></pre><p>So we have created our backend code, now its time to wire up our frontend to our own smart contract and take a step further</p>
<h1 id="heading-setup-frontend">Setup Frontend</h1>
<p>Inside our project let's add our frontend project name <em>micro_twitter_tailwind</em> using the following command</p>
<pre><code>npx create<span class="hljs-operator">-</span>react<span class="hljs-operator">-</span>app micro_twitter_tailwind
cd micro_twitter_tailwind
</code></pre><p>Once the project is created, we will add tailwind to our project to quickly scaffold our micro Twitter frontend using the following command</p>
<pre><code>npm install <span class="hljs-operator">-</span>D tailwindcss postcss autoprefixer
npx tailwindcss init <span class="hljs-operator">-</span>p
</code></pre><p>Refer to this link to setup react tailwind project <a target="_blank" href="https://tailwindcss.com/docs/guides/create-react-app">here</a> </p>
<p>Using tailwind I have created a very basic design, like below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648438476399/HW0NVUzub.png" alt="tailwind_micro_twitter.png" /></p>
<h3 id="heading-connect-our-wallet">Connect Our Wallet</h3>
<p>We have already created our smart contract, now its time to connect our wallet so that we can access our contract</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648439046177/Ls-HBCYsI.png" alt="ss2.png" /></p>
<p>Code to connect, the wallet. Here we are already assuming that metamask is installed which exposes the Ethereum object in the windows</p>
<pre><code>  const connectWallet <span class="hljs-operator">=</span> async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">try</span> {
      const { ethereum } <span class="hljs-operator">=</span> window; <span class="hljs-comment">//get the ethereum object from window</span>
      <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>ethereum) {
        alert(<span class="hljs-string">"get metamask"</span>)
        <span class="hljs-keyword">return</span>;
      }
      const accounts <span class="hljs-operator">=</span> await ethereum.request({ method: <span class="hljs-string">"eth_requestAccounts"</span> });
      console.log(<span class="hljs-string">"Connected"</span>, accounts[<span class="hljs-number">0</span>]); <span class="hljs-comment">//get the current account</span>
      setCurrentAccount(accounts[<span class="hljs-number">0</span>]); <span class="hljs-comment">//set the current account</span>
    } <span class="hljs-keyword">catch</span> (err) {
      console.log(err)
    }
  }
</code></pre><p>You can find the full code inside my Github. </p>
<h3 id="heading-get-the-list-of-total-tweets">Get the list of total tweets</h3>
<p>Here we will be referencing our contract function which we have written in the solidity code</p>
<pre><code>  <span class="hljs-comment">// Get all tweets</span>
  const  getAllTweets <span class="hljs-operator">=</span> async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    const { ethereum } <span class="hljs-operator">=</span> window
    <span class="hljs-keyword">if</span> (ethereum) {
      const provider <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ethers.providers.Web3Provider(ethereum);
      const signer <span class="hljs-operator">=</span> provider.getSigner()
      const tweetContract <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ethers.Contract(contractAddress, contractABI, signer);
      const tweets <span class="hljs-operator">=</span> await tweetContract.getAllTweets(); <span class="hljs-comment">//our contract function</span>
      let tweetsCleaned <span class="hljs-operator">=</span> [];
      tweets.forEach(twt <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
        tweetsCleaned.<span class="hljs-built_in">push</span>({
          twitters_address: twt.twitters_address,
          timestamp: <span class="hljs-keyword">new</span> Date(twt.timestamp <span class="hljs-operator">*</span> <span class="hljs-number">1000</span>),
          tweet: twt.tweet
        });
      });

      setAllTweets(tweetsCleaned);
    }
  }
</code></pre><h3 id="heading-send-tweet">Send tweet</h3>
<p>Here we will be referencing our contract function which we have written in the solidity code</p>
<pre><code> const tweet <span class="hljs-operator">=</span> async () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">try</span> {
      setIsMinting(<span class="hljs-literal">true</span>)
      const { ethereum } <span class="hljs-operator">=</span> window;
      <span class="hljs-keyword">if</span> (ethereum) {
        const provider <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ethers.providers.Web3Provider(ethereum);
        const signer <span class="hljs-operator">=</span> provider.getSigner();
        <span class="hljs-comment">// How to connect to the created contract</span>
        const microTwitterContract <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ethers.Contract(contractAddress, contractABI, signer);

        <span class="hljs-comment">// Get the count of total tweet</span>
        let count <span class="hljs-operator">=</span> await microTwitterContract.getTotalTweets();
        console.log(<span class="hljs-string">"Retrieved total wave count..."</span>, count.toNumber());
        <span class="hljs-comment">// Send the transaction</span>
        const twettxn <span class="hljs-operator">=</span> await microTwitterContract.tweet(message);

        console.log(<span class="hljs-string">"Mining"</span>, twettxn.hash)
        <span class="hljs-comment">// Wait for the transaction to complete</span>
        await twettxn.wait();
        console.log(<span class="hljs-string">"Minted--"</span>, twettxn.hash)
        setIsMinting(<span class="hljs-literal">false</span>)
        count <span class="hljs-operator">=</span> await microTwitterContract.getTotalTweets();
        console.log(<span class="hljs-string">"Retrieved total wave count..."</span>, count.toNumber());
        getAllTweets()
      }
      <span class="hljs-keyword">else</span> {
        console.log(<span class="hljs-string">"Ethereum object doesn't exist!"</span>);
      }
    }
    <span class="hljs-keyword">catch</span> (<span class="hljs-function"><span class="hljs-keyword">error</span>) </span>{
      console.log(<span class="hljs-function"><span class="hljs-keyword">error</span>)
    }
  }</span>
</code></pre><p>Once we are done with the wiring up frontend and smart contract, it's time to deploy our contract to test network AKA Rinkeby Test Network. You can refer to my other article to deploy the smart contract <a target="_blank" href="https://chopcoding.com/how-we-created-our-own-crypto-token-while-chit-chatting-in-the-office">here</a></p>
<p>Hoorayyyyy Our Contract is deployed 🎉🎉</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648439975342/lqgW4ekwg.png" alt="test_network.png" /></p>
<p>Using vercel I deployed my frontend <a target="_blank" href="https://micro-twitter-tailwind.vercel.app/#_">here</a>
and made a very first tweet on the blockchain</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648440695844/E5ORBykzP.png" alt="first_Tweet.png" /></p>
<p>You can find the transactions details here 
https://rinkeby.etherscan.io/tx/0xbffa052865aedd83e8d4ae3ed8c41bd85ff77e4f50c1b3f217fe55ad61defdff</p>
<p>Git repo of this project <a target="_blank" href="https://github.com/kartikpuri95/micro-twitter-tailwind">https://github.com/kartikpuri95/micro-twitter-tailwind</a></p>
<h2 id="heading-we-have-deployed-our-own-micro-twitter">We have deployed our own micro twitter 🎉🎉</h2>
<p>I hope you like this post, you can follow me on twitter for more such updates and do give a reaction</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/chopcoding/status/1484746863249342464">https://twitter.com/chopcoding/status/1484746863249342464</a></div>
<p>You can get in touch with me <a target="_blank" href="https://www.kartikpuri.com/">kartikpuri.com</a></p>
]]></content:encoded></item><item><title><![CDATA[My favorite tailwind UI kit for your next project]]></title><description><![CDATA[If you have been following me on Twitter, you would have realized that tailwind is by far my favorite library to use. The level of customization and modification you could do in tailwind is best. Combining the power of tailwind along with a few libra...]]></description><link>https://blog.krtk.dev/my-favorite-tailwind-ui-kit-for-your-next-project</link><guid isPermaLink="true">https://blog.krtk.dev/my-favorite-tailwind-ui-kit-for-your-next-project</guid><category><![CDATA[UI]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Tailwind CSS Tutorial]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Tue, 08 Feb 2022 04:36:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644294976209/ir5K4Pzku.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have been following me on Twitter, you would have realized that tailwind is by far my favorite library to use. The level of customization and modification you could do in tailwind is best. Combining the power of tailwind along with a few libraries you could kick out a beautiful-looking project at no time.</p>
<p>Let's find out a few awesome UI kits for your next project</p>
<h1 id="heading-tailblocks">Tailblocks</h1>
<p>Tailblocks gives you ready-to-use blocks built entirely using Tailwind CSS that you can use in your own projects. Unlike other UI kits, this is not a dependency to add in your project, but instead, provide ready copy-paste code that you can straightway use in your project </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644213452074/Qk0QK4feP.png" alt="tailblocks.png" /></p>
<p><a target="_blank" href="https://tailblocks.cc/">https://tailblocks.cc/</a></p>
<h1 id="heading-wicked-blocks">Wicked Blocks</h1>
<p>This is similar to tailblocks and provides you with over 120  fully responsive components and blocks you can copy-paste into your Tailwind projects</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644294451389/dWAktytXj.png" alt="wickedblocks.png" /></p>
<p><a target="_blank" href="https://blocks.wickedtemplates.com/">https://blocks.wickedtemplates.com/</a></p>
<h1 id="heading-daisyui">DaisyUI</h1>
<p>This is one of my favorite kits, unlike the tailblocks and wicked blocks, this adds a dependency to your project. But it gives a set of ready-made classes built on tailwind to create a beautiful-looking project at no time. Also, it makes your code looks much cleaner as you have to write very less classes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644213498374/dClt82fOG.png" alt="daisy_ui.png" />
<a target="_blank" href="https://daisyui.com/">https://daisyui.com/</a></p>
<h1 id="heading-bonus-section">Bonus Section</h1>
<h2 id="heading-tailwind-headless-ui">Tailwind Headless UI</h2>
<p>This is not a UI kit but completely unstyled, UI components that can be integrated beautifully with tailwind CSS. For example, if you want to build a menu(Mobile and Desktop) functionality in your project you could easily use the predefined component and add tailwind CSS on top of that to make it both functional and beautiful</p>
<p>Apart from the above-mentioned libraries, there are multiple libraries/UI kits available in the market but according to me, these are enough to finish any medium grade to production graded software or application, the rest is just the noise</p>
<p>I hope you like my post do follow me on Twitter for more amazing content related to Web2 and Web3.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/chopcoding/status/1490907504435335169">https://twitter.com/chopcoding/status/1490907504435335169</a></div>
]]></content:encoded></item><item><title><![CDATA[What future holds for NFT's]]></title><description><![CDATA[The only problem that I personally feel about NFT is that it's still hard to adapt to the masses. There is so much happening behind the scene or inside the blockchain which is a little complicated for any layman to learn and understand.
Managing the ...]]></description><link>https://blog.krtk.dev/what-future-holds-for-nfts</link><guid isPermaLink="true">https://blog.krtk.dev/what-future-holds-for-nfts</guid><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[NFT]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[crypto]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Chop Coding]]></dc:creator><pubDate>Fri, 04 Feb 2022 06:39:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643956178631/D_J080570.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The only problem that I personally feel about NFT is that it's still hard to adapt to the masses. There is so much happening behind the scene or inside the blockchain which is a little complicated for any layman to learn and understand.</p>
<p>Managing the user experience is very critical in this ecosystem and over time I believe that more and more NFT projects will shift towards Direct-To-Customer(DTC) marketplaces just how <strong>larva labs</strong> are doing right now.</p>
<ol>
<li><p>When we talk about NFT's our first idea is how we can make any digital entity transferrable though this is a very good use case we can't neglect the practical part where there might be cases where transfer of NFT ownership wouldn't be a good idea, for example, Driving License, Certifications, Degrees, etc.</p>
</li>
<li><p>NFT's are perfect for getting access across physical and as well as digital worlds. NFT's open up whole new possibilities to unlock temporary or permanent access. Imagine you have an NFT to visit some live concert, or an NFT to unlock an entry in some guest lecture or conference. </p>
</li>
<li><p>For all the creators or brands or organizations it is very easy to drop bounties within the communities which will eventually get crazy traffics and easier branding. NFT's can be used for rewarding, for bounties, or for referring members to the community</p>
</li>
<li><p>NFTs in gaming would be an amazing idea where I can buy a game character to play some game and once I am done with the game I can obviously sell that NFT to someone else who is also interested to play the same game. A good use case I recently read was NFT of Mario game where Nintendo can sell Mario NFT instead of a game and only those user who owns Mario NFT can play the game. </p>
</li>
<li><p>Unlock early access using NFTs, brands or creators can exchange NFTs before the launch of the product. This NFT can unlock early access to products, releases, or potential profit sharing</p>
</li>
</ol>
<p>In the end, I would still say that we are still in a very early phase of this ecosystem and there are still things coming up. And whenever there is a launch of any ecosystem there would eventually be things getting built around that ecosystem, there will be lots of trial error around this ecosystem, there will be many failed products around this ecosystem so it a still a bumpy road ahead, and let's see what exactly web3.0 holds for us.</p>
<p>I hope you like my thoughts do follow me on Twitter</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/chopcoding/status/1480150119148568581">https://twitter.com/chopcoding/status/1480150119148568581</a></div>
]]></content:encoded></item></channel></rss>