<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by KIHSA Rai on Medium]]></title>
        <description><![CDATA[Stories by KIHSA Rai on Medium]]></description>
        <link>https://medium.com/@ashikthulungrai7?source=rss-5108acd168c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wQwUnV2Kq8RveP22rh40iA.png</url>
            <title>Stories by KIHSA Rai on Medium</title>
            <link>https://medium.com/@ashikthulungrai7?source=rss-5108acd168c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:05:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashikthulungrai7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Your Own Weather Forecasting Agentic AI: A Step-by-Step Guide with n8n]]></title>
            <link>https://ashikthulungrai7.medium.com/build-your-own-weather-forecasting-agentic-ai-a-step-by-step-guide-with-n8n-d2cea4a73080?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2cea4a73080</guid>
            <category><![CDATA[n8n-workflow]]></category>
            <category><![CDATA[weather-forecasts]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[n8n-workflow-automation]]></category>
            <category><![CDATA[agentic-ai-solution]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 22:00:14 GMT</pubDate>
            <atom:updated>2026-08-04T22:00:14.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVVoUI-PscVdrsf9YcazoA.png" /><figcaption>Generated this image using Gemini with my n8n workflow reference</figcaption></figure><p>In the realm of artificial intelligence, a significant shift is occurring from purely analytical AI to <strong>Agentic AI</strong>. While standard AI can analyze large datasets and provide insights, <strong>Agentic AI</strong> goes a step further: it <em>acts</em>. It can understand a request, determine the necessary steps, and use tools to achieve a goal.</p><p>Imagine a user asking, “Is it going to rain this weekend?” A standard chatbot might provide a historical average or a vague answer. An <strong>Agentic Weather AI</strong>, on the other hand, understands the location (from the user or context), uses a specialized tool to fetch real-time data, and then interprets that data to give a precise, conversational answer.</p><p>In this step-by-step guide, we will build a conversational weather assistant using <a href="https://n8n.io/"><strong>n8n</strong></a>, <strong>Google Gemini</strong>, and the <a href="https://home.openweathermap.org/"><strong>OpenWeatherMap</strong></a><strong> API</strong>.</p><blockquote>Clap and Comment, if you want a tutorial on what is n8n, and I will create a tutorial.</blockquote><h3>1. Prerequisites</h3><p>Before starting, ensure you have:</p><ol><li><strong>n8n Account:</strong> An <a href="https://n8n.io/cloud/">n8n Cloud</a> account(initial 14 days are free) or a self-hosted local instance.</li><li><strong>Google Gemini Api Key:</strong> Generated via Google AI Studio.</li><li><strong>OpenWeatherMap API Key:</strong> Sign up for a free account on <a href="https://home.openweathermap.org/"><strong>OpenWeatherMap</strong></a><strong> </strong>to get an API key.</li></ol><blockquote>Clap and Comment if you want to know how to set up n8n for free in local system</blockquote><h3>2. Architecture Overview</h3><p>Our n8n workflow consists of five interconnected components:</p><ol><li><strong>Trigger:</strong> The entry point for our workflow. On Chat Message / Webhook (handles incoming user messages). This makes our agent accessible via simple HTTP requests.</li><li><strong>AI Agent Node:</strong> It’s the central hub that receives the user’s message, manages the conversation, and decides which tool to use.</li><li><strong>Chat Model:</strong> Google Gemini (powers natural language understanding).</li><li><strong>Memory:</strong> n8n Simple Memory This allows the agent to maintain context over multiple messages (retains multi-turn context like remembering the location mentioned in the previous chats).</li><li><strong>Tools:</strong> Two OpenWeatherMap nodes (one for current conditions, one for 5-day forecasts).</li></ol><p>Now, let’s build it! 😜</p><h3>Step 1: Set Up the Webhook Trigger</h3><p>Create a new empty workflow. Add an On chat message (Chat Trigger) node. This automatically equips your agent with a test chat interface and an accessible API endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_mQynJSxadGgRaE0PZdww.gif" /><figcaption><strong>Illustration on how to create a Chat Trigger</strong></figcaption></figure><h3>Step 2: Configure the AI Agent Node</h3><ol><li>Add an <strong>AI Agent</strong> node to the canvas and connect it to the Chat Trigger.</li><li>It will connect from the <strong>Webhook</strong> node (chat node). Now when message/prompt is given to the chat Node it gets triggered and the message/prompt is forwarded to the AI Agent Node.</li><li>The AI Agent had multiple connecting nodes <strong>(Chat Model, Memory, Tool)</strong> , for now, don’t worry about that.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMlrjC_-ctVaCrFOVCKdbg.gif" /><figcaption><strong>Illustration on how to bind AI Agent to Chat Trigger</strong></figcaption></figure><h3>Step 3: Integrate the Google Gemini Model</h3><p>We have created the AI Agent Node, but it is just a dummy node. It cannot perform any task. So we need to make it start by adding the Chat Model, Memory and the required tools. In this tutorial we will use Gemini Chat model as it is free as of today.</p><ol><li>Click on the <strong>Chat Model’s + icon</strong>, which lists all the available chat models. Today we will be using <strong>Google Gemini Chat Model.</strong></li><li><strong>Credential:</strong> You need to create a Gemini API Key and need to use it to authenticate your requests.</li><li><strong>Models: </strong>There are multiple models available, you can select that best suits me. In this tutorial we will use gemini-3.1-flash-lite</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jl641eLqCZ0Cz1wC_xkKAg.gif" /><figcaption><strong>Illustration on how to bind Gemini Model to AI Agent</strong></figcaption></figure><blockquote>Clap and Comment, if you want to learn how to create a Gemini API key for n8n</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-Kvx-RiCYRXLlbRfDoFIQ.png" /><figcaption><strong>Adding Credentials and Selecting Gemini Model</strong></figcaption></figure><p>Now we can test the basic Workflow that we created. We can open the chat and then give our prompt and get the response as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbXV6jGSbTX4Nv8P58fUkA.png" /><figcaption><strong>Illustration of testing the workflow</strong></figcaption></figure><h3>Step 4: Add Conversation Memory</h3><p>We will use <strong>n8n Simple Memory </strong>in this tutorial. Connect the <strong>Simple Memory</strong> node to the Memory socket on the AI Agent.<br>Set the <strong>Context Window Length</strong> to 5 or 10.</p><blockquote><em>Why this matters:</em> Without memory, asking <em>“What’s the weather in Darjeeling?”</em> followed by <em>“What about tomorrow?”</em> fails because the model forgets “<em>Darjeeling</em>”. Memory preserves this context.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UChSSIMIyqgCRO76yVoIGg.gif" /><figcaption><strong>Illustration on how to bind N8N Simple Mempry AI Agent</strong></figcaption></figure><p>Below example shows why memory is important to preserve the context while conversing with the chat model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuZ3Z35sfwwP7QC0WXnXig.png" /><figcaption><strong>Illustration showing why memory is important to preserve context</strong></figcaption></figure><h3>Step 5: Equip with OpenWeatherMap Tools</h3><p>Now to fetch the weather detail we will use the openWeather API. We will create two separate nodes for the two different API calls (current weather and future weather). Each node will be connected to the Tool input on the <strong>AI Agent</strong> node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3znnggv4cIZ4YUjex3i7hQ.gif" /><figcaption><strong>Illustration on how to add OpenWeatherMap Tool</strong></figcaption></figure><p>Once the tool is added we need to create the <strong>OpenWeatherMap API Key</strong> and add in the tool. <br>For current weather details we need to select <strong>Current Weather in the Operations</strong><br>The API needs the location detail such as the <strong>CityName and the CountryCode</strong>. We cannot hardcode this value as it depends on the message/prompt/query. So, instead we need to infer these details from the prompt using below expression.</p><pre>{{ $fromAI(&quot;city&quot;, &quot;The city name and 2-letter country code separated by comma, e.g. Darjeeling, IN&quot;) }}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGEQH3fPtjsqSWVBEmD4FQ.png" /><figcaption><strong>Illustration on how to extract the CityName from the message/prompt</strong></figcaption></figure><p>Similarly for the future weather details we need to add the <strong>OpenWeatherMap</strong> once more but in the Operation we need to select <strong>5 Day Forecast. </strong>Then our weather forecast is complete as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERIGt5cUIoqoqColbKoMAw.png" /><figcaption><strong>Illustration showing the complete workflow for weather forecast.</strong></figcaption></figure><p>Below is the illustration of whole workflow works to get the weather forecast for any city given in the prompt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TX8IvcWPkAI_xkKQpdPmIQ.gif" /></figure><h3>Testing &amp; Response Example</h3><p>Click <strong>Open Chat</strong> in n8n and run a multi-turn conversation:</p><p><strong>User:</strong> <em>What is the current weather in Darjeeling?<br></em><strong>Agent:</strong> <em>The current weather in Darjeeling is 17.3°C with light rain. Humidity is at 96% with heavy cloud cover.</em></p><p><strong>User:</strong> <em>Give me the forecast for the next 3 days.<br>(The Agent uses memory to retain “Darjeeling” and triggers the 5-day forecast tool.)<br></em><strong>Agent:<br></strong>The weather in Darjeeling for the next three days will remain consistently <br>rainy with high humidity:</p><ul><li><strong>Aug 5:</strong> Light rain throughout the day. Temps between 16°C and 19°C.</li><li><strong>Aug 6:</strong> Rain continuing, turning moderate by evening. Temps between 16°C and 23°C.</li><li><strong>Aug 7:</strong> Scattered light rain. Temps ranging from 16°C to 20°C.</li></ul><h3>Next Steps &amp; Enhancements (Missing Content Added)</h3><ul><li><strong>Error Handling:</strong> Configure fallback outputs on the tool nodes if the OpenWeatherMap API limit is reached or if an invalid city name is given.</li><li><strong>Production Deployment:</strong> Toggle the workflow from <strong>Draft</strong> to <strong>Active</strong> to expose the production webhook URL for production web applications or Telegram/Slack bots.</li></ul><h3>Summary</h3><p>You’ve built an autonomous AI agent capable of managing memory, identifying missing parameter information, calling external weather APIs, and formatting responses.</p><ol><li>How to create chat Trigger,</li><li>Bind AI Agent to the chat trigger.</li><li>How to select a Chat Model and add to the AI Agent.</li><li>How to add Memory to the AI Agent to preserve context</li><li>How to add OpenWeatherMap Tool to AI Agent to get weather forecast</li></ol><blockquote><em>Enjoyed this build? Leave a clap or comment if you’d like a follow-up guide on self-hosting n8n or building multi-agent systems!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2cea4a73080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AWS MQTT]]></title>
            <link>https://ashikthulungrai7.medium.com/mqttx-client-with-aws-mqtt-broker-7e7007dc023b?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7007dc023b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[node-red]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[mqtt-client]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 12:23:19 GMT</pubDate>
            <atom:updated>2024-02-21T10:03:22.042Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to configure and test your AWS MQTT Broker Publish/Subscribe service with the MQTTX client tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXxPcrYAanTUWQecvO7mHA.gif" /><figcaption>image source: <a href="https://mqttx.app/">link</a></figcaption></figure><p>Hello Jawans, 😎, today we will be learning about <strong>MQTT</strong>, the basics of <strong>AWS</strong>, <strong>AWS-Mqtt</strong>, <strong>MQTTX Client</strong>, and how to <strong>Publish and Subscribe</strong> to<strong> </strong><strong>MQTT Topic</strong>. Howzzzzz the <strong>Joshhhhhhhh </strong>…???… ⭐🤩🔥</p><blockquote>To learn about MQTT Architecture and how it works in detail read my previous tutorial:<strong> </strong><a href="https://medium.com/@ashikthulungrai7/everything-to-know-about-mqtt-message-queue-telemetry-transport-acbf32d1b761"><strong>Mqtt part1</strong></a></blockquote><p>📝 In this blog we will not focus on how to set up an MQTT Broker in AWS. If you want a separate tutorial on this, please clap 👏 and comment.</p><h3>1. Setting up AWS MQTT Thing</h3><p>To use the AWS MQTT service, we need to:<br><strong>I. First create an AWS account</strong>. <br><strong>II.</strong> Look for the <strong>IOT Core </strong>option, if not available then simply use the search box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azmcQLABy5SPTUSglluSxw.png" /></figure><p><strong>III. </strong>Look for an Option <strong>Thing </strong>and C<strong>reate a new Thing </strong>or use an <strong>existing Thing.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5BvZgwVz7SqYkIirTLjgA.png" /><figcaption>Creating a new AWS Thing</figcaption></figure><p><strong>IV. </strong>After creating <strong>Thing </strong>go to the <strong>Security Tab </strong>and create a new <strong>Certificate or use an existing Certificate</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-h7Hh6iOXr4sqGYTR6fyg.png" /><figcaption>Creating a new Certificate</figcaption></figure><p><strong>V. </strong>If you are creating a <strong>new Certificate, </strong>then <strong>Download the Keys immediately </strong>because it cannot be accessed later. If you are using an existing Certificate, then make sure that you have the keys downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm9Pwzz42vEn4aADHw64Yg.png" /><figcaption>Downloading keys for the new Certificate</figcaption></figure><p><strong>VI. </strong>Go to the tab <strong>Policies </strong>and <strong>Create a new Policy </strong>or <strong>use an existing Policy.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhKxhMKtQ1OKpTHNYBbYIg.png" /><figcaption>Creating new Policy</figcaption></figure><p><strong>VII. </strong>Once<strong> AWS Thing, Certificate, and Policy </strong>is created Attach <strong>Policy and Thing with the Certificate.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wl1HyVEawJ_VbxLArCzLsg.png" /><figcaption>Attaching Policy to the Certificate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzn6gBjyBa15FfG0Oc4RgQ.png" /><figcaption>Attaching Thing to the Certificate</figcaption></figure><h3>2. Setting up MQTT-X Client to Connect to AWS MQTT Broker</h3><p>First, we need to download the MQTT-X Client from their official website: <a href="https://mqttx.app/downloads">MQTTX Download</a></p><p><strong>I.</strong> <strong>Connection:<br></strong>Create a <strong>new connection</strong> by clicking the <strong>+</strong> symbol and then entering the details of the newly created AWS Thing. Give a <strong>name</strong> to this connection and also a <strong>name to the MQTT Client</strong>. In the host section choose <strong>mqtts:// </strong>and provide the <strong>endpoint of the AWS Thing</strong>. Use the Port value as <strong>8883 </strong>and <strong>switch on SSL options</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qvc5CAOh9WQnYhVdcgOOpQ.png" /><figcaption>Creating a new Connection to AWS MQTT Broker in MQTT-X Client</figcaption></figure><p><strong>II. AWS Thing Endpoint<br></strong>To get the endpoint value run the command on the AWS console<br><strong>aws iot describe-endpoint — output json</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aL33Ft_oobDtXAWW8QGpQ.png" /><figcaption>EndPoint for the AWS Thing</figcaption></figure><p><strong>III. Adding Certificate<br></strong>To add the downloaded Certificate, select Certificate type as <strong>Self signed</strong>. Add <strong>AmazonRootCA1.pem, </strong><strong>Device Certificate.crt</strong>, and <strong>private key.key</strong>. After Adding the certificates just click to connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxg1fpAL7rIB9z_HzDf87Q.png" /><figcaption>Adding Certificates to validate the connection to AWS MQTT Broker</figcaption></figure><h3>3. Subscribing to a MQTT Topic</h3><p>Once connected to the AWS MQTT Broker create a <strong>New Subscription</strong>. Enter the topic that you want to subscribe to and later use the same Topic to Publish the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4n2jhHGnrAI5hpCE5aNtQw.png" /><figcaption>Creating new Subscription</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*01qyvv_5GPAYOgmF8vKGsQ.png" /><figcaption>Entering the Topic for Subscription</figcaption></figure><h3>4. Publishing to a MQTT Topic</h3><p>After connecting to the AWS MQTT Broker and Subscribing to a Topic. We need to Publish on the same Topic and push some messages to the Topic.<br><strong>Point 1: </strong>Our Created Subscription is ready.<br><strong>Point 2: </strong>We need to mention the Topic name to Pulish and also the message.<br><strong>Point 3: </strong>After adding Topic and Message we can publish the message using the send button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8OIo32dHeJZCAxfQUQ_fw.png" /></figure><h3>5. AWS MQTT in Action</h3><p>Since we have learned how to configure AWS Thing, how to download Certificates, get Endpoint Values, and use those values to configure the MQTT-X Client. Let’s see the AWS MQTT and MQTT-X client in action.</p><p>Below we are <strong>subscribing and publishing to the same Topic <br></strong>AWS-MQTT/Topic1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUCCnVunoojLziMOme07Pg.gif" /><figcaption>AWS MQTT and MQTT-X Client in Action</figcaption></figure><h3>6. Node-Red and MQTT-X Client Integration</h3><p>Node-RED is an open-source flow-based development tool for visual programming. It is typically used for wiring together devices, APIs, and online services in a way that’s easy to understand and deploy.<br>website: <a href="https://nodered.org/">Node-RED (nodered.org)</a><br>Below we can see that <strong>Node-Red </strong>is publishing a message to the Topic AWS-MQTT/Topic1 and the <strong>MQTT-X Client </strong>is subscribing to the same topic. They both are sharing the message using the <strong>AWS MQTT Broker</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aEFBYLOouDeuuMIWASjnQ.gif" /><figcaption>Node-Red and MQTT-X Client communicating using AWS MQTT Broker.</figcaption></figure><blockquote>If you want to learn how to configure Node-Red and integrate Node-Red with AWS MQTT then please clap 👏 and leave a comment.</blockquote><p>If you find this tutorial helpful, then don’t forget to follow me.</p><h3>📝My Other Articles</h3><p><a href="https://medium.com/nerd-for-tech/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa"><strong>Paramiko- How to transfer files with Remote System (SFTP Servers) using Python | by KIHSA Rai | Nerd For Tech | Medium</strong></a></p><p><a href="https://medium.com/nerd-for-tech/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f"><strong>Python ConfigParser: A Comprehensive Guide ⚙️ | by KIHSA Rai | Nerd For Tech | Medium</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/python-profiling-know-why-and-where-your-code-is-slow-507babca84af"><strong>Python Profiling: Know Why and Where Your Code is Slow | by KIHSA Rai | Sep, 2023 | Medium</strong></a></p><p>Happy Coding, Let’s meet on another tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*29ieFh7SkWR5DIdJn-aU-g.jpeg" /><figcaption>image Source: <a href="https://pin.it/5aSciA4">link</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7007dc023b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything to know about MQTT (Message Queue Telemetry Transport)]]></title>
            <link>https://ashikthulungrai7.medium.com/everything-to-know-about-mqtt-message-queue-telemetry-transport-acbf32d1b761?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/acbf32d1b761</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mqtt-broker]]></category>
            <category><![CDATA[mqtt-client]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[mqtt]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 10:25:07 GMT</pubDate>
            <atom:updated>2024-01-04T07:25:21.176Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive guide on what is <strong>MQTT</strong>, <strong>MQTT client-broker</strong>, <strong>publisher/subscriber architecture</strong>, and <strong>Topics.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVyfmXHsccg2djRRyrKVyQ.jpeg" /><figcaption><a href="https://blog.paessler.com/our-new-mqtt-sensors-video-tutorials">image source</a></figcaption></figure><p>Hello Jawans, 😎, today we will be learning about <strong>MQTT</strong>, <strong>MQTT client-broker</strong>, and<strong>publisher/subscriber architecture</strong>. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3>1 — What is MQTT</h3><p><a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html"><strong>MQTT (Message Queuing Telemetry Transport)</strong></a><strong> </strong>according to the official website definition is a “<em>Client Server publish/subscribe messaging transport protocol. It is lightweight, open, simple, and designed so as to be easy to implement. These characteristics make it ideal for use in many situations, including constrained environments such as for communication in Machine to Machine (M2M) and Internet of Things (IoT) contexts where a small code footprint is required and/or network bandwidth is at a premium.”</em></p><p>The main highlights are <strong>lightweight </strong>because it is designed to be simple, and less resource hungry. <strong>Publish/Subscribe, </strong>this means that the sender and receiver don’t know each other they communicate via a central broker. The publisher writes/publishes a message under a topic and subscribers will subscribe to the topic that they are interested in.</p><h3>2 — How MQTT Works</h3><p>To understand how MQTT works, we must first know about <strong>MQTT Client, MQTT Broker, Publisher-subscriber, Topic, </strong>and <strong>QOS.</strong></p><h3>2.1 — What is MQTT Client</h3><p><a href="https://www.emqx.com/en/blog/the-easiest-guide-to-getting-started-with-mqtt#:~:text=Any%20application%20or%20device%20running%20the%20MQTT%20client%20library%20is%20an%20MQTT%20client.%20For%20example%2C%20an%20instant%20messaging%20app%20that%20uses%20MQTT%20is%20a%20client%2C%20various%20sensors%20that%20use%20MQTT%20to%20report%20data%20are%20a%20client%2C%20and%20various%20MQTT%20testing%20tools%20are%20also%20a%20client."><strong>EMQX</strong></a><strong> </strong>defines any application or device running the MQTT client library as an MQTT client. For example, an instant messaging app that uses MQTT is a client, various sensors that use MQTT to report real-time data are a client.</p><h3>2.2 — What is MQTT Broker</h3><p><strong>MQTT Broker </strong>plays an important role in MQTT architecture. It acts as a central hub for client connection, subscription, routing, and managing the flow of messages between MQTT clients. The MQTT broker plays a critical role in enabling communication between various devices, sensors, and applications in an MQTT-based system, such as those found on the Internet of Things (IoT) and other real-time communication applications. It is highly scalable so it can handle millions of MQTT client connections.</p><h3>2.3 — What is <strong>Publisher-subscriber</strong></h3><p>In the <strong>Publisher-Subscriber </strong>model, unlike the Client-Server, the client that sends the message (<strong>Publisher</strong>) is unaware of the existence of the client that receives the message (<strong>Subscriber</strong>). Clients do not connect to each other directly they connect to the <strong>Broker </strong>which is responsible for routing the messages. The <strong>MQTT Broker </strong>uses <strong>Topics </strong>for routing messages to the exact <strong>subscribed client</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q89-wOLNZp-jMHk-5rlDNQ.gif" /><figcaption>Published Subscriber Message Routing Example : <a href="https://3508888488-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LhKFvCh4dnxgthNTIuu%2Fuploads%2FF3wG7yxhjmcygOZopQlB%2FMQTT-1toN.gif?alt=media&amp;token=9ba28140-2c54-4cb8-bbd6-13cc974bcd87">image Source</a></figcaption></figure><h3>2.4 — What is a Topic</h3><p><strong>MQTT Topic </strong>is a string that is used to route messages. We can create multiple hierarchies by using slash /, similar to a <strong>URL</strong>. A <strong>Publisher client </strong>can publish a message on a topic and a <strong>Broker </strong>delivers the message to all the <strong>Clients </strong>that has subscribed to that topic.</p><blockquote>📝 If you want to learn more about MQTT Topics, Wildcards, and rules of Topic please leave a comment.</blockquote><pre><strong>Topic Examples</strong><br><br>sensor/1/temperature<br>sensor/2/humidity<br><br>software-update/android/14/<br>software-update/android/14/2<br>software-update/ios/17<br>software-update/ios/17/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FFYDtifXCxP4wZfTsmRaag.gif" /><figcaption>MQTT Topic used to route messages : <a href="https://blog.thaieasyelec.com/introduction-to-mqtt/">image source</a></figcaption></figure><h3>2.5 — What is QOS</h3><p>QOS or Quality of Service basically means the message delivery reliability. MQTT offers three levels of QOS.</p><ul><li><strong>QOS 0: </strong>The message is delivered at most once. If the client is not available currently, it will lose this message.</li><li><strong>QOS 1: </strong>The message is delivered at least once.</li><li><strong>QOS 2: </strong>The message is delivered only once.</li></ul><h3>3 — MQTT WorkFlow</h3><p>Since we are now aware of all the components of an MQTT let&#39;s see how a message is created and delivered from start to end.</p><ul><li>The client initiates a connection to the MQTT broker. This step also includes client authentication and session creation.</li><li>The client either subscribes to a Topic or publishes a message to a specific topic. The Publishing client sends a message to the Broker while the Subscriber informs the Broker of its interest in any message that has been published on the topic.</li><li>The Broker receives the published message and forwards the message to all the clients that have subscribed to that topic.</li></ul><p>📝If you like the tutorial, please follow and clap 👏.<br>Please comment for any doubts or tutorials on any other topic.</p><p>Happy Coding, Let’s meet on another tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3>📝Next Article</h3><p>In our next article, we will learn how to publish and subscribe to a topic and connect to AWS Broker. We will learn how to use <a href="https://mqttx.app/"><strong>MQTTX</strong></a><strong> </strong>to connect, publish, and subscribe topics.</p><p><a href="https://ashikthulungrai7.medium.com/mqttx-client-with-aws-mqtt-broker-7e7007dc023b">Mqttx Client with AWS Mqtt Broker | by KIHSA Rai | Dec, 2023 | Medium</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUCCnVunoojLziMOme07Pg.gif" /><figcaption>MQTT Client Subscription and Publishing messages</figcaption></figure><h3>📝My Other Articles</h3><p><a href="https://medium.com/nerd-for-tech/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa"><strong>Paramiko- How to transfer files with Remote System (SFTP Servers) using Python | by KIHSA Rai | Nerd For Tech | Medium</strong></a></p><p><a href="https://medium.com/nerd-for-tech/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f"><strong>Python ConfigParser: A Comprehensive Guide ⚙️ | by KIHSA Rai | Nerd For Tech | Medium</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/python-profiling-know-why-and-where-your-code-is-slow-507babca84af"><strong>Python Profiling: Know Why and Where Your Code is Slow | by KIHSA Rai | Sep, 2023 | Medium</strong></a></p><p>Happy Coding, Let’s meet on another tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JQty58SViCQYaTiEu4YTFw.jpeg" /><figcaption><a href="https://www.instagram.com/behind_pixl/">Darjeeling aka Queen of Hills by: behind_pixl </a>👉 <a href="https://in.pinterest.com/pin/816488607466621864/">link</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acbf32d1b761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Profiling: Know Why and Where Your Code is Slow]]></title>
            <link>https://ashikthulungrai7.medium.com/python-profiling-know-why-and-where-your-code-is-slow-507babca84af?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/507babca84af</guid>
            <category><![CDATA[code-optimization]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 13:45:02 GMT</pubDate>
            <atom:updated>2024-01-04T07:25:22.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn the Art of Writing Faster and More Efficient Code and accelerate your code like a pro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*7jykw_C60DispvvbmHU85w.jpeg" /><figcaption>image source: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fprateekvjoshi.com%2F2014%2F11%2F08%2Fwhy-is-python-slow%2F&amp;psig=AOvVaw3PeWfbgFQ9rNN5IFHCnBz7&amp;ust=1693396662541000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBAQjRxqFwoTCOjxpKbogYEDFQAAAAAdAAAAABAE">link</a></figcaption></figure><p>Hello Jawans, 😎, today we will be learning about <strong>Python Profiling</strong>, basics of <strong>Pandas</strong>, <strong>Threads</strong>, and <strong>SnakeViz</strong>. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><p><strong>Imagine this</strong>: You are working on a time-sensitive project. You need to work on a real-time data stream, read some files/data do some operations on it, and then save the file in a specific format. The time frame is limited to before the next data is available in the stream. It&#39;s very crucial because some extra milliseconds can result in late delivery of the formatted data or missing the data from the stream as it is flushed or overwritten. In this case, you need to decrease the execution time of formatting the data or at least keep the execution time under the timeframe.</p><p>While you may not always have a time-constrained scenario, but you might face a situation where the data or operation that you are handling is too big, and it feels like it takes ages to execute.</p><blockquote>In today’s example, we will be dealing with operations on huge CSV files. We will write a simple code and then use profiling to see where we can achieve optimization and then rewrite the code to achieve faster results.</blockquote><p>In both cases, you want to know <strong>why your code is slow? </strong>and <strong>where your code is slow?</strong> <br>To answer this, we need to dive into a tool called Profiler.</p><h3>1. What is a Profiler?</h3><p>In simple words, a Profiler is a special tool for your code. It runs your code and keeps track of how long each function takes to run, how often they’re called, and the order in which they’re called.<br>By analyzing these parameters, you can find which part of your code takes the most time to execute (bottleneck). You can rank the bottlenecks and design a solution for each one so that the execution time is reduced.</p><h3>2. Reading the Profiler output</h3><p><a href="https://jiffyclub.github.io/snakeviz/"><strong>SnakeViz</strong></a>is a browser-based interactive graphical representation of the output of Python code’s profiling data. It’s very easy to install <strong>(pip install snakeviz)</strong> and use the SnakeViz tool <strong>(snakeviz &lt;path-of-the-profiling-output-file&gt;)</strong>.</p><h3>3. Example Problem</h3><p>As discussed earlier, we need to work on a huge size CSV file(s). We need to <strong>1.</strong> <strong>Read the CSV file(s)<br>2. Search for certain values<br>3. Drop some rows and columns<br>4. Merge the CSV files.</strong></p><h3>3.1 Normal Code</h3><p>We are working on a multiple CSV file with 10000 to 100,000 records. The CSV file is an <strong>Organizations dataset </strong>downloaded from this 👉 <a href="https://www.datablist.com/learn/csv/download-sample-csv-files">link</a>. <br>In the code, we are reading the dataset and performing operations such as reading files, merging the data, searching for a value in a column, dropping a row if the column value matches the search value, etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDgbk-tDoFvtN06Yt_oopw.png" /><figcaption>Dataset CSV Files</figcaption></figure><pre>import pandas as pd<br>import os<br><br>class CSVEditor:<br>    def __init__(self, FilePath):<br>        self.FilePath= FilePath<br>        self.dataFrame= None<br>        <br>    # Reading and merging the CSV files inside the directory FilePath<br>    def readCSV(self):<br>        df_list= []<br>        for file in os.listdir(self.FilePath):<br>            file= os.path.join(self.FilePath, file)<br>            df_list.append(pd.read_csv(file))<br><br>        if (len(df_list) == 0):<br>            return<br>        if (len(df_list) == 1):<br>            self.dataFrame= df_list[0]<br>        else:<br>            self.dataFrame= pd.concat(df_list).reset_index(drop=True)<br>    <br>    # Removing a row if the countryName is present in the CountryNameList<br>    def editCntryCol(self, CountryNameList):<br>        dropIndex= []<br>        for index,value in enumerate(self.dataFrame[&#39;Country&#39;]):<br>            if value in CountryNameList:<br>                dropIndex.append(index)<br>        if (len(dropIndex) &gt; 0):<br>            print(f&quot;Formatting Country Column: ({len(dropIndex)} items dropped)&quot;)<br>            self.dataFrame= self.dataFrame.drop(dropIndex).reset_index(drop=True)<br>    <br>    # Removing a row if the Founded value is less than Year Value   <br>    def editFoundedCol(self, Year):<br>        dropIndex= []<br>        for index,value in enumerate(self.dataFrame[&#39;Founded&#39;]):<br>            if int(value) &lt; Year:<br>                dropIndex.append(index)<br>        if (len(dropIndex) &gt; 0):<br>            print(f&quot;Formatting Founded Column: ({len(dropIndex)} items dropped)&quot;)<br>            self.dataFrame= self.dataFrame.drop(dropIndex).reset_index(drop=True)<br>            <br>    # Removing a row if the Employee Count value is less than EmployeeCount Value<br>    def editEmpCountCol(self, EmployeeCount):<br>        dropIndex= []<br>        for index,value in enumerate(self.dataFrame[&#39;Number of employees&#39;]):<br>            if int(value) &lt; EmployeeCount:<br>                dropIndex.append(index)<br>        if (len(dropIndex) &gt; 0):<br>            print(f&quot;Formatting Number of employees Column: ({len(dropIndex)} items dropped)&quot;)<br>            self.dataFrame= self.dataFrame.drop(dropIndex).reset_index(drop=True)<br>            self.dataFrame[&#39;Index&#39;]= [i for i in range(self.dataFrame.shape[0])]<br>    <br>    # Saving the file        <br>    def saveFile(self, path, filename):        <br>        if (self.dataFrame is None):<br>            print(f&quot;Error: No data to save&quot;)<br>            return <br>        print(f&quot;successfully saved the file {filename} in path: {path}&quot;)<br>        self.dataFrame.to_csv(os.path.join(path,filename), index=False)</pre><h3>3.2 Let’s Profile the code.</h3><p>There are built-in profiling modules (cProfile, and profile) in Python but for the sake of learning and exploring we will be using another Python module called <a href="https://pypi.org/project/profilehooks/"><strong>profilehooks</strong></a>. It provides a decorator which we can use to wrap our function for profiling. <br>As you can see, I have wrapped a function called <strong>main </strong>which calls all the methods of class <strong>CSVEditor </strong>one by one. The output of the profiling is saved in a file called <strong>CSVEditorNormalCode.prof</strong></p><pre>from profilehooks import profile                   # &lt;== importing the module<br><br>@profile(stdout=False, filename=&#39;CSVEditorNormalCode.prof&#39;)  # &lt;== Profiling<br>def main():<br>    csvEditor = CSVEditor(&quot;./Dataset/&quot;)<br>    csvEditor.readCSV()<br>    csvEditor.editCntryCol([&quot;China&quot;, &quot;Kuwait&quot;, &quot;Uzbekistan&quot;, &quot;Pakistan&quot;, &quot;Mauritius&quot;, &quot;Bahamas&quot;, &quot;Afghanistan&quot;, &quot;Western Sahara&quot;, &quot;Zimbabwe&quot;])<br>    csvEditor.editFoundedCol(2000)<br>    csvEditor.editEmpCountCol(5000)<br>    csvEditor.saveFile(&quot;./&quot;,&quot;FinalReport.csv&quot;)</pre><h3>3.3 Snakeviz: Visualizing the Profiler Output</h3><p>To read the profile output we need to run the snakeviz and provide the path of the profilerOutput file as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI9vjDtAkoGqOwU_9GNYVg.png" /><figcaption>Running Snakeviz to see Profiler Output</figcaption></figure><p>Once you run the command you can see the result which will be displayed in your default browser. You can see that most time is taken by the function <strong>readCSV (2.73s)</strong>, followed by <strong>SaveFile (0.862s),</strong> then <strong>editFoundedCol (0.442s), editCntryCol (0.417s), and editEmpCountCol (0.261s).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_C3MOULgjybPtt-nmIbAw.png" /><figcaption>Visualization of Profiler output: Snakeviz</figcaption></figure><h3>4. Potential bottlenecks</h3><p>There are a few potential code segments that can be improved to increase the speed and decrease the execution time. Here’s what they are:</p><ol><li>csvEditor.<strong>readCSV(): </strong>Since reading is taking the maximum time, we can reduce it by introducing multithreading.</li><li><strong>editCntryCol(), editFoundedCol(), editEmpCountCol(): <br>2.1: </strong>Since the operations that we do on current rows are not dependent on previous or future rows. We can introduce parallelism using multithreading. <br><strong>2.2: </strong>To further improve the performance, we can bind the operations into one single function call instead of making three different function calls</li><li>csvEditor.<strong>saveFile(): </strong>We can even speed up the process of saving the file. If you want a tutorial on this, please leave a comment.</li></ol><h3>5. Refining the Code</h3><p>We will introduce multi-threading to speed up the code execution. We will use threads to read CSV files.</p><blockquote>Please remember this tutorial is not about threads so we will not focus on writing a robust multi-threading code. Here we are just demonstrating how we can use profiling data to find the bottleneck and after code optimization compare the results to see if the execution time is reduced or not.</blockquote><pre>from threading import Thread<br><br># This class uses threads to read CSV<br>class readCSV(Thread):<br>    def __init__(self, dataFrameList, filepath):<br>        Thread.__init__(self)<br>        self.__filepath= filepath<br>        self.__dataFrameList= dataFrameList<br>              <br>    def run(self):<br>        self.__dataFrameList.append(pd.read_csv(self.__filepath))</pre><p>We need to modify the old function <strong>readCSV() </strong>to call the thread class readCSV. The code is given below. There are multiple ways of improving the code or optimizing it, here we are mainly focusing on just using profiling tools to find bottlenecks.</p><pre><br>class CSVEditor:<br>    def __init__(self, FilePath):<br>        self.FilePath= FilePath<br>        self.dataFrame= None<br>                   <br>    def threadReadCSV(self):<br>        df_list= []<br>        threadList= []<br>        <br>        for file in os.listdir(self.FilePath):<br>            file= os.path.join(self.FilePath, file)<br>            cvReadThread= readCSV(df_list, file)<br>            cvReadThread.start()  # &lt;== Starting the thread<br>            threadList.append(cvReadThread)<br><br>        for thread in threadList:<br>            thread.join()   # &lt;== Waiting for all threads to end<br>        if (len(df_list) == 0):<br>            return<br>        if (len(df_list) == 1):<br>            self.dataFrame= df_list[0]<br>        else:<br>            self.dataFrame= pd.concat(df_list).reset_index(drop=True)</pre><p>After the code is optimized the execution time is reduced as shown in the profiling output. The change is minimal as we are working on a small-scale dataset, but results may bring big differences when working on huge datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2c-6p5KFEo35O18QNmMDUA.png" /><figcaption>Profiler output for optimized code: Snakeviz</figcaption></figure><p>Below we have compared the profiles output for both code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAHSZGr5ABbDj7adi7lUTw.png" /><figcaption>Comparing the profiler output for <strong>raw(main)</strong> and <strong>optmized(threadmain) </strong>code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXizXx8OzMuQLjptQWpN-g.png" /><figcaption>star Trail effect by behind_pixl 👉 <a href="https://www.instagram.com/p/CnoYxvEskYH/?utm_source=ig_web_copy_link&amp;igshid=MzRlODBiNWFlZA==">link</a></figcaption></figure><p>If you like the tutorial, please follow and clap 👏.<br>Please comment for any appreciation, or doubts, or tutorials that you want on any other topic.</p><p>Happy Coding, Let’s meet on another tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3>Read my other articles</h3><ul><li><a href="https://ashikthulungrai7.medium.com/mqttx-client-with-aws-mqtt-broker-7e7007dc023b">Mqttx Client with AWS Mqtt Broker | by KIHSA Rai | Dec, 2023 | Medium</a></li><li><a href="https://medium.com/nerd-for-tech/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f">Python ConfigParser: A Comprehensive Guide ⚙️ | by KIHSA Rai | Nerd For Tech | Medium</a></li><li><a href="https://medium.com/@ashikthulungrai7/everything-to-know-about-mqtt-message-queue-telemetry-transport-acbf32d1b761">Everything to know about MQTT (Message Queue Telemetry Transport) | by KIHSA Rai | Oct, 2023 | Medium</a></li><li><a href="https://medium.com/nerd-for-tech/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa">Paramiko- How to transfer files with Remote System (SFTP Servers) using Python | by KIHSA Rai | Nerd For Tech | Medium</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507babca84af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paramiko- How to transfer files with Remote System (SFTP Servers) using Python]]></title>
            <link>https://ashikthulungrai7.medium.com/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/52d3e51d2cfa</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[paramiko]]></category>
            <category><![CDATA[sftp-server]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 09:22:26 GMT</pubDate>
            <atom:updated>2024-12-04T08:59:06.690Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive guide on how to upload and download files from an SFTP-Server/remote machine using paramiko</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b15A8LMqqeocQJcT" /><figcaption>Photo by <a href="https://unsplash.com/@cookiethepom?utm_source=medium&amp;utm_medium=referral">Cookie the Pom</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello Jawans, 😎, today we will be learning about <strong>Sftp Server</strong>, <strong>Rebex Tiny SFTP Server</strong>, and <strong>Paramiko</strong>. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3>¡Bcak Sroty</h3><p>So, the backstory goes like this, I was working on a project where I wanted to <strong>download files from a remote SFTP Server</strong> 🖥️ and <strong>upload that file into another remote SFTP server. </strong>💻</p><p>Well, there are multiple ways to do this. I can use SSH, curl, or use any SFTP Clients using either <strong>SFTP</strong> or <strong>SCP</strong>. I followed a different approach, I wanted to automate this process without any human intervention except for starting at the beginning.</p><p>I will use a Python script and Python modules <strong>Paramiko</strong> and<strong> </strong><strong>PyCurl</strong> to achieve the requirement and to fully automate it will schedule the execution of the Python script at 8 a.m. every day.<br><strong><em>Today we will be discussing about </em></strong><strong><em>Paramiko</em></strong></p><h3>1. Paramiko Client</h3><p>According to <a href="https://docs.paramiko.org/en/latest/">paramiko.org</a> documentation. Paramiko is a Python implementation of SSHv2. It provides both client and server-side functionality. To connect to the remover server and transfer the file or perform any operations we need to create a Paramiko client as shown below.<strong><br> </strong><strong>SSH_Client= Paramiko.SSHClient()</strong></p><h3>2. Free SFTP Server</h3><p>I’m using <strong>Rebex Tiny SFTP Server</strong> as my remote SFTP server. As you can see all the server details such as an address, port, username, password, and root directory, all are shared in the UI and once you start the Rebex server it will listen to the port for any request. <br><strong>If you want to learn more about Rebex and how to configure it, then follow and write down in a comment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwNZX3_WCSWli5HW8mopbw.png" /><figcaption>Rebex Tiny SFTP Server UI</figcaption></figure><p><strong><em>Download Rebex Tiny SFTP Server: </em></strong><a href="https://www.rebex.net/tiny-sftp-server/#download"><strong><em>link</em></strong></a></p><h3>3. Connect to the Remote Server</h3><p>Once we have created <strong>Paramiko Client</strong> we can then use the username and password for authentication to connect to the server.<br><strong>SSH_Client.connect(hostname=hostName, port= port, username=userName, password= password) </strong><br>If you directly connect to the server, you will get an error because Paramiko is not sure whether the remote server is trustworthy or not. To avoid this, we need to set<strong>look_for_keys</strong> flag and also add<strong> </strong><strong>AutoPolicy.</strong></p><pre>import paramiko<br>SSH_Client= paramiko.SSHClient()<br>SSH_Client.set_missing_host_key_policy(paramiko.AutoAddPolicy())<br>SSH_Client.connect( hostname=hostName, port=port, username=userName,<br>                   password= password, look_for_keys= false<br>                 )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxdpoKhST28wkVzdNa3muA.png" /><figcaption>Connecting to Rebex Tiny SFTP Server</figcaption></figure><h3>4. Storing Credentials</h3><p>It’s a very dangerous and bad coding exercise to hardcode the credentials. The best practice is to store the credentials in encrypted form. One of the simplest ways to store credentials is config files (.ini files). To learn about python <a href="https://medium.com/@ashikthulungrai7/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f"><strong>configParse</strong> </a>follow this <a href="https://medium.com/@ashikthulungrai7/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f">link</a><br><a href="https://medium.com/@ashikthulungrai7/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f">Python ConfigParser: A Comprehensive Guide ⚙️ | by KIHSA Rai | Aug, 2023 | Medium</a></p><h3>5. Downloading Files</h3><p>To transfer files, we need to first create an SFTP session between the client and the server. We can do this by using the <strong>SSHClient</strong> that we have created earlier.<br><strong>sftp_client= SSH_Client.open_sftp() </strong><br>Once this is done then we can call the API <br><strong>get(remoteFilePath,</strong> <strong>localFilePath)</strong> to download the file from the remote server to the local system (localFilePath).<br><strong><em>Since I’m using the </em></strong><strong><em>Rebex SFTP server the </em></strong><strong><em>root directoryis the </em></strong><strong><em>data folder. So, I will be downloading files from the root (data) directory itself.</em></strong></p><pre>sftp_client    = SSH_Client.open_sftp()<br>localFilePath  = &quot;temp/testfile.txt&quot;<br>remoteFilePath = &quot;testfile.txt&quot;<br>try:<br>  sftp_client.get(remoteFilePath, localFilePath)<br>except FileNotFoundError as err:<br>    print(f&quot;File: {remoteFilePath} was not found on the source server {self.__hostName}:{self.__port}&quot;)<br>sftp_client.close()</pre><p>This will download the file <strong>testfile.txt</strong> from the data folder of the Rebex Server to the local system, <strong>inside the temp folder</strong>, with the same filename. Once the download is done we need to also close the session by calling <strong>close() </strong>function`.</p><h3>6. Uploading Files</h3><p>Similar to download we need to first create a SFTP session.<br>sftp_client= SSH_Client.open_sftp() <br>Once this is done then we can call the API <br>put(localFilePath, remoteFilePath) to upload the file from the local system (localFilePath) to the remote server.<br><strong><em>Since I’m using the </em></strong><strong><em>Rebex SFTP server the </em></strong><strong><em>root directory is the</em></strong><strong><em>data folder. So, I will be uploading files to the root (data) directory itself.</em></strong></p><pre>sftp_client    = SSH_Client.open_sftp()<br>localFilePath  = &quot;temp/testfile.txt&quot;<br>remoteFilePath = &quot;testfile.txt&quot;<br>try:<br>  sftp_client.put(localFilePath, remoteFilePath)<br>except FileNotFoundError as err:<br>  print(f&quot;File {localFilePath} was not found on the local system&quot;)<br>sftp_client.close()  </pre><p>This will upload the file <strong>testfile.txt</strong> from the <strong>temp folder</strong> to the Rebex Servers root directory <strong>data</strong> with the same filename.</p><h3>7. Listing the files</h3><p>First, create the SFTP session and call the API <strong>listdir </strong>and provide the remoteFilePath</p><pre>sftp_client= SSH_Client.open_sftp()<br>remoteFilePath= &quot;.&quot;<br>try:<br>  print(f&quot;lists of files {sftp_client.listdir(remoteFilePath)}&quot;)<br>except err:<br>  print(f&quot;Error while getting the list of files&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3d7GiSIY2101lUCbo08gA.png" /><figcaption>Listing files in the Rebex SFTP Server</figcaption></figure><h3>8. Executing remote Commands</h3><p>To execute commands remotely you need to call API <strong>exec_command()</strong>. The API call returns a <strong>tuple of (stdin, stdout, stderr). <br></strong>Since Rebex Tiny SFTP Server doesn’t allow shell subsystem, only SFTP connections, we can use <strong><em>Rebex Buru SFTP Server</em></strong> for this.<br><a href="https://www.rebex.net/buru-sftp-server/download/"><strong><em>Download Rebex Buru SFTP Server — Rebex.NET</em></strong></a></p><pre>stdin,stdout,stderr= SSH_Client.exec_command(“ls”)<br>print(stdout.readlines())<br>print(stderr.readlines())</pre><h3>9. Combined Code</h3><pre>import paramiko<br>import os<br><br>class SFTPServerClient:  <br><br>  def __init__(self, hostname, port, username, password):<br>    self.__hostName   = hostname<br>    self.__port       = port<br>    self.__userName   = username<br>    self.__password   = password<br>    self.__SSH_Client = paramiko.SSHClient()<br>        <br><br>  def connect(self):<br>    try:<br>      self.__SSH_Client.set_missing_host_key_policy(paramiko.AutoAddPolicy())<br>      self.__SSH_Client.connect(<br>        hostname      = self.__hostName,<br>        port          = self.__port,<br>        username      = self.__userName,<br>        password      = self.__password,<br>        look_for_keys =False<br>      )<br>    except Exception as excp:<br>      raise Exception(excp)<br>      return<br>    else:<br>      print(f&quot;Connected to server {self.__hostName}:{self.__port} as <br>              {self.__userName}.&quot;)<br><br><br>  def disconnect(self):<br>    self.__SSH_Client.close()<br>    print(f&quot;{self.__userName} is disconnected to server <br>            {self.__hostName}:{self.__port}&quot;)<br>    <br><br>  def getListofFiles(self, remoteFilePath):<br>    sftp_client= self.__SSH_Client.open_sftp()<br>    try:<br>      print(f&quot;lists of files {sftp_client.listdir(remoteFilePath)}&quot;)<br>    except err:<br>      print(f&quot;Error while getting the list of files&quot;)<br>   <br><br>  def downloadFiles(self, remoteFilePath):<br>    localFilePath= os.path.join(&quot;temp&quot;,remoteFilePath)<br>    print(f&quot;downloading file {remoteFilePath} to remote {localFilePath}&quot;)<br>        <br>    sftp_client=self.__SSH_Client.open_sftp()<br>    try:<br>      sftp_client.get(remoteFilePath, localFilePath)<br>    except FileNotFoundError as err:<br>      print(f&quot;File: {remoteFilePath} was not found on the server&quot;)<br>    sftp_client.close()<br>  <br>      <br>  def uploadFiles(self, remoteFilePath, localFilePath):<br>    localFilePath= os.path.join(&quot;temp&quot;,remoteFilePath)<br>    print(f&quot;uploading file {localFilePath} to remote {remoteFilePath}&quot;)<br>        <br>    sftp_client=self.__SSH_Client.open_sftp()<br>    try:<br>      sftp_client.put(localFilePath, remoteFilePath)<br>    except FileNotFoundError as err:<br>      print(f&quot;File {localFilePath} was not found on the local system&quot;)<br>    sftp_client.close()  <br>   <br>     <br>  def executeCommand(self, command):<br>    stdin,stdout,stderr= self.__SSH_Client.exec_command(command)<br>    print(stdout.readlines())<br>    print(stderr.readlines())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-8PqYGDxrdINKNQU" /><figcaption>Photo by <a href="https://unsplash.com/@mohdarman?utm_source=medium&amp;utm_medium=referral">Mohd Arman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you like the tutorial, please follow and clap 👏.<br>Please comment for any doubts or tutorial on any other topic.</p><p>Happy Coding, Lets meet on another tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><p>My References: <a href="https://docs.paramiko.org/en/latest/">Welcome to Paramiko’s documentation! — Paramiko documentation</a></p><h3>Read my other articles</h3><ul><li><a href="https://ashikthulungrai7.medium.com/mqttx-client-with-aws-mqtt-broker-7e7007dc023b">Mqttx Client with AWS Mqtt Broker | by KIHSA Rai | Dec, 2023 | Medium</a></li><li><a href="https://medium.com/nerd-for-tech/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f">Python ConfigParser: A Comprehensive Guide ⚙️ | by KIHSA Rai | Nerd For Tech | Medium</a></li><li><a href="https://medium.com/@ashikthulungrai7/everything-to-know-about-mqtt-message-queue-telemetry-transport-acbf32d1b761">Everything to know about MQTT (Message Queue Telemetry Transport) | by KIHSA Rai | Oct, 2023 | Medium</a></li><li><a href="https://ashikthulungrai7.medium.com/python-profiling-know-why-and-where-your-code-is-slow-507babca84af">Python Profiling: Know Why and Where Your Code is Slow | by KIHSA Rai | Sep, 2023 | Medium</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d3e51d2cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python ConfigParser: A Comprehensive Guide ⚙️]]></title>
            <link>https://ashikthulungrai7.medium.com/python-configparser-a-comprehensive-guide-%EF%B8%8F-36331be5244f?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/36331be5244f</guid>
            <category><![CDATA[configuration-file]]></category>
            <category><![CDATA[configparser]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 05:28:36 GMT</pubDate>
            <atom:updated>2023-12-27T12:29:27.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Mastering Configuration Management in Python: A Deep Dive into the Configparser Module</p><figure><img alt="https://i.pinimg.com/222x/34/5a/ee/345aeee714fc811016fab1c1b5edfdf5.jpg" src="https://cdn-images-1.medium.com/max/221/1*BWdIX622_GPi2drOBqH60w.jpeg" /><figcaption>image source: <a href="https://i.pinimg.com/222x/34/5a/ee/345aeee714fc811016fab1c1b5edfdf5.jpg">link</a></figcaption></figure><p>Hello Jawans, 😎, today we will be learning about config files, and conifParser. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3><strong>1. What is a ConfigParser?</strong></h3><p>While coding we have multiple lines of code or variables holding different configuration values related to the application. The configuration variables can be related to either test or production environments or both. Since most of the configuration values are static so instead of hardcoding values in the code, we can make it more flexible by creating a config file where all configurations are stored and can be read and edited without disturbing the application’s code.</p><p>ConfigParser is a Python module that is used to create and read the configuration files and use them in the application development.</p><h3>2. How to create a Config File?</h3><p>Config files are files with .ini extensions. The contents are organized as sections and items. Sections are like headings and items are the ones that actually store the config values in a key-value pair format.</p><p>Let’s assume that we are connecting to a remote server, and we need to store config values such as host, port, username, password, etc. Since there can be multiple servers that the applications connect to in such cases, we can separate each server’s config data using different sections in the config file.</p><pre>[SFTP_SERVER1]      # &lt;------------------ Section<br>host = 10.120.98.12 # &lt;------------------ Items (key-value)<br>port = 22<br>username = tester<br>password = password<br><br><br>[SFTP_SERVER2]      # &lt;------------------ Section<br>host = 10.120.98.12 # &lt;------------------ Items (key-value)<br>port = 23<br>username = tester<br>password = password</pre><p>So SFTP_SERVER1 and SFTP_SERVER2 are sections and host, port, username, password are keys with their respective values.</p><p><strong><em>To learn about how to connect to SFTP Servers, how to transfers file and run remote command read this article: </em></strong><a href="https://medium.com/@ashikthulungrai7/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa"><strong><em>link</em></strong></a><strong><em><br></em></strong><a href="https://medium.com/@ashikthulungrai7/paramiko-how-to-transfer-files-with-remote-system-sftp-servers-using-python-52d3e51d2cfa"><strong><em>Paramiko- How to transfer files with Remote System (SFTP Servers) using Python | by KIHSA Rai | Aug, 2023 | Medium</em></strong></a></p><blockquote>Section name must be unique.</blockquote><h3>3. How to Read Config Files</h3><p>First, create a ConfigParser object.</p><pre>import configparser<br><br>configParser= configparser.ConfigParser() # Creating a configParser object</pre><p>Read the config file. The filename used in the code is tempConfig.ini</p><pre>filename= &quot;tempConfig.ini&quot;<br>configParser.read(filename)    # Reading the config file</pre><p>Use ApIs to list all defined sections in the config file.</p><pre>Servers= configParser.sections()    # Getting sections from config file<br>print (Servers)                     # Printing the Sections (Servers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*5NMDYQqCROdtiAt94HGQsQ.png" /><figcaption>Printing the sections defined in config file</figcaption></figure><p>Use ApIs to read item defined under the sections.</p><pre>Servers= configParser.sections()    # Getting sections from config file<br>host= configParser[Servers[0]][&#39;host&#39;]  # Getting item using the key host<br>port= configParser[Servers[0]][&#39;port&#39;]  # Getting item using the key port<br><br>print(f&quot;Host: {host} port: {port}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*aXd1D_Ly12G19mJL6-bUwg.png" /><figcaption>Printing the item defined under Section: SFTP_SERVER1</figcaption></figure><h3>Combined Code</h3><p>Here I have created a class (HostConfig) for reading a config file and also provided some API’s to read the sections and items defined in the config file.</p><pre>import configparser<br><br>class HostConfig:<br>    def __init__(self, configFile):<br>        self.configFile= configFile<br>        self.config= configparser.ConfigParser()<br>        <br>    def readConfig(self):<br>        # Reading the config file<br>        self.config.read(self.configFile)<br>    <br>    def getServers(self):<br>        # Returning all the sections defined in the config file<br>        return self.config.sections()<br>    <br>    def getData(self, host, key):<br>        # Getting the values from the particular section (host) <br>        # by using the key       <br>        return self.config[host][key]<br>    <br>    def getHostDetails(self, host):<br>        # Getting all the values defined under the given section (host).<br>        # Assuming the keys are known and fixed.<br>        hostdata= self.config[host]<br>        return hostdata[&#39;host&#39;],hostdata[&#39;port&#39;],hostdata[&#39;username&#39;],hostdata[&#39;password&#39;]</pre><pre>hostConfig= HostConfig(&#39;tempConfig.ini&#39;)  # creating object of HostConfig<br>hostConfig.readConfig()                   # Reading config file <br><br>Servers= hostConfig.getServers()       # Getting the list of sections (servers)<br>print(&quot;Servers: &quot;,Servers)<br><br>print(&quot;Server 0 data: \n&quot;,hostConfig.getHostDetails(Servers[0]))  # Getting items for Section No 0<br><br>print(&quot;Server1: Host &quot;,hostConfig.getData(Servers[1], &#39;host&#39;))  # Getting item for Section No 1<br>print(&quot;Server1: Port &quot;,hostConfig.getData(Servers[1], &#39;port&#39;))  # Getting item for Section No 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*Hb3nnNuSRWlRFr3rd_Yn4A.png" /><figcaption>Output of the above code</figcaption></figure><blockquote>If you want another tutorial on how to create a Config file using Python.<br>If you want to learn how to convert a dictionary to a config file in Python.<br>please leave a comment.<br>If you like the tutorial, please clap for it and follow me.</blockquote><h3>Read my other articles</h3><p><a href="https://medium.com/@ashikthulungrai7/everything-to-know-about-mqtt-message-queue-telemetry-transport-acbf32d1b761"><strong>Everything to know about MQTT (Message Queue Telemetry Transport) | by KIHSA Rai | Oct, 2023 | Medium</strong></a></p><p><a href="https://ashikthulungrai7.medium.com/mqttx-client-with-aws-mqtt-broker-7e7007dc023b"><strong>Mqttx Client with AWS Mqtt Broker | by KIHSA Rai | Dec, 2023 | Medium</strong></a></p><p><strong>Read my other tutorials on ReactJs</strong>, I’ve explained it in simple words with examples and also provided a Git Hub link for the source code.</p><p><a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189"><strong>Part 1: How to create a new React App Explained in simple steps</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/part-2-easy-way-to-create-reactjs-components-7d458b577c67"><strong><em>Part 2: Easy Way To Create ReactJS Components</em></strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/drag-drop-react-beautiful-dnd-328e00797f27"><strong>DRAG &amp; DROP: REACT BEAUTIFUL DND</strong></a></p><p><strong>Read my other tutorial on Android Development</strong></p><p><a href="https://medium.com/@ashikthulungrai7/android-shared-preferences-11517624a991"><strong>Android Shared Preferences. Save and retrieve simple data easily… | by KIHSA Rai | Jul, 2023 | Medium</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/android-view-and-viewgroup-6a8e235a3c92"><strong>Android View and ViewGroup. Easy tutorial about Android View and… | by KIHSA Rai | Jul, 2023 | Medium</strong></a></p><p>let’s meet again in next tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1H6VhzVL9ktqBxCJ" /><figcaption>Photo by <a href="https://unsplash.com/@cslangston?utm_source=medium&amp;utm_medium=referral">@Chrissy Langston</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>My references:</strong> <a href="https://docs.python.org/3/library/configparser.html">configparser — Configuration file parser — Python 3.11.4 documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36331be5244f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part1: How To Create A First ReactNative App With Few Easy Steps]]></title>
            <link>https://ashikthulungrai7.medium.com/part1-how-to-create-a-first-reactnative-app-with-few-easy-steps-5b8470a1f4bc?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b8470a1f4bc</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 09:38:03 GMT</pubDate>
            <atom:updated>2023-11-29T09:20:47.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3f8zhjFNKR7Twlp07fmKQ.gif" /><figcaption><strong><em>Image Edited in CANVA</em></strong></figcaption></figure><blockquote>This blog is created as a tutorial to teach <strong>mobile app development using React-Native. </strong>The tutorial is divided to multiple parts and each part teaches different stages in mobile app development in detail. We may not be able to cover everything so please reach out to us for any help and we shall create a new blog for you.</blockquote><blockquote>Today we are going to learn how to <strong>create a Mobile App using React-Native</strong></blockquote><h3>Quick Links to other ReactJS Tutorials</h3><ol><li>Part 1: <a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189">How to create a new React App | by KIHSA Rai | Medium | Medium</a></li><li><a href="https://medium.com/nerd-for-tech/part-2-easy-way-to-create-reactjs-components-7d458b577c67">Part 2: Easy Way To Create ReactJS Components</a></li><li><a href="https://medium.com/@ashikthulungrai7/drag-drop-react-beautiful-dnd-328e00797f27">How To Create DRAG &amp; DROP Components Using REACT BEAUTIFUL DND Library</a></li></ol><h3>Contents</h3><ol><li>Introduction.</li><li>Create React-Native App and setting up the development environment.</li><li>Run the React Native Project</li><li>Run the React Native Project in your Smartphone (iOS/Android)</li><li>Launch the Native App.</li></ol><h3>1. Introduction</h3><p>React Native is a framework for building native apps for iOS and Android using JavaScript. A React-Native developer need not know iOS and Android Programming until and unless we need to develop some complex, platform-specific apps which uses the native API’s. But React-Native has more than required support available for the native API’s. Due to the platform independent nature of React-Native it is being widely use and accepted as it eliminates the requirement of separate developer of iOS and Android.</p><blockquote>Some of the most widely used React-Native Apps are <strong>Facebook, Instagram, Skype, Uber Eats, Pinterest, etc.</strong></blockquote><blockquote><a href="https://reactjs.org/">React</a> is the underlying engine for React-Native. If you want a detailed course on React please read my another full tutorial on <a href="https://medium.com/nerd-for-tech/how-to-create-a-new-react-app-3286a37e2189">React</a></blockquote><p>There are two different ways of building React-Native Apps one is by using <strong>Expo CLI </strong>and other one is by using <strong>React Native CLI</strong>, <strong><em>follow the </em></strong><a href="https://reactnative.dev/docs/environment-setup"><strong><em>link </em></strong></a><strong><em>for detail in two CLI’s. </em></strong>If you choose Expo CLI and later want to switch back to React Native CLI its just some clicks away.</p><blockquote>In this tutorial we will be using <strong>Expo CLI</strong>. If you want to know how to use React Native CLI then please reach out to me and I will make a new full tutorial on that.</blockquote><h3>2. Create React-Native App and setting up the development environment.</h3><p>First we need to install <strong>nodejs </strong>use this <a href="https://nodejs.org/en/">link</a> to download the latest version of nodejs and install in your local machine. Next we are going to install the <strong>Expo CLI.</strong></p><p><strong>2.1 Install Expo CLI</strong></p><p>Expo CLI is the first choice rather than React Native CLI when people have zero knowledge about mobile development. Expo CLI is a command line interface between a developer and Expo tools. Using Expo CLI you can <strong>Creating new projects, develop your app</strong>, <strong>open the simulator, p</strong><a href="https://docs.expo.dev/workflow/publishing/"><strong>ublish</strong></a><strong> your app , </strong><a href="https://docs.expo.dev/distribution/building-standalone-apps/"><strong>Building binar</strong></a>y files like .apk and .ipa for Play Store and App Store. It also provides a web based interface which gets opens automatically when we run the app, in case if the Web CLI is not opened you can press d from the CLI.</p><p>To install Expo CLI run the command</p><pre>npm i -g expo-cli --save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYcnLel84gkzelpFvEYx6g.png" /><figcaption><strong>Installing Expo CLI</strong></figcaption></figure><p><strong>2.2 Create a First React Native + Expo Project</strong></p><p>To create the Project run the command</p><pre>expo init MyFirstNativeApp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPVJVNGEsA8jT1eLfIvGjQ.png" /><figcaption>Creating a React Native App</figcaption></figure><p>As you can see in the main -&gt; origin is the git branch, RNA is the name of the active virtualenv (abbreviation for React-Native-App). So after running the command we have some options displayed on the console. Please use the first option name <strong>blank under Managed Workflow</strong>. Once the project is created you will see something similar to this in your console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rq5GgUfvWOyjEi9ZWChhYA.png" /><figcaption>React Native Project Created successfully</figcaption></figure><p>So once the project is created cd to your project and the directory structure is as discussed below. The folder assets contains all the media files like images, png, videos, audios, etc. We also have App.js which is the default and root functional component as in React-Project. Unlike in html and React Project in React Native we have a whole new set of components such as Text, View, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpYb64nA9l5KbdrLUOLUkA.png" /><figcaption>Default directory structure and files</figcaption></figure><blockquote>Visit the <a href="https://reactnative.dev/docs/environment-setup"><em>link</em></a> for docs and detailed explanation.</blockquote><h3>3. Run the React Native Project in local Machine</h3><p>To run the React Native Project run the command npm start. After the server is completely started the Expo CLI is rendered automatically in your browser at <a href="http://localhost:19002/">http://localhost:19002/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox8_lgt3l4ZIml0dEfTgzA.png" /><figcaption>Running the React Native Project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3fgAch0hpSRqE0UdFkuIw.png" /><figcaption>Expo Web Browser CLI</figcaption></figure><p>As you can see in the first image we have a bundle of options such as Open in Android, Open in web, Reload App, etc. We also have option of Run on Android Simulator, Run on iOS Simulator, Run in Web Browser, etc. So, we can either use the Expo Command CLI or Web CLI.</p><blockquote>We have a QR Code in both Console and in Web CLI. If we scan the QR Code then we can directly open the React Native Project in mobile if we already have installed a Expo Client. (Read next section on how to install Expo Client)</blockquote><p>We can select the option run on Android or iOS but we need to have a simulator for android or iOS in our local machine. We can even share the link of our project for others to access. The most important feature for me at least is the last option <strong>Publish or Republish</strong>. We can simply publish our whole app to <strong>EXPO </strong>and anyone on the world can use the App from the Expo Client. Very helpful in development or testing cycle of your App.</p><p>If you select web browser to run your Native Project then you Project is rendered in port <strong>19006.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejfa8uyfVloFBUESHnqVCA.png" /><figcaption>React Native Project Rendered in Web Browser</figcaption></figure><blockquote>To run the React Native App on <strong>iOS Simulator </strong>please follow the video using <a href="https://www.youtube.com/watch?v=0-S5a0eXPoc"><strong>this link</strong></a><strong> (14:39 to 18:00) </strong>to run on <strong>Android Simulator </strong>follow the video from <strong>(18:00 to 26:46).</strong></blockquote><h3>4. Run the React Native Project in your Smartphone (iOS/Android)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*p_sbWw0d6TS95P-0_LmJcQ.gif" /><figcaption>Running React Native App in iOS device using Expo Client</figcaption></figure><p>To run the React Native app in your mobile device download the Expo Client its available both in AppStore and PlayStore.</p><p>After Installing the Expo Client run the React Native Project using the command npm start as discussed in section 3.</p><p>Once the server is up it will open the Expo Web CLI and you can find the QR Code in Web CLI and also in the console. Scan the QR Code and it will open your Expo Client and your Native Project is rendered.</p><p>Even when you change the code in you editor the re-rendering happens in real time and the lag is not even noticeable.</p><blockquote><strong>Next Article: </strong>Part2:<strong> </strong>Build a Login Form Using React Native Core Components</blockquote><h3>Read more of my articles on React App Development and other awesome React packages</h3><blockquote><em>Part 1: </em><a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189"><em>How to create a new React App | by KIHSA Rai | Medium | Medium</em></a></blockquote><blockquote><a href="https://medium.com/nerd-for-tech/part-2-easy-way-to-create-reactjs-components-7d458b577c67"><em>Part 2: Easy Way To Create ReactJS Components</em></a></blockquote><blockquote><a href="https://medium.com/@ashikthulungrai7/drag-drop-react-beautiful-dnd-328e00797f27"><em>How To Create DRAG &amp; DROP Components Using REACT BEAUTIFUL DND Library</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*mNTE06ETn6dv_w60SI19DA.jpeg" /><figcaption>image source: <a href="http://www.hiremobiledeveloper.com/blog/android-versions-history/">link</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b8470a1f4bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering C++ Abstract Class, Interface, and (Pure)Virtual Functions in Few Steps ]]></title>
            <link>https://medium.com/javarevisited/mastering-c-abstract-class-interface-and-pure-virtual-functions-in-few-steps-ddbeff770d1f?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddbeff770d1f</guid>
            <category><![CDATA[virtual-function]]></category>
            <category><![CDATA[pure-virtual-function]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[abstract-class]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 05:11:02 GMT</pubDate>
            <atom:updated>2023-12-30T10:44:32.033Z</atom:updated>
            <content:encoded><![CDATA[<p>Explained in simple words about Abstract Class, Interface, Virtual, and Pure Virtual Functions in C++ with examples 😉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*v0DezEiwvAe9Sxy9sZ0wwg.jpeg" /><figcaption>Image source: <a href="https://prepinsta.com/abstract-class-in-java/">link</a></figcaption></figure><p>Hello Jawans 😎, today we will be learning about Abstract Class, Interface, Virtual Functions, and Pure Virtual Functions. Howzzzzz the <strong>Joshhh</strong>hhhhh …???… ⭐🤩🔥</p><h3>Heads Up ⛑</h3><p>When we talk about Abstract Classes and Interfaces in C++, most people tend to get confused. The confusion is because in languages such as Java, and C# we have keyword abstract and Interface for creating Abstract Class and Interface Class. But in C++ we don’t have any language-supported keywords for creating such classes.</p><blockquote>C++ is flexible and powerful enough to create Abstract and Interface classes without any keywords.</blockquote><p>Before learning 📚 about Abstract Class and Interface let’s first talk <strong><em>🎤 </em></strong>about <strong><em>Virtual </em></strong>and <strong><em>Pure Virtual Functions.</em></strong></p><h3>1. What is a Virtual and Pure Virtual Functions</h3><p>A Virtual function (<strong>VF</strong>) is always defined in a Base or Parent class with the keyword virtual at the beginning and is overridden in the derived/child class. We use the virtual function for <strong>dynamic binding or late binding, </strong>most famously known as <strong>Runtime Polymorphism. </strong><em>If a VF is not redefined in the derived/child class, it will not cause any compile error but then it doesn’t make sense to make the function virtual if it’s not overridden in the child class.</em></p><pre>virtual void setValues(int B, char a, float b, string u) {<br>   // assign those values to desired variables<br>} </pre><p>A Pure Virtual Function (<strong>PVF</strong>) is a special type of Virtual Function. A Pure Virtual Function must be overridden in one of its derived/child classes. <strong>A PVF only has a function declaration and no definition. </strong>It is declared by assigning 0 to a virtual function without any function body or implementation.</p><pre>// Function signature of a Pure Virtual Function<br>virtual void setValues (int B, char a, float b, string u) = 0;</pre><blockquote>Now that we know what Virtual and Pure Virtual Functions are let’s talk 🎤about Abstract Class and Interface.</blockquote><h3>1. Abstract Class in C++</h3><p>An Abstract Class, in C++, is a class that has <strong>at least one Pure Virtual Function (PVF)</strong> however the class is <strong><em>allowed to have implemented methods and declared variables</em></strong><em>.</em> Since the Abstract class has PVF, <strong><em>an abstract class cannot be instantiated</em></strong>, but we can create a Pointer variable of an Abstract Class pointing to its derived/child class objects.</p><pre>class MyAbstractClass {<br>    private:<br>      int Baps;<br>    public:<br>      MyAbstractClass {  // Constructor<br>        Baps= 0;<br>      }<br><br>      void setBaps(int baps) {  This is just a normal function<br>          Baps= baps;<br>      }<br><br>      virtual void setValue(int B, char a, float b, string u) {<br>           // This is a Virtual Function<br>          //  Do the relevant assignment.<br>      }<br><br>      // This is a Pure Virtual Function<br>      virtual void resetValues() = 0;<br><br>};</pre><blockquote>If a class doesn’t implement the Pure Virtual Function(s) of its parent Abstract class, then the child also becomes an Abstract Class and cannot be instantiated.</blockquote><h3>2 Interface in C++</h3><p>In C++ when a <strong><em>class has all its functions (methods) as Pure Virtual Functions</em> </strong>then that class is called an Interface Class. An Interface Class cannot have any variable declarations. Similar to Abstract Class we cannot create objects of an Interface Class.</p><pre>class MYInterfaceClass {<br>  public:<br>    // Pure Virtual Functions<br>    virtual void setValues(int B, char a, float b, string u) = 0;<br>    virtual void setValue(int B) = 0;<br>    virtual void setValue(char a) = 0;<br>    virtual void setValue(float b) = 0;<br>    virtual void setValue(string u) = 0;<br>};</pre><p>R<strong>ead my other tutorials on ReactJs</strong>, I’ve explained it in simple words with examples and also provided a Git Hub link for the source code.</p><p><a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189"><strong>Part 1: How to create a new React App Explained in simple steps</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/part-2-easy-way-to-create-reactjs-components-7d458b577c67"><strong><em>Part 2: Easy Way To Create ReactJS Components</em></strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/drag-drop-react-beautiful-dnd-328e00797f27"><strong>DRAG &amp; DROP: REACT BEAUTIFUL DND</strong></a></p><p><strong>Read my other tutorial on Android Development</strong></p><p><a href="https://medium.com/@ashikthulungrai7/android-shared-preferences-11517624a991"><strong>Android Shared Preferences. Save and retrieve simple data easily… | by KIHSA Rai | Jul, 2023 | Medium</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/android-view-and-viewgroup-6a8e235a3c92"><strong>Android View and ViewGroup. Easy tutorial about Android View and… | by KIHSA Rai | Jul, 2023 | Medium</strong></a></p><p>let&#39;s meet again in next tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_F2VYxS4B6_2Z1Gb" /><figcaption>Photo by <a href="https://unsplash.com/@mikael_k?utm_source=medium&amp;utm_medium=referral">Mikael Kristenson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddbeff770d1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/mastering-c-abstract-class-interface-and-pure-virtual-functions-in-few-steps-ddbeff770d1f">Mastering C++ Abstract Class, Interface, and (Pure)Virtual Functions in Few Steps 👣</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android View and ViewGroup]]></title>
            <link>https://ashikthulungrai7.medium.com/android-view-and-viewgroup-6a8e235a3c92?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a8e235a3c92</guid>
            <category><![CDATA[andorid-dev]]></category>
            <category><![CDATA[android-viewgroup]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-views]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 05:08:53 GMT</pubDate>
            <atom:updated>2023-07-14T07:57:15.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Easy tutorial about Android View and ViewGroup with simple examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OKx-UNWox38ZPtd4" /><figcaption>Photo by <a href="https://unsplash.com/@rsdiz?utm_source=medium&amp;utm_medium=referral">Muhammad Rosyid Izzulkhaq</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello Jawans, 😎 today we will be learning about Android View and ViewGroups. Howzzzzz the <strong>Joshhh</strong>hhhhh …???…</p><blockquote>To learn about <strong>Android SharedPreferences </strong><a href="https://medium.com/@ashikthulungrai7/android-shared-preferences-11517624a991">click here</a> <em>👍💗</em></blockquote><h3>1. What is a View</h3><p>Views are the building block of an Android Application’s UI Interface (UI). In very blunt terms it’s a box that users can interact with either for giving input or performing some action. There are many views, but today we will highlight only a few most commonly used views.</p><ul><li><strong>TextView: </strong>For displaying text contents in the UI.</li><li><strong>EditTextView: </strong>For adding input area in the UI.</li><li><strong>ImageView: </strong>For displaying Image contents in the UI.</li><li><strong>ButtonView: </strong>For adding (action) buttons in the UI.</li><li><strong>ImageButtonView: </strong>For adding (action) buttons with an image in the UI.</li><li><strong>RadioButtonView: </strong>For adding radio buttons in the UI.</li><li><strong>Checkbox ButtonView: </strong>For adding CheckBox buttons in the UI.</li></ul><blockquote>In the below image, we can see an Instagram App UI translated in terms of Views</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbyapb8pwU2o-2TFnI6A6A.jpeg" /><figcaption>Image Source: <a href="https://techcrunch.com/wp-content/uploads/2023/01/IG-Nav-2023-.png">link</a>, Edited by: <a href="https://www.instagram.com/behind_pixl/?igshid=YmMyMTA2M2Y%3D"><strong>@behind_pixl</strong></a></figcaption></figure><blockquote>As you can see, we can use a combination of ImageView, TextView, ButtonView, and other views to create an attractive UI.</blockquote><h3>2. What is a ViewGroup 🤔💭</h3><p>ViewGroup, as the name suggests is a special type of view that can contain other views (children) one or more. It is an invisible container for other views and can also contain another ViewGroup inside it. Below are some ViewGroups</p><ul><li><strong>LinearLayout</strong></li><li><strong>RelativeLayout</strong></li><li><strong>FrameLayout</strong></li><li><strong>TableLayout</strong></li><li><strong>CoordinatorLayout</strong></li><li><strong>ConstraintLayout</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*FZk9Tdx7PClafPjod_zZHw.jpeg" /><figcaption>Image source: <a href="https://programming.vip/docs/the-easiest-to-understand-series-of-custom-view-principles-1.html">link</a></figcaption></figure><blockquote>To learn more about <a href="https://developer.android.com/reference/android/view/View">View</a> and <a href="https://developer.android.com/reference/android/view/ViewGroup">ViewGrop</a> visit the <a href="https://developer.android.com/reference/android/view/ViewGroup">Android studio docs</a></blockquote><p>I hope you <strong>Jawans 😎 </strong>enjoyed reading the tutorial let’s meet in the next tutorial. Howzzzzz the <strong>Joshhh</strong>hhhhh …???…</p><blockquote>To Read about <strong>Android Shared Preferences </strong><a href="https://medium.com/@ashikthulungrai7/android-shared-preferences-11517624a991"><strong>click here</strong></a></blockquote><blockquote>To Read about <strong>ReactJs </strong><a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189"><strong>click here</strong></a></blockquote><h4>My Sources:</h4><p><a href="https://developer.android.com/reference/android/view/View">View | Android Developers</a></p><p><a href="https://developer.android.com/reference/android/view/ViewGroup">ViewGroup | Android Developers</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*CM33ByTbzwbek5LIXtpqqg.png" /><figcaption>Image source: <a href="https://recruitingtimes.org/wp-content/uploads/2016/11/tech-industry.png">link</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a8e235a3c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Shared Preferences]]></title>
            <link>https://ashikthulungrai7.medium.com/android-shared-preferences-11517624a991?source=rss-5108acd168c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/11517624a991</guid>
            <category><![CDATA[sofware-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-programming]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <dc:creator><![CDATA[KIHSA Rai]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 12:08:03 GMT</pubDate>
            <atom:updated>2024-01-29T08:44:38.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Save and retrieve simple data easily using shared preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*p-qqqDkqjJ0z6TcxdOzuyA.png" /><figcaption>image source: <a href="https://www.chawtechsolutions.com/android-app-development-company/">chawtechsolutions</a></figcaption></figure><p>Hello Jawans, 😎 today we will be learning about Android Shared Preferences,</p><ol><li>What is Shared Preferences?</li><li>How to use them in Project?</li><li>When to use them in Project?</li></ol><h3>1. What is Shared Preferences</h3><p>Shared-Preferences <strong>(SP)</strong> is one of the easiest and simple ways to store-retrieve primitive and small amounts of data which has the nature of Key-Value pair. The data is stored in the file in the device storage and can be String, int, boolean, or float. It’s simply an XML file on the device which can be read and edited using simple methods.</p><h3>2. How to use Shared Preferences</h3><p>We can create or access the already created SP file by using any of the below functions.</p><h3><strong>I. getPreferences()</strong></h3><p>This method is used to access activity-specific sharedPreferences (SP). This method is used when we want to access only a single SP that is specific to an activity.</p><blockquote>The name of the sharedPreferences file is the same as the Activity Filename, so no need to pass the sharedPreferences filename as an argument.</blockquote><pre>SharedPreferences SP= getActivity().getPreferences(Context.MODE_PRIVATE);</pre><h3><strong>II. getSharedPreferences()</strong></h3><p>This method is used to access application-specific sharedPreferences. Since it uses Application-specific SP files we need to provide the SP Filename in the argument along with the access type. We use this also when we want to access more than one SP file.</p><pre>Context context = getActivity();<br>SharedPreferences SP = context.getSharedPreferences(<br>        getString(R.string.preference_file_key), Context.MODE_PRIVATE);</pre><p>As you can see, we need to pass the operating mode of the SP file in the arguments. These are the most common operating modes.</p><ul><li><strong>MODE_PRIVATE</strong>: Accessible to the calling application (Default Mode).</li><li><strong>MODE_PUBLIC: </strong>Accessible to every application in the device.</li><li><strong>MODE_APPEND: </strong>Append the preference with already opened SP.</li><li><strong>MODE_MULTI_PROCESS: </strong>This will listen for any changes made to the SP file even if the file is already loaded. It’s useful when multiple processes are using the same SP file.</li><li><strong>MODE_WORLD_READABLE </strong>&amp; <strong>MODE_WORLD_WRITEABLE </strong>are deprecated due to security reasons.</li></ul><blockquote>While naming the SP files it&#39;s important to name them uniquely. A very good exercise is to prefix the name with ApplicationName example: com.example.myAppName.MY_PREFERENCE_FILE</blockquote><h3>2.a How to Edit SharedPreferences</h3><p>To edit or write into SP files we need to create an editor SharedPreferences.Editor by calling the method edit(). Once we have the editor we can edit/write by passing the key and value to method putInt(), putString(), putBoolean(), etc. To apply those changes at the end we need to call commit() or apply() method.</p><pre>String SP_Filename= &quot;com.example.myAppName.MY_PREFERENCE_FILE&quot;<br>SharedPreferences SP = getSharedPreferences(SP_Filename, Context.MODE_PRIVATE);<br><br>Editor editor = SP.edit();                   // Getting the editor for SP<br><br>editor.putBoolean(&quot;flag&quot;, true);             // Storing boolean true/false <br>editor.putString(&quot;appName&quot;, &quot;AndroidApp1&quot;);  // Storing string <br>editor.putInt(&quot;appVersion&quot;, 7);              // Storing integer <br>editor.putFloat(&quot;floatKey1&quot;, 123.45);        // Storing float <br>editor.putLong(&quot;longKey1&quot;, 878789123412341); // Storing long <br><br>editor.commit();                             // commit the changes </pre><h3>2.b How to Read Data from SharedPreferences</h3><p>To read data from SP file we need to provide the key to the respective methods.</p><pre>String SP_Filename= &quot;com.example.myAppName.MY_PREFERENCE_FILE&quot;<br>SharedPreferences SP = getSharedPreferences(SP_Filename, Context.MODE_PRIVATE);<br><br>String app_Name=  SP.getString(&quot;appName&quot;, null);        // getting String<br>int app_Version=  SP.getInt(&quot;appVersion&quot;, -1);          // getting Integer <br>float temp_Float= SP.getFloat(&quot;floatKey1&quot;, null);       // getting Float<br>long temp_Long=   SP.getLong(&quot;longKey1&quot;, null);         // getting Long<br>boolean flag=     SP.getBoolean(&quot;flag&quot;, false);         // getting boolean</pre><h3>2.c How to Delete Data from SharedPreferences</h3><p>We can delete the data from the SP file one at a time by using the key editor.remove(&quot;Key&quot;) , or we can remove all the data by calling the method editor.clear() and then saving the changes using the method commit() or apply() .</p><pre>String SP_Filename= &quot;com.example.myAppName.MY_PREFERENCE_FILE&quot;<br>SharedPreferences SP = getSharedPreferences(SP_Filename, Context.MODE_PRIVATE);<br><br>Editor editor = SP.edit();              // Getting the editor for SP<br><br>editor.remove(&quot;appName&quot;);               // Remove using the key<br>editor.remove(&quot;appVersion&quot;);            // Remove using the key<br>editor.commit()<br><br>editor.clear()                          // Remove all Data<br>editor.commit()</pre><blockquote>If you want a more detail tutorial on SharedPreferences write in the comment “<strong>more detail tutorial</strong>” and feel free to flap and follow. 😅🤣</blockquote><h3>3. When to use Shared Preferences</h3><p>Well, we can use SharedPreferences when the application wants to save the user preferences, settings, user basic data, app statistics, etc.</p><blockquote>To learn about when to create sharePreferences and when to commit or apply the changes in sharedPreferences during the activity life-cycle, follow me, clap for the tutorial and comment “<strong>more detail tutorial</strong>”</blockquote><p><strong>Read my other tutorials on ReactJs</strong>, I’ve explained it in simple words with examples and also provided Git Hub link for source code.</p><p><a href="https://medium.com/@ashikthulungrai7/how-to-create-a-new-react-app-3286a37e2189"><strong>Part 1: How to create a new React App Explained in simple steps</strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/part-2-easy-way-to-create-reactjs-components-7d458b577c67"><strong><em>Part 2: Easy Way To Create ReactJS Components</em></strong></a></p><p><a href="https://medium.com/@ashikthulungrai7/drag-drop-react-beautiful-dnd-328e00797f27"><strong>DRAG &amp; DROP: REACT BEAUTIFUL DND</strong></a></p><p>Read my other tutorial on C++</p><p><a href="https://medium.com/@ashikthulungrai7/mastering-c-abstract-class-interface-and-pure-virtual-functions-in-few-steps-ddbeff770d1f">Mastering C++ Abstract Class, Interface, and (Pure)Virtual Functions in Few Steps 🦵👣 | by KIHSA Rai | Jul, 2023 | Medium</a></p><blockquote>Read more about the Shared Preferences from the Android Docs <a href="https://developer.android.com/training/data-storage/shared-preferences"><strong>link</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11517624a991" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>