<?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 Nerdan on Medium]]></title>
        <description><![CDATA[Stories by Nerdan on Medium]]></description>
        <link>https://medium.com/@danielkarama13?source=rss-61617cf44ac6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AoIU1cKUFbfBIBhRHPTDlQ.jpeg</url>
            <title>Stories by Nerdan on Medium</title>
            <link>https://medium.com/@danielkarama13?source=rss-61617cf44ac6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:52:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielkarama13/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[Let’s Build a Real-time Chat Application with Django Channels and Redis Tech Stack]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://python.plainenglish.io/lets-build-a-real-time-chat-application-with-django-channels-and-redis-tech-stack-63c80d301e2c?source=rss-61617cf44ac6------2"><img src="https://cdn-images-1.medium.com/max/600/1*6R1VcBKUTcNYidtrV3sOjw.png" width="600"></a></p><p class="medium-feed-snippet">Hello and welcome to yet another article:)I have always been curious on how real-time chat applications like WhatsApp and telegram work.</p><p class="medium-feed-link"><a href="https://python.plainenglish.io/lets-build-a-real-time-chat-application-with-django-channels-and-redis-tech-stack-63c80d301e2c?source=rss-61617cf44ac6------2">Continue reading on Python in Plain English »</a></p></div>]]></description>
            <link>https://python.plainenglish.io/lets-build-a-real-time-chat-application-with-django-channels-and-redis-tech-stack-63c80d301e2c?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63c80d301e2c</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 03:49:58 GMT</pubDate>
            <atom:updated>2024-04-22T01:44:25.541Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Crash Casino Bet Algorithm — Build your own app (Part 1)]]></title>
            <link>https://python.plainenglish.io/crash-casino-bet-algorithm-build-your-own-app-part-1-1dba109cc896?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dba109cc896</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[casino]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[crash-betting]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 08:37:58 GMT</pubDate>
            <atom:updated>2024-05-10T11:01:22.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Casino Bet Algorithm — Build Your Own App (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*cBpyvh70AjD19_NvG3q2Kg.jpeg" /></figure><p>Crash bet games have increasingly been an exciting online hobby for a number of people who hope to turn a quick buck in a fast paced world such as the one we are in . And who would blame them, in a world of fast foods and algorithmic trading more and more people favor making fast cash as opposed to trusting the process as the older generation did! If like me you are more intrigued by the mechanics behind it then you have come to the right place. The psychology silhouetting behind the piper’s flute , apart from being dead simple is equally exhilarating if instead the turns of the mind are what float your boat. Winning against a much larger opponent can be quite satisfying , we are after all ,all built for greatness! Anyways story for another day, the common wisdom is the house always wins. It wouldn’t hurt however to delve into the complex mathematical structure that governs the house’s edge.</p><h3>Gambling Strategies</h3><p>While every player has there own strategies , mostly based on intuition or mood, risk appetite perhaps even some calculations they made , here are a few well known mathematical based strategies. Note that there is a caveat hidden in a statistical probability called Poisson distribution which in summary measures the probability of a given number of events happening in a specified time period. The more you play the more likely you are to lose , in short Vegas always wins! This is a common model used in algorithmic trading and smart order routers.</p><h3>1. Fibonacci Strategy</h3><p>This tactic is a well-known winning strategy in Crash games, in which you calculate the ideal bet size for each round. For example, if you make a base bet of $1 and then lose in the first round, your next bet will also be $1. Protagonists of the strategy say it helps to limit or remove emotional bias from each bet. This strategy is also very popular when <a href="https://plainenglish.io/gambling/us/online-casinos/blackjack">playing blackjack online</a>.</p><h3>2. Martingale Strategy</h3><p>The theory behind the strategy is that you regain whatever’s been lost. For example, if you bet $1 and lost, you should increase your bet to $2 in the next round. Similarly, an anti-Martingale Strategy states that one must increase the trade size given a win. The goal is that the size of the winning bet will exceed the combined losses of all the previous bets. The difference is the size of the original bet size.</p><h3>3. D’Alembert Strategy</h3><p>The D’Alembert betting strategy involves raising your bet by one unit after a loss and lowering it by one unit after a win. If you bet $1 and lose, you bet $2 in the next round. If you win, your next bet must be reduced to $1.The aim is to generate a modest overall profit.</p><p>Having looked at the fundamentals of how the crash casino game is built by the gaming house and the different strategies used by players it’s time to pit the house against the players . In Part 2 we create our casino crash game based on the principles in this article. We will be using python to write our crash casino app, sip your coffee, decorate your Christmas trees as I prepare my development environment. Happy holidays!</p><p><a href="https://milyin.com/500132/crash-casino-bet-algorithm-build-your-own-app-part-1/">https://milyin.com/500132/crash-casino-bet-algorithm-build-your-own-app-part-1/</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dba109cc896" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/crash-casino-bet-algorithm-build-your-own-app-part-1-1dba109cc896">Crash Casino Bet Algorithm — Build your own app (Part 1)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Case For The African Writer]]></title>
            <link>https://danielkarama13.medium.com/a-case-for-the-african-writer-877cdcefd6d1?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/877cdcefd6d1</guid>
            <category><![CDATA[human-rights]]></category>
            <category><![CDATA[black-history-month]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[blacklivesmatter]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Tue, 10 May 2022 02:17:21 GMT</pubDate>
            <atom:updated>2022-05-10T02:17:21.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRcHSTEdbONEQE53P_jDtw.jpeg" /><figcaption><a href="https://www.olympic.org/mexico-1968">1968 Olympic Games</a> in Mexico City, gold and bronze medalists <a href="http://www.tommiesmith.com/">Tommie Smith</a> and <a href="https://www.facebook.com/pages/category/Public-Figure/Dr-John-Carlos-Official-133399393389456/">John Carlos</a> made history when they each stood on the the victory dais and raised a black gloved fist in solidarity with the Black Power movement.</figcaption></figure><p>As my first non tech article , I would have wanted to share a great deal of other content but none would come close to that African activism. Why now you may ask, simply because there has never been a better time than now for digital activism. Aggravating for the equal treatment of all peoples regardless of color, gender and social status either of their person or those around them.</p><p>Over the years people of color across the world have been subjected to various means of exploitation from the dark ages where Africans were transported across the world’s oceans , separated from their land and the people they loved to go work on plantations and mines in far off lands for no pay. The two world wars despite their darkening clouds of human loss of life never before witnessed , brought about the dawn of the concepts of freedom, equality and justice. While simple words , these represent an endless desire by human beings to live as their creator willed them to be. To enjoy the fruits of their labor , move around the world freely and to settle disputes in a way that discourages the aggressor from committing the same errors while preserving the dignity of the oppressed.</p><p>Following in the footsteps of all those activists and pan Africans that walked in the murky roads of activism, I feel it’s my duty to address inequality in a field am passionate about. The tech industry brings modernity to mind to whoever comes across it , however some ideas and actions have been carried on from the vestiges of the old world and hence the reason for putting pen to paper to what I do best, write(and code:D)!</p><p>Now to why I really wrote this article, by far the easiest I have ever done. Medium and other online platforms for writers and content creators ought to have included Africa, India and other countries as part of their partner program. What this means is that writers who happen not to be in Europe and the Americas cannot earn as their counterparts, inequality! As of writing this article this is not possible for some reason. I would like to believe it is a mistake on their part and not by choice.</p><p>In Africa we love to tell stories over the fireplace, we welcome visitors ,respect our elders and our motto is Ubuntu(What is mine is yours). My point being the prejudice perpetuated on people of color across centuries is unwarranted. The world would be a better place with our ideas on the same table , not just our wealth. Kwaheri!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=877cdcefd6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a REST API Endpoint on Top of an Existing Legacy Database Using FastAPI]]></title>
            <link>https://python.plainenglish.io/how-to-build-a-rest-api-endpoint-on-top-of-an-existing-legacy-database-using-fastapi-489f38feab98?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/489f38feab98</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 13:45:20 GMT</pubDate>
            <atom:updated>2022-04-04T13:58:02.506Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on reading data from a CSV file and inserting it into a database and building a REST API endpoint on top of an existing database.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5oUbrG930x9hZmCZdDMzw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sincerely Media</a> on <a href="https://unsplash.com/s/photos/rest?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A lot of different companies and developers have legacy systems with databases spanning several years or even decades. In order to turn these archaic systems into conformity with modern solutions and needs in the software sphere, two strategies can be applied. The first is to commission the development of a new system complete with its own database and the second is to develop a new system using modern standards and have data from the old legacy system passed to the new system. The only challenge is in the difference in software standards applied between the old and new systems.</p><p>Enter REST which is a modern standard of sharing data between different systems. In this article, I will attempt to assume a database that has existing data and then build a REST API endpoint to pass that data to an external system.</p><p>What you will learn from this article:</p><ol><li>Reading data from a CSV file using pandas and inserting that data into a database.</li><li>Building a REST API endpoint on top of an existing database.</li></ol><p>Requirements for this tutorial include:</p><ol><li>Setting up a virtual environment using virtualenv</li><li>Installing FastAPI and SqlAlchemy inside the virtualenv</li><li>An existing database with data.</li></ol><h4>The Database</h4><p>For this tutorial, I have set up an MYSQL database on my local machine. (The tutorial should work with any database of your choice i.e. Oracle, PostgreSQL, or SQLite)</p><ol><li>Download the following CSV from the link below. We will insert data from this CSV into our database using pandas.</li><li><a href="https://www.kaggle.com/prateekmaj21/anz-banking-data">https://www.kaggle.com/prateekmaj21/anz-banking-data</a></li><li>pip install mysql-connector-python &amp;&amp; sqlalchemy</li></ol><p>4. Create a schema/database using SQL Workbench or the SQL command line ~ CREATE DATABASE tutorial;</p><p>5. Run the script below to insert all the data from the CSV into your database. (*Adjust the database connection string to your database)</p><pre>#!/usr/bin/env python3<br>import pandas as pd<br>import mysql.connector<br>import sqlalchemy<br>import numpy as np</pre><pre>#Create engine to link our pandas dataframe to our database<br>&#39;&#39;&#39;For clarity: ‘mysql+pymysql’ indicates that I am using mysql as my database management system, and functions within the module pymysql to interface with this database management system (DBMS).<br>username = dbuser, password =******, hostname = localhost, and database name = tutorial.<br>&#39;&#39;&#39;</pre><pre>engine = sqlalchemy.create_engine(&#39;mysql+pymysql://dbuser:******@localhost/tutorial&#39;)</pre><pre>#The filename is the csv downloaded from the link in step 2 above <br>df = pd.read_csv(&#39;ANZ.csv&#39;)</pre><pre>#Check memory usage of current dataframe<br>#print(df.shape)<br>#print(df.dtypes)<br>#print(df.memory_usage(index=False, deep=True).sum())</pre><pre>#print(df.info())</pre><pre>#Improve memory usage<br>dfi = pd.read_csv(&#39;ANZ.csv&#39;,dtype={&#39;status&#39;:&#39;string&#39;,&#39;card_present_flag&#39;:&#39;string&#39;,&#39;bpay_biller_code&#39;:&#39;string&#39;,&#39;account&#39;:&#39;string&#39;,<br>                                   &#39;currency&#39;:&#39;string&#39;,&#39;long_lat&#39;:&#39;string&#39;,&#39;txn_description&#39;:&#39;string&#39;,<br>                                   &#39;merchant_id&#39;:&#39;string&#39;,&#39;merchant_code&#39;:&#39;float16&#39;,&#39;first_name&#39;:&#39;string&#39;,<br>                                   &#39;balance&#39;:&#39;float16&#39;,&#39;date&#39;:&#39;string&#39;,&#39;gender&#39;:&#39;string&#39;,&#39;age&#39;:&#39;int8&#39;,&#39;merchant_suburb&#39;:&#39;string&#39;,<br>                                   &#39;merchant_state&#39;:&#39;string&#39;,&#39;extraction&#39;:&#39;string&#39;,&#39;amount&#39;:&#39;float16&#39;,&#39;transaction_id&#39;:&#39;string&#39;,<br>                                   &#39;country&#39;:&#39;string&#39;,&#39;customer_id&#39;:&#39;string&#39;,&#39;merchant_long_lat&#39;:&#39;string&#39;,&#39;movement&#39;:&#39;string&#39;,})</pre><pre>dfi = dfi.replace([np.inf,-np.inf],np.nan)<br>df2 = dfi.replace(np.nan, &#39;&#39;, regex=True)<br>df2 = df2.rename(columns={&quot;date&quot;:&quot;transaction_date&quot;})<br>df2 = df2.rename(columns={&quot;extraction&quot;:&quot;extraction_timestamp&quot;})<br>df2 = df2.rename(columns={&quot;amount&quot;:&quot;transaction_amount&quot;})<br>df2[&#39;merchant_code&#39;] = df2[&#39;merchant_code&#39;].replace(&quot;&quot;,0.0)</pre><pre>#Insert the data to the database using to_sql method.<br>df2.to_sql(name=&#39;financial_data&#39;,con=engine, index=False, if_exists=&#39;append&#39;)</pre><h4>Starting a FastAPI Project</h4><p>Once the database part is done we need to achieve the following:</p><ol><li>Connect to the database using an ORM(Object Relation Mapper), which is basically a fancy way of saying we need to connect to the database for the purpose of high-level interaction with the database. Here we shall leverage a library called SQLAlchemy. SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.</li><li>Expose our data from the database via REST API endpoint for other applications to consume. For this we will use FastAPI, which the contributors describe as “<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production” It is a python based framework that delivers reliable, easy to use APIs at very fast speeds! </em>Follow the link below to read more on the FastAPI project. <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a></li></ol><p>We start by creating a project (name it any way that floats your boat) I called mine FastDbTutorial. Depending on your operating system and or preference, this can be done in a number of ways.</p><p>For Linux users run the following command to get started:</p><p>1. Create your project folder using the below command:</p><pre>mkdir FastDbTutorial</pre><p>2. Install virtualenv package using the below command:</p><pre>pip3 install virtualenv</pre><p>3. Change to your directory folder (FastDbTutorial) then create a virtual environment and activate it:</p><pre>$   cd FastDbTutorial<br>$   virtualenv venv<br>$   source venv/bin/activate</pre><p>4. If it has worked properly and activated you should see the below:</p><pre>(venv) ~/FastDbTutorial$ </pre><p>5. Inside the project folder with your virtual environment activated install the following packages using the commands below:</p><pre>(venv) ~/FastDbTutorial$ pip install PyMySQL<br>(venv) ~/FastDbTutorial$ pip install SQLAlchemy<br>(venv) ~/FastDbTutorial$ pip install fastapi</pre><p>For Windows users:</p><p>I used the pycharm IDE and setup a new project with virtualenv, its pretty straightforward . In case it’s your first time, use the link below to learn how to setup your project and proceed with the tutorial.</p><p><a href="https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-python-project.html">Step 1. Create and run your first Python project | PyCharm</a></p><p>I used PyCharm community edition for this tutorial and set up the folder structure as below:</p><pre>└── FastDbTutorial<br>  ├── __init__.py <br>  ├── crud.py    <br>  ├── database.py     <br>  ├── main.py     <br>  ├── models.py     <br>  └── schemas.py</pre><p>Once the skeleton has been set up, now we go to the meat of the project , I will explain one by one the purpose of the files in achieving our project goals starting with the __init__.py</p><p><strong>Note: Any line that begins with # is a comment</strong></p><p>__init__.py tells the IDE and even Python itself that this is a Python package and is useful when doing imports between the various modules in our project.</p><pre>#__init__.py</pre><pre>import os, sys</pre><pre>sys.path.append(os.path.dirname(os.path.realpath(__file__)))</pre><p>The first thing we need to do is connect to the database. We do this using SQLAlchemy from the file database.py:</p><pre>#database.py</pre><pre>from sqlalchemy import create_engine<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker<br><br>SQLALCHEMY_DATABASE_URL = &quot;mysql+pymysql://database_username:database_password@127.0.0.1/database_name&quot;<br><br>engine = create_engine(SQLALCHEMY_DATABASE_URL  , echo=True)<br><br>#Each instance of SessionLocal class will be  database session<br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br><br>#we use declarative_base to return a class which we will inherit from to create database models or classes<br>Base = declarative_base()<br><br><br></pre><p>Once we have connected to the database the next step is to create models in SQLAlchemy. A model in the high-level framework language is the equivalent of a table in a database. Therefore we are able to create classes that represent the underlying database tables and the variables corresponding to the columns of that table. Also, any relationship between tables should be declared here . This allows the SQLAlchemy framework to convert the data structure of the underlying database to high-level Python data structures and vice-versa. We do this in the models.py file. <strong>Note: One of the fields has to have a primary key set to True even if the underlying database table doesn’t have a primary key. This is because of how SQLAlchemy saves objects in a session.</strong></p><pre>#models.py<br>from sqlalchemy import Boolean, Column, Integer, String, Date, DateTime,Float,Text<br>from database import Base</pre><pre>#The __tablename__ attribute should be the actual name of the #database we are connecting to</pre><pre>class FinanceData(Base):<br>    __tablename__ = &quot;financial_data2&quot;<br><br>    status = Column(Text)<br>    card_present_flag = Column(Text)<br>    bpay_biller_code = Column(Text)<br>    account = Column(Text)<br>    currency = Column(Text)<br>    long_lat = Column(Text)<br>    txn_description = Column(Text)<br>    merchant_id = Column(Text)<br>    merchant_code = Column(Float)<br>    first_name = Column(Text)<br>    balance = Column(Text)<br>    transaction_date = Column(Date)<br>    gender = Column(Text)<br>    age = Column(Integer)<br>    merchant_suburb = Column(Text)<br>    merchant_state = Column(Text)<br>    extraction_timestamp = Column(DateTime)<br>    transaction_amount = Column(Float)<br>    transaction_id = Column(Text,primary_key=True)<br>    country = Column(Text)<br>    customer_id = Column(Text)<br>    merchant_long_lat = Column(Text)<br>    movement = Column(Text)</pre><p>After we have done the mapping , we then need to create a schema , once the data has been retrieved by SQLAlchemy using the connection engine it then passes through pydantic (which is a library within fastapi that performs data validation and settings management using python type annotations. <em>pydantic</em> enforces type hints at runtime, and provides user-friendly errors when data is invalid.)</p><pre>#schemas.py<br>from typing import Optional<br>from pydantic import BaseModel<br>from datetime import datetime,date<br><br>class FinanceData(BaseModel):<br>    status: str<br>    card_present_flag: str<br>    bpay_biller_code: str<br>    account: str<br>    currency: str<br>    long_lat: str<br>    txn_description: str<br>    merchant_id: str<br>    merchant_code: float<br>    first_name: str<br>    balance: str<br>    transaction_date: str<br>    gender: str<br>    age: int<br>    merchant_suburb: str<br>    merchant_state: str<br>    extraction_timestamp: datetime<br>    transaction_amount: float<br>    transaction_id: str<br>    country: str<br>    customer_id: str<br>    merchant_long_lat: str<br>    movement: str<br><br>    class Config:<br>        orm_mode = True</pre><pre>#Pydantic&#39;s orm_mode will tell the Pydantic <em>model</em> to read the data #even if it is not a dict, but an ORM model (or any other arbitrary #object with attributes).</pre><p>The next step after high-level data validation would be to write functions that do the actual querying of the database using the SQLAlchemy syntax. For our tutorial we only query all the data in the database, we don’t do insertion or deletion whoever the code for that would be done in the file below i.e ccrud.py. (CRUD- is an acronym considered necessary to implement a persistent storage application: <strong><em>create, read, update</em></strong> and <strong><em>delete</em></strong>.)</p><pre>#crud.py<br>from sqlalchemy.orm import Session<br>import models, schemas<br><br>def get_financedata(db: Session, skip: int=0,limit: int=1000):<br> return db.query(models.FinanceData).offset(skip).limit(limit).all()</pre><p>In the code above we create a function called get_financedata with the following:</p><ol><li>db:Session which is passed the current db session which we will create ,skip which implies skipping n number of records and limit can be used to limit the number of returned entries.</li><li>the db.query(models.FinanceData).offset(skip).limit(limit).all() — This is SQLAlchemy syntax that queries the models from models.py we created earlier to give us results from the database.</li></ol><p>Finally, we go to our main.py file where we will put the final touches to our project/app. Here we will initialize our FastAPI app and create functions that receive HTTP requests in the <em>paths /finance-data.</em></p><pre>from sqlalchemy.orm import Session<br>import crud, models,schemas<br>from database import SessionLocal,engine<br><br>models.Base.metadata.create_all(bind=engine)<br><br>app = FastAPI()<br><br>#Dependency<br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()<br><br>@app.get(&quot;/finance-data&quot;,response_model=list[schemas.FinanceData])<br>def read_financedata(skip: int=0, limit: int=1000, db: Session = Depends(get_db)):<br>    finance_data = crud.get_financedata(db,skip=skip,limit=limit)<br>    return finance_data</pre><p>If you have reached the end get yourself a cup of coffee before running this last command to start your application server!</p><pre>(venv) ~/FastDbTutorial$ uvicorn main:app --reload</pre><p>On your browser go to <a href="http://GET API endpoint">http://127.0.0.1/finance-data /</a> to see your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myaise3AosrMUer2b-dn3g.png" /></figure><h4><strong>D</strong>OCUMEN<strong>TATION</strong></h4><p>Now you must be thinking what about documentation for my new REST API? Well, good for you because FastAPI does that for you! Head over to <a href="http://documentation/">http://127.0.0.1/docs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JUiM0wCohjoeZp5bOKJxA.png" /></figure><p>Feel free to leave your comments, questions, and suggestions below! Ciao:)</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our</em><strong><em> </em></strong><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489f38feab98" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-build-a-rest-api-endpoint-on-top-of-an-existing-legacy-database-using-fastapi-489f38feab98">How to Build a REST API Endpoint on Top of an Existing Legacy Database Using FastAPI</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Motion Detection Using Arduino, PIR Sensor and Algorithms in SMART Environments]]></title>
            <link>https://python.plainenglish.io/motion-detection-using-arduino-pir-sensor-and-algorithms-in-smart-environments-63150d81cd48?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63150d81cd48</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 05:06:44 GMT</pubDate>
            <atom:updated>2021-11-17T11:25:34.535Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on motion detection using Arduino, PIR sensor, and algorithms in SMART environments.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*etr3hcBm4d1IXQ_4_NASCA.gif" /><figcaption>Thief breaking in via window</figcaption></figure><p>Most people and even organizations take a lot of consideration for the physical security of their premises or property. Traditionally that was done by pure brick and mortar with most security installations including fences, walls, castles, fortresses, trenches you get my point.</p><p>More recently as the world evolved more sophisticated ways of keeping unwanted guests out of property or areas they are not invited to have been developed. This includes sophisticated locks, safes, CCTV cameras, and sensors. The security system chosen draws a fine line to choose between the costs involved, effectiveness, and efficiency of the chosen security system.</p><p>In this article, I would like to show an innovative and cost-effective way of physical intrusion detection. It involves an Arduino microcontroller, a PIR sensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*pjEkTYCZH2rAgsX1rHjxTQ.png" /></figure><p>Why a motion sensor and not say a CCTV camera system you may ask. Pyroelectric Infrared Sensors have been an ideal choice for detecting motion in home, office, and factory surveillance systems. This is because they are small, inexpensive, and effective even in the dark. They are also a non-intrusive form of security as the sensors themselves do not emit any form of radiation or infrared light but instead detect the motion of animals or human beings.</p><p>To be able to use some algorithms, I would like to also perform signal processing on the motion detection therefore we will use analog outputs instead of digital outputs which are used to normally trigger an alarm, LED, etc.</p><h3><strong>1. Circuitry and Setup</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6xjB7JEb6WOvbfQ9Er3NQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QsNGcW4y7r401odQiA4k_g.jpeg" /></figure><p>Connect the circuit according to this circuit diagram, feel free to add an LED just to visualize the detection at first and check whether your circuit is working. I used Arduino Uno, three jumper cables, an HC-SR501 passive infrared sensor (PIR), and one LED.</p><p>For this tutorial, I connected my led to pin 13 on Arduino (note the Longer pin of the LED is + hence on pin 13, shorter pin on GND since it’s negative), I connected my PIR sensor output jumper cable to analog pin A3 on my Arduino Uno board.</p><p>For a simpler introduction to circuitry head over to</p><p><a href="https://create.arduino.cc/projecthub/55845/innovation-lab-11-pir-motion-sensor-with-led-43420e">Innovation Lab #11: PIR Motion Sensor with LED</a></p><h3><strong>2. Sensor Input Code</strong></h3><p>The first step is to install an Arduino IDE. In case you haven’t installed it on your machine, head over to <a href="https://docs.arduino.cc/hardware/uno-rev3">https://docs.arduino.cc/</a> for an easy installation guide for your operating system. Once that’s done we need to upload code to the Arduino board, this is called a sketch.</p><pre>int led = 13;<br>int sensor = A3;</pre><pre>void setup() {<br>  pinMode(led, OUTPUT);<br>  pinMode(sensor, INPUT);<br>  Serial.begin(9600);<br>}</pre><pre>void loop() {<br>  int sensorval = analogRead(sensor);<br>  Serial.println(sensorval);<br>  <br>  if (sensorval &gt; 234) {<br>    digitalWrite(led, HIGH);<br>  }<br>  else {<br>    digitalWrite(led, LOW);<br>  }<br>}</pre><p>In the above code, we specify the LED pin number which is 13, and the sensor pin which is A3 (Analog pin 3), the led is our output, and the sensor the input as we are reading data from the sensor and outputting it on the led once motion is detected. Then we enter the loop to read in the sensor data and print using Serial.println(). We then proceed to write to our led ie make it light up if our sensor value is above 234.</p><h3><strong>3. Python Code to Perform Signal Processing</strong></h3><p>After uploading the above sketch to our Arduino Uno board, we are now ready to read data using Python.</p><p>The first step is to install the libraries we will need :</p><p>(a) pip install pyserial → To communicate with Arduino</p><p>(b) pip install matplotlib → For data visualization</p><pre>import serial<br>import datetime<br>import matplotlib.pyplot as plt</pre><pre>ser = serial.Serial(&#39;COM3&#39;, 9600)</pre><pre>y=[]</pre><pre>for i in range(1000):<br>    dt = str(ser.readline().splitlines())<br>    dt = dt[3:-2]<br>    dt = int(dt)<br>    y.append(dt)<br>    print(dt)<br>    print(type(dt))<br>    x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(len(y))]<br>        <br>    plt.plot(x, y)<br>    plt.title(&quot;Real Time sensor data  plot&quot;)<br>    plt.xlabel(&quot;Time&quot;)<br>    plt.ylabel(&quot;Sensor Reading&quot;)<br>    plt.pause(0.05)<br>    plt.gcf().autofmt_xdate()</pre><pre>plt.show()</pre><p>Python code that reads the sensor data from Arduino and plots it as a line graph.</p><figure><img alt="Sensor data when no motion is detected" src="https://cdn-images-1.medium.com/max/640/1*SdoMhuVI4MltLfKdF5hCcQ.png" /><figcaption>Sensor Visualization when no motion is detected NB It goes to Zero</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*W8n2BMI6K-DkrzMiViucgA.png" /><figcaption>Sensor Data when motion is detected by the PIR Sensor</figcaption></figure><h3><strong>4. SMART Algorithm</strong></h3><p>Data is only useful if it helps us answer questions, solve problems, or optimize already existing solutions. After collecting all the data we need to perform some algorithm to make our sensor somehow smart.</p><p>My approach is to first perform data collection followed by data visualization which helps optimize data engineering techniques and come up with better models among other advantages such as storytelling for visual learners. It also helps in my case to understand what type of data we are getting as well as know the upper and lower limits of our data.</p><p>Our question is how to differentiate between an animal and a human, based on the sensor reading. Now note the data from animals is purely theoretical as I was unable to take my sensor out of the lab! Feel free to replace the data with actual data collected in the field.</p><p>This algorithm utilizes the 2500-year-old Pythagorean theorem. It’s not about <strong>distance</strong> in the sense of walking diagonally across a room. It’s about <strong>any distance</strong>, as the “distance” between our movie preferences or colors. If it can be measured, it can be compared with the Pythagorean Theorem. In this case, we want to measure how close human sensor data is close to animal data, the greater the number the more the gap!</p><pre>import math</pre><pre>human_data = [688, 694, 699, 699, 699, 699, 700, 699, 699, 699,<br>700, 698, 700, 699, 700, 699, 700, 700, 699, 700, 700, 699, 700, 700, 699, 699, 699, 699, 699, 700, 700, 700, 699, 700, 700, 699, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 699, 700, 700, 699, 699, 699, 699, 699, 700, 699, 699, 700, 699, 699, 700, 699, 699, 700, 700, 700, 700, 700, 699, 700, 700, 699, 699, 700, 700, 700, 700, 699, 700, 700, 699, 700, 700, 699, 700, 700, 699, 699, 700, 700, 699, 700, 700, 699, 700, 700]</pre><pre>animal_data = [388, 394, 399, 399, 399, 399, 400, 399, 399, 399, 400, 398, 400, 399, 400, 399, 400, 400, 399, 400, 400, 399, 400, 400, 399, 399, 399, 399, 399, 400, 400, 400, 399, 400, 400, 399, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 700, 399, 400, 400, 399, 399, 399, 399, 399, 400, 399, 399, 400, 699, 399, 400, 399, 399, 400, 400, 400, 400, 400, 399, 400, 400, 699, 399, 400, 400, 400, 400, 399, 400, 400, 399, 400, 400, 399, 700, 400, 399, 399, 400, 400, 399, 400, 400, 399, 400, 400]</pre><pre>def distance(data1,data2):<br>    &quot;&quot;&quot;Computes distance between two datasets<br>    &quot;&quot;&quot;<br>    distance = 0<br>    for i in range(data1):<br>        distance += pow((data1[i]- data2[i]),2)<br>        print(distance)<br>    return math.sqrt(distance)</pre><pre>distance(human_data,animal_data)</pre><p>Ciao!</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63150d81cd48" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/motion-detection-using-arduino-pir-sensor-and-algorithms-in-smart-environments-63150d81cd48">Motion Detection Using Arduino, PIR Sensor and Algorithms in SMART Environments</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computing Paradigms: A Modern vs Classical Approach (Python & Lisp)]]></title>
            <link>https://python.plainenglish.io/computing-paradigms-a-modern-vs-classical-approach-python-lisp-10474f3a1bc5?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/10474f3a1bc5</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 07:53:14 GMT</pubDate>
            <atom:updated>2021-11-29T04:03:44.810Z</atom:updated>
            <content:encoded><![CDATA[<h4>Object Oriented Programming vs Functional Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtHrkksEWoZM93BwIdehIQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@birminghammuseumstrust?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Birmingham Museums Trust</a> on <a href="https://unsplash.com/s/photos/classic-vs-modern-art?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Since the dawn of time, the world has always been divided into two opposing ideas. I will explain. In the electrical industry, the giants of their age Edison and Nicola Tesla championed two different ideas on how electricity should be conducted. Direct current vs Alternating current wars were very personal and the lengths that they went to ensure their ideas carried the day were both extreme and daunting. This was the precursor to the birth of the information age.</p><p>In the programming sphere, the major debate has been centered around functional vs object-oriented programming. These ideas are important because they represent different views on how to solve problems. In the case of functional programming, problems are solved by breaking them down into smaller parts called functions, with each function carrying out a very specific task. There is also the concept of pure functions, which is a pattern where functions: (a)Do not depend on external data. (b)Have no side effects (c) Give the same output with the same inputs.</p><p>The major concept in object-oriented programming is that of abstraction. The major question that object-oriented aims to answer is, how do you represent real-life objects like cars, human beings in the computing space. The answer to this is classes. A class contains methods that mimic real-world functionality, a person walking or a car changing gears. What’s more, there are key concepts like inheritance, polymorphism, and encapsulation.</p><p>So why do we take time to learn all these concepts, think of a detective who has been called into a crime scene where the only evidence left is the suspect’s coat. No witnesses and no fingerprints, where should they begin? In the case of our poor detective, they can start by measuring the length of the coat’s arms from end to end to get the suspect’s height. Now we know that the human height is on average 7 or 7.5 heads, this means we can get the size of our suspect’s head. We also know from human physiology that the Length of the face is equal to the length of the hand and that the length of the foot is equal to the length of the forearm. There we have the suspect’s foot size hmm? We could go on and on getting to understand our suspect better just as our detective here.</p><p>We should not forget that these concepts help us to solve problems in the most efficient way possible and that more than anything else should be the reason we learn them. More importantly, we should be able to use them to solve problems practically using computational thinking among other problem-solving techniques. The late Steve Jobs described computers as the bicycle of the mind, the reason being a <strong>bicycle</strong> can be up to 5 times more <strong>efficient</strong> than walking.</p><h4><strong>ENOUGH TALK SHOW ME THE MONEY!</strong></h4><p>Let’s crown this short theoretical class on functional vs object-oriented techniques with some practical code. We shall use common lisp for functional programming and test out python 3.7’s new data classes for object-oriented programming.</p><p>First, we write a function to help us to store some music for our theoretical upcoming music app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5522488c8e20aef07e684e721103fc5/href">https://medium.com/media/c5522488c8e20aef07e684e721103fc5/href</a></iframe><p>Our output for the code above running on Emacs should look like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttVJMiPZ87O5ZEMUsxcCJg.png" /><figcaption>Emacs Buffer for the above code</figcaption></figure><p>Now to our music App implementation using Python Data Classes newly introduced in Python 3.7.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7529ec009e73ffb25a1743bd38753a8/href">https://medium.com/media/d7529ec009e73ffb25a1743bd38753a8/href</a></iframe><p>In the age of APIs and multi-system dependencies, what does the future hold for pure functions? What of Aspect programming? Does quantum computing completely change how we solve problems? Which is better between functional and object-oriented techniques? I prefer to think of them as tools, one a knife another a fork, you simply cannot compare the two without losing perspective. Depending on the nature of the challenge or your approach to the solution feel free to use the most effective one.</p><p>That’s all from me, Love and Light :)</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10474f3a1bc5" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/computing-paradigms-a-modern-vs-classical-approach-python-lisp-10474f3a1bc5">Computing Paradigms: A Modern vs Classical Approach (Python &amp; Lisp)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation: The next Frontier in Devopps?]]></title>
            <link>https://danielkarama13.medium.com/automation-the-next-frontier-in-devopps-c0936d8d7669?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0936d8d7669</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ansible-tutorial]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 18:17:15 GMT</pubDate>
            <atom:updated>2021-04-27T18:17:15.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2r-U3kxiwx2iyJX5KjXOg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@birminghammuseumstrust?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Birmingham Museums Trust</a> on <a href="https://unsplash.com/s/photos/charlie-chaplin-factory?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>“What has been will be again, what has been done will be done again; there is nothing new under the sun ~<strong>Ecclesiastes 1:9 “</strong></p><p>Today I am reminded of my history class.We were taught that mankind has gone through several stages or ages as some may call it .What defined those ages were mainly the tools or systems that were so prevalent in that time and had impact enough to attach that period of time with the tools that characterized it.Stone age, iron age , bronze age , industrial age just to name a few.There is also the golden age of a society or a people which loosely translates to the zenith(developed from Arabic terms meaning “the way over one’s head”) or the highest a community or person reaches.Think the Egyptians and the pyramids, athletes and their peak performance.</p><p>Reminds me of our African heritage where in years not so distant ago, old men and women remembered their birth dates not with actual days but seasons.So one mzee(old person in Swahili ) would tell you I was born during the rainy season for example or when locusts invaded our harvests.</p><p>Fast forward to today where we are undoubtedly in the information age.No industry has seen so much change as the Tech industry has. Only a few years ago the software development life cycle consisted of a number of players i.e web designers, back end developers , deployment engineers , project managers and so forth.</p><p>Depending on who you talk to, they might say we are in the age of AI, cloud computing, Block chain, Augmented Reality and with good reason since these frontier technologies have produced giants if I may call them so. This include Sophia the robot (AI) ,Amazon (AWS), Bitcoin(Block chain), Oculus (Facebook). These technologies and industry leaders caused a shift on the way technology is done.</p><p>Once upon a time software developers would write code and pass their code over to testers/QA engineers who would test the code before passing the same over to system engineers who would ensure the application code is deployed on to hardware.The system admins, database admins would ensure the hardware and database systems would run smoothly with the application.</p><p>Enter Devops Engineers. The manual process described above where a single application would go through various teams is steadily reaching its twilight. This is mainly due to the rapid application development cycle that modern application requires and the necessity for 99.9 % up time that companies promise their users and clients. So Backend and frontend developers now have to skill up and adopt a new title devops, system and database admins have to evolve as well and thus acquire the title site reliability engineers(SRE).</p><h4>Software is King</h4><p>Enter Infrastructure as code which is basically software that provisions servers , something that used to be done by commands run manually on servers.This is now the new industry standard in network &amp; system engineering.I cannot fail to mention that this has been instrumental in the 5G roll, disaster recovery sites &amp; co location data centers out where network switches &amp; servers are provisioned through software.This means a large number of hardware having open operating systems can be configured across the globe with repeatable and reliable outcomes.Some notable technologies in this field include ansible, terraform, puppet(Infrastructure as code) and cumulus, Cisco IOS, Openswitch , Openwrt(Network Os).</p><p>I borrowed your attention at the beginning of what I hoped would be a short article, and now I have to repay your time and attention with interest. From my small neck of the woods in the tech universe I present to you my small automation project where I provision a node js application with pm2 using ansible on Amazon EC2 instance hosted on github.</p><p><a href="https://github.com/Maestro1/node-ansible-deployment.git">https://github.com/Maestro1/node-ansible-deployment.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0936d8d7669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Multi-step Form Using Django-Formtools and Django Inline Formsets]]></title>
            <link>https://python.plainenglish.io/django-formtools-django-inline-formsets-with-files-tutorial-e48d1e1f89df?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48d1e1f89df</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 10:14:33 GMT</pubDate>
            <atom:updated>2021-11-29T02:19:21.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to creating multi-step forms using django-formtools and Django inline formsets.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qDw2XcSZwdd4iNC9" /><figcaption>Photo by <a href="https://unsplash.com/@kpietrzakweb?utm_source=medium&amp;utm_medium=referral">Kamil Pietrzak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>“Teaching is a wonderful way to learn”</p><h4><strong>Requirements for this tutorial</strong></h4><ol><li>Django-formtools library is a cool library when you want to implement multi-step forms using sessions or cookies. Documentation is found here: <a href="https://django-formtools.readthedocs.io/en/latest/wizard.html#wizard-files">https://django-formtools.readthedocs.io/en/latest/</a></li><li>Django inline formsets using Django-dynamic-formsets library found here. <a href="https://github.com/elo80ka/django-dynamic-formset">https://github.com/elo80ka/django-dynamic-formset</a></li><li>Django crispy forms to give our forms a modern bootstrap feel.<a href="https://django-crispy-forms.readthedocs.io/en/latest/index.html">https://django-crispy-forms.readthedocs.io/en/latest/index.html</a></li></ol><p>Once you have installed the two libraries we are good to go. Feel free to skip the virtual environment setup if you are already familiar with the setup of a Django project and app.</p><p>Assumptions made in this tutorial, you are familiar with both Python language and Django framework. You are familiar with the Python packaging index (pip).</p><p>The scenario used is: Say you are applying for a university scholarship application where the university system requires you to fill a multi-step form. This is a basic two-step form where in the first step you enter your personal details ie name, date of birth, and in the second step, you enter your academic history ie name of institution, date_from, date_to, and certificate_awarded.</p><ol><li>Linux Users. Create a directory named multistep-tutorial for your project using the following commands</li></ol><pre> mkdir multistep-tutorial &amp;&amp; cd multistep-tutorial </pre><p>2. Create a virtual environment inside the folder you created above. In case your system does not have a python virtual environment you can easily install one using the pip command. Once you create a virtual environment then proceed to activate it as seen below.</p><pre>pip3 install virtualenv</pre><pre>~/multistep-tutorial$virtualenv env</pre><pre>~/multistep-tutorial$source env/bin/activate</pre><p>3. Once the virtual environment is activated, install the necessary libraries required for our tutorial. We will need django-formtools.</p><pre>(env)~/multistep-tutorial$pip install Django<br>(env)~/multistep-tutorial$pip install django-formtools<br>(env)~/multistep-tutorial$pip install django-crispy-forms</pre><p>4. Create a Django project and a Django app.</p><pre>(env)~/multistep-tutorial$django-admin startproject multisteproject</pre><pre>(env)~/multistep-tutorial$ cd multisteproject</pre><pre>(env)~/multistep-tutorial$python manage.py startapp multistepapp</pre><p>5. Open settings.py and include the apps we installed in step 3 under installed_apps.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;crispy_forms&#39;,<br>    &#39;formtools&#39;,<br>    &#39;multistepapp&#39;,<br>]</pre><p>6. Now we create our models for the application in models.py inside the multistepapp folder. Quick explanation, the Appl model represents our applicant’s details then the academic history is represented by the academic Institution model which has a foreign key to the Appl model. What this implies is a single applicant can have many institutions ie primary, high school, and university. Hence the many2one relationship.</p><pre>Models.py</pre><pre>class Appl(models.Model):<br>   name = models.CharField(max_length=100)<br>   age = models.IntegerField(default=1)</pre><pre>class AcademicInstitution(models.Model):<br>   institution = models.CharField(max_length=100)<br>   date_from = models.DateField()<br>   date_to = models.DateField()<br>   achievements = models.FileField(upload_to=&#39;media/%Y/%m/%d&#39;)<br>   appl=models.ForeignKey(Appl,on_delete=models.CASCADE,null=True)</pre><p>7. Next let us create our forms. Under multistepapp folder create a forms.py file and input the code below. What we are doing is creating the backend to handle forms for the application. Remember this is where you can enter any extra validation ie the type of files to accept for the academic institutions. We use Django inline formset factory to allow the applicant to enter any number of institutions. For a deeper explanation on Django formsets, refer to: <a href="https://docs.djangoproject.com/en/3.1/topics/forms/formsets/">https://docs.djangoproject.com/en/3.1/topics/forms/formsets/</a>forms.py</p><pre>from django import forms<br>from multistepapp.models import Appl,AcademicInstitution<br>from django.forms.models import BaseInlineFormSet, inlineformset_factory<br>from django.forms import modelformset_factory</pre><pre>class ApplicantDetailsForm(forms.ModelForm):<br>   class Meta:<br>     model = Appl<br>     fields = (&#39;name&#39;,&#39;age&#39;)</pre><pre>class AcademicQualificationForm(forms.ModelForm):<br>   institution = forms.CharField(max_length=100,<br>                 label=&#39;Name of     institution&#39;,<br>                 widget=forms.TextInput(<br>                       attrs={&#39;class&#39;: &quot;form-  control&quot;}))</pre><pre>   date_from = forms.DateField(<br>               widget=forms.TextInput(<br>               attrs={&#39;type&#39;:&#39;date&#39;}))</pre><pre>   date_to = forms.DateField(<br>               widget=forms.TextInput(<br>               attrs={&#39;type&#39;:&#39;date&#39;}))</pre><pre>   achievements = forms.FileField(<br>                  label=&#39;Upload Certificate/achievements awarded&#39;,<br>                  help_text=&#39;max. 42 megabytes&#39;)</pre><pre>   class Meta:<br>     model = AcademicInstitution<br>     fields =(&#39;institution&#39;,&#39;date_from&#39;,&#39;date_to&#39;,&#39;achievements&#39;)</pre><pre>AcademicQualificationFormSet = inlineformset_factory(Member,AcademicInstitution,form=AcademicQualificationForm,fields=[&#39;institution&#39;,&#39;date_from&#39;,&#39;date_to&#39;,&#39;achievements&#39;],extra=1,can_delete=True)</pre><p>8. And now finally to the meat of this tutorial, we head to the views.py still under multistepapp folder. A quick one, django-formtools has a weird bug that while in the documentation they say it supports formsets as part of the formlists, there is hardly any documentation, practically when I tried to get all the fields in the formsets I only managed to get the first and last forms in the formset ie If you enter multiple institutions more than two say primary school, high school, and university to use my analogy, you get only the fields entered in primary and university. This caused me several sleepless nights not to mention how to pass file field across sessions as that is what django-formtools supports to get the eventual files entered when the user completes all the forms. This is my hack for the problems listed above so feel free to chat me up on a better explanation. Onward Forward.</p><pre>views.py</pre><pre>from django.shortcuts import render</pre><pre># Create your views here.<br>from multistepapp.forms import ApplicantDetailsForm,AcademicQualificationForm,AcademicQualificationFormSet <br>from formtools.wizard.views import SessionWizardView<br>from django.core.files.storage import FileSystemStorage</pre><pre><br>def home(request):<br>   return render(request,&quot;home.html&quot;)</pre><pre>class ApplicationWizardView(SessionWizardView):</pre><pre>file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, &#39;files&#39;))<br>    form_list = [ApplicantDetailsForm,AcademicQualificationFormSet]<br>    template_name = &quot;form.html&quot;<br>    initial_dict= initial</pre><pre>def process_step(self, form):<br>        #print(form.data)<br>        &quot;&quot;&quot;<br>        This method is used to postprocess the form data.By default,   it      <br>        returns the raw `form.data` dictionary.<br>        &quot;&quot;&quot;</pre><pre>#print(form.data)<br>        #print(self)<br>        <br>        institution = {}<br>        inst_list = []<br>        if self.steps.current == &#39;1&#39;:<br>            <br>            institution[&#39;institution&#39;] = form.data[&#39;1-0- institution&#39;]<br>            institution[&#39;date_from&#39;] = form.data[&#39;1-0-date_from&#39;]<br>            institution[&#39;date_to&#39;] = form.data[&#39;1-0-date_to&#39;]<br>            inst_list.append(institution)<br>            inst_keys = dict(form.data.lists())<br>            <br>            #Create dictionary dynamically for the other institutions incase more than two institutions are entered<br>            if inst_keys.get(&#39;1-NaN-institution&#39;) and type(inst_keys.get(&#39;1-NaN-institution&#39;)) is list:<br>                inst_list2 = []<br>                #Add institutions <br>                for i,insti in enumerate(inst_keys.get(&#39;1-NaN-institution&#39;)):<br>                    inst_i = {}<br>                    #print(i)<br>                    date_from = inst_keys[&#39;1-NaN-date_from&#39;][i]<br>                    date_to = inst_keys[&#39;1-NaN-date_to&#39;][i]<br>                    course_duration = inst_keys[&#39;1-NaN-course_duration&#39;][i]<br>                    inst_i[&#39;institution&#39;] = insti<br>                    inst_i[&#39;date_from&#39;] = date_from<br>                    inst_i[&#39;date_to&#39;] = date_to<br>                    <br>                    inst_list2.append(inst_i)<br>                    #print(inst_list2)<br>                inst_list.extend(inst_list2)<br>            #Create dictionary dynamically for the other institutions incase more than two institutions are entered<br>            if inst_keys.get(&#39;1-NaN-institution&#39;) and type(inst_keys.get(&#39;1-NaN-institution&#39;)) is not list:<br>                inst_0 = {}<br>                inst_0[&#39;institution&#39;] = form.data[&#39;1-NaN-institution&#39;]<br>                inst_0[&#39;date_from&#39;] = form.data[&#39;1-NaN-date_from&#39;]<br>                inst_0[&#39;date_to&#39;] = form.data[&#39;1-NaN-date_to&#39;]<br>                inst_0[&#39;course_duration&#39;] = form.data[&#39;1-NaN-course_duration&#39;]<br>                #inst_0[&#39;achievements&#39;] = &#39;&#39;<br>                inst_list.append(inst_0)<br>            <br>            #Add the entered information to a session object<br>            self.request.session[&#39;institution&#39;] = inst_list<br>    <br>    #Edit the function to process files <br>    def process_step_files(self, form):<br>        if self.steps.current == &#39;1&#39;:<br>            inst_list = []<br>            inst_list2 = []<br>            inst_0 = form.files[&#39;1-0-achievements&#39;]<br>            inst_keys = dict(form.files.lists())<br>            inst_list.append(inst_0)<br>            <br>            if inst_keys.get(&#39;1-NaN-achievements&#39;) and type(inst_keys.get(&#39;1-NaN-achievements&#39;)) is list:<br>                for insti in  inst_keys.get(&#39;1-NaN-achievements&#39;):<br>                    inst_list2.append(insti)<br>                   <br>                inst_list.extend(inst_list2)</pre><pre>if inst_keys.get(&#39;1-NaN-achievements&#39;) and type(inst_keys.get(&#39;1-NaN-achievements&#39;)) is not list:<br>                inst_list2.append(inst_keys.get(&#39;1-NaN-achievements&#39;))<br>                inst_list.extend(inst_list2)<br>            print(inst_list)</pre><pre>institutions = self.request.session[&#39;institution&#39;]<br>            #Use django file system storage to store the files and get the file path <br>            #which we will append to the session created in the previous function ie process_step<br>          <br>            fs = FileSystemStorage()<br>            for i, institution in enumerate(institutions):<br>                myfile = inst_list[i]<br>                filename = fs.save(myfile.name, myfile.file)<br>                print(filename)<br>                uploaded_file_url = fs.url(https://medium.com/filename)<br>                institution[&#39;achievements&#39;] = filename<br>                print(&quot;File URL &quot;,institution[&#39;achievements&#39;])<br>                <br>            self.request.session[&#39;institution&#39;] = institutions<br>    <br>    <a href="http://twitter.com/transaction">@transaction</a>.atomic<br>    def done(self, form_list,form_dict, **kwargs):<br>     form_dict2 = self.get_all_cleaned_data()<br>        print(form_dict2)</pre><pre>#Remove the default formset by django-formtools before entering the record to the db<br>     insts = form_dict2.pop(&#39;formset-1&#39;)<br>        print(&quot;Institutions,&quot;,insts)</pre><pre>#Get the institutions we implemented in the two functions above<br>        academic_institutions = self.request.session[&#39;institution&#39;]<br>        <br>        #Enter the Application details to the Appl database table<br>        application, created = Appl.objects.update_or_create(**form_dict2)<br>        print(created)</pre><pre>for institution in academic_institutions:<br>            temp_file = institution[&#39;achievements&#39;]<br>            print(type(temp_file))<br>            #print(academic_institutions)<br>            academic_institution, created =   AcademicInstitution.objects.update_or_create(**institution)<br>            academic_institution.appl = application<br>            <br>            academic_institution.save()<br>        application.save()</pre><pre>return redirect(&#39;multistepapp:home&#39;)</pre><p>The project should look like this once done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJR2trtaP4J2TzHbHQD-JA.png" /></figure><p>Check out the complete source code at my GitHub account repo:</p><p><a href="https://github.com/Maestro1/multistep-tutorial">GitHub - Maestro1/multistep-tutorial: This is a multistep tutorial I did at medium.com</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e48d1e1f89df" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/django-formtools-django-inline-formsets-with-files-tutorial-e48d1e1f89df">How to Create a Multi-step Form Using Django-Formtools and Django Inline Formsets</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tales from a novice software engineer]]></title>
            <link>https://danielkarama13.medium.com/tales-from-a-novice-software-engineer-d508756519d?source=rss-61617cf44ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d508756519d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Nerdan]]></dc:creator>
            <pubDate>Fri, 19 Jul 2019 02:58:37 GMT</pubDate>
            <atom:updated>2019-07-19T02:58:37.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Software Engineering" src="https://cdn-images-1.medium.com/max/1024/1*scPiZN6iPbVMooBnXSKUtg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It’s a bright Monday morning,you wake up do the usual morning routines before heading to work.If you are anything like me , you would be grateful for getting matching socks without tearing apart the whole house, but those little troubles are what make the world go round!</p><p>I stride into the office , greet everyone who is getting their morning dose of coffee or tea before heading to SCRUM(that’s like a short meeting where everyone gets their tasks).Personally am a tea person so I get mine and settle in.</p><p>I look at the task assigned to me from Jiira , and for a moment I have no clue how am going to go about it.Am sure most people go through this cycle whenever they feel challenged and for me my mind starts to race thinking whether this is the software problem that becomes my water loo.I immediately start thinking what if am not up for it , suppose it is beyond my abilities?I finally decide to tackle it, better to fail while trying than fail to try.It’s not like I have an option to forfeit.</p><p>I call the manufacturer of the device am supposed to interface with our web system.I get no response.I try to call the supplier who we bought the device from, its no use he thinks its an installation problem am having.Am at pains trying to explain to him what am up to.He whoever explains to me how the whole process goes , its not what I was hoping for but its a useful start.My brain goes into a spin.</p><p>In case you are wondering what task it is that is driving me nuts, and sends me to writing my first article on Medium.PS I actually took advice from my boss who said I tell him how I went about it or I write a book!Here I am guys , the first chapter:)The task is to write a web service that communicates with an ESD (tax register )device for signing invoices after a client has paid.It is required for our platform to achieve tax compliance with the regulatory authorities.</p><p>Look out for Part Two. Have yourselves a good one!If you enjoyed do share your comments.Ciao.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d508756519d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>