❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayKrishna

Effortless Git Repo Switching with a Simple Bash Function!

By: krishna
12 February 2025 at 10:36

Why I Created This Function

At first, I used an alias

alias gitdir="cd ~/Git/" (This means gitdir switches to the ~/Git/ directory, but I wanted it to switch directly to a repository.)
So, I wrote a Bash function.

Write Code to .bashrc File

The .bashrc file runs when a new terminal window is opened.
So, we need to write the function inside this file.

Code

gitrepo() {
    # Exact Match
    repoList=$(ls $HOME/Git)
    if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1
    else
	# Relevant Match
	getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"
	else
	    echo "Repository Not Founded"
	    cd $HOME/Git
	fi
	
    fi   
}

Code Explanation

The $repoList variable stores the list of directories inside the Git folder.

Function Logic Has Two Parts:

  • Exact Match
  • Relevant Match

Exact Match

if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1

If condition: The $repoList variable parses input for grep.

  • grep -w matches only whole words.
  • $1 is the function’s argument in bash.
  • -n checks if a variable is not empty. Example syntax:
    [ a != "" ] is equivalent to [ -n a ]

Relevant Match

getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"

Relevant search: If no Exact Match is found, this logic is executed next.

getRepoName="$repoList" | grep -i -m 1 $1
  • -i ignores case sensitivity.
  • -m 1 returns only the first match.

Example of -m with grep:
ls | grep i3
It returns i3WM and i3status, but -m 1 ensures only i3WM is selected.

No Match

If no match is found, it simply changes the directory to the Git folder.

	else
	    echo "Repository Not Founded"
	    cd $HOME/Git

What I Learned

  • Basics of Bash functions
  • How to use .bashrc and reload changes.

Python variable

By: krishna
7 February 2025 at 06:34

This blog explores Python variable usage and functionalities.

Store All Data Types

First, let’s list the data types supported in Python.

Python Supported Data Types

  • Primitive Data Types:
    • Integer
    • Float
    • String
    • Boolean
    • None
  • Non-Primitive Data Types:
    • List
    • Tuple
    • Set
    • Bytes and ByteArray
    • Complex
    • Class Object

Store and Experiment with All Data Types

phone = 1234567890
pi    = 3.14
name  = "python programming"
using_python   = True
example_none   = None
simple_list    = [1,2,3]
simple_dict    = {"name":"python"}
simple_set     = {1,1,1,1,1.0}
simple_tuple   = (1,2,3)
complex_number = 3+5j

print("number     = ",phone)
print("float      = ",pi)
print("boolean    = ",using_python)
print("None       = ",example_none)
print("list       = ",simple_list)
print("dictionary = ",simple_dict)
print("set        = ",simple_set)
print("tuple      = ",simple_tuple)
print("complex    = ",complex_number)

Output

number     =  1234567890
float      =  3.14
boolean    =  True
None       =  None
list       =  [1, 2, 3]
dictionary =  {'name': 'python'}
set        =  {1}
tuple      =  (1, 2, 3)
complex    =  (3+5j)

Type Function

This function is used to print the data type of a variable.

print(type(phone))
print(type(pi))
print(type(using_python))
print(type(simple_list))
print(type(simple_dict))
print(type(simple_set))
print(type(simple_tuple))
print(type(complex_number))
print(type(example_none))

Output

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'set'>
<class 'tuple'>
<class 'complex'>
<class 'NoneType'>

Bytes and ByteArray

These data types help modify large binary datasets like audio and image processing.

The memoryview() function allows modifying this data without zero-copy access to memory.

bytes is immutable, where as bytearray is mutable.

bytes

b1 = bytes([1,2,3,4])
bo = memoryview(b1)
print("byte example :",bo[0])

Output

byte example : 1

bytearray

b2 = bytearray(b"aaaa")
bo = memoryview(b2)
print("byte array :",b2)
bo[1] = 98
bo[2] = 99
bo[3] = 100
print("byte array :",b2)

Output

byte array : bytearray(b'aaaa')
byte array : bytearray(b'abcd')

Other Data Types

Frozenset

A frozenset is similar to a normal set, but it is immutable.

test_frozenset = frozenset([1,2,1])
for i in test_frozenset:
    print("frozen set item :",i)

Output

frozen set item : 1
frozen set item : 2

Range

The range data type specifies a number range (e.g., 1-10).

It is mostly used in loops and mathematical operations.

a = range(3)
print("a = ",a)
print("type = ",type(a))

Output

a =  range(0, 3)
type =  <class 'range'>

Type Casting

Type casting is converting a data type into another. Try explicit type casting to change data types.

value = 1
numbers = [1,2,3]
print("type casting int     : ",type(int(value)))
print("type casting float   : ",type(float(value)))
print("type casting string  : ",type(str(value)))
print("type casting boolean : ",type(bool("True")))
print("type casting list    : ",type(list(numbers)))
print("type casting set     : ",type(set(numbers)))
print("type casting tuple   : ",type(tuple(numbers)))

Output

type casting int     :  <class 'int'>
type casting float   :  <class 'float'>
type casting string  :  <class 'str'>
type casting boolean :  <class 'bool'>
type casting list    :  <class 'list'>
type casting set     :  <class 'set'>
type casting tuple   :  <class 'tuple'>

Delete Variable

Delete an existing variable using Python’s del keyword.

temp = 1
print("temp variable is : ",temp)
del temp
# print(temp)  => throw NameError : temp not defined

Output

temp variable is :  1

Find Variable Memory Address

Use the id() function to find the memory address of a variable.

temp = "hi"
print("address of temp variable : ",id(temp))

Output

address of temp variable :  140710894284672

Constants

Python does not have a direct keyword for constants, but namedtuple can be used to create constants.

from collections import namedtuple
const = namedtuple("const",["PI"])
math = const(3.14)

print("namedtuple PI = ",math.PI)
print("namedtuple type =",type(math))

Output

namedtuple PI =  3.14
namedtuple type = <class '__main__.const'>

Global Keyword

Before understanding global keyword, understand function-scoped variables.

  • Function inside variable are stored in stack memory.
  • A function cannot modify an outside (global) variable directly, but it can access it.
  • To create a reference to a global variable inside a function, use the global keyword.
message = "Hi"
def dummy():
    global message 
    message = message+" all"

dummy()
print(message)

Output

Hi all

Explicit Type Hint

Type hints are mostly used in function parameters and arguments.

They improve code readability and help developers understand variable types.

-> float : It indicates the return data type.

def area_of_circle(radius :float) -> float:
    PI :float = 3.14
    return PI * (radius * radius)

print("calculate area of circle = ",area_of_circle(2))

Output

calculate area of circle =  12.56

Learn REST-API

By: krishna
5 February 2025 at 06:01

REST API

A REST API (Representational State Transfer) is a web service that allows different applications to communicate over the internet using standard HTTP methods like GET, POST, PUT, and DELETE. It follows REST principles, making it lightweight, scalable, and easy to use.

REST API Principles

Client-Server Architecture

A REST API follows a client-server architecture, where the client and server are separate. The client sends requests, and the server processes them and responds, allowing different clients like web and mobile apps to communicate with the same backend.

Statelessness

Before understanding statelessness, you need to understand statefulness.

  • Statefulness: The server stores and manages user session data, such as authentication details and recent activities.
  • Statelessness: The server does not store any information. Each request is independent, and the client must include all necessary data, like authentication details and query parameters, in every request.

This behavior makes the server scalable, reliable, and reduces server load.

Caching

Caching improves performance by storing responses that can be reused, reducing the need for repeated requests to the server. This minimizes response time and server load.

Uniform Interface

A uniform interface ensures consistency by using standard HTTP methods like GET, POST, PUT, and DELETE. This makes the API predictable and easy to use.

Layered System

A layered system divides tasks into separate layers, like security, caching, and user requests. The client only interacts with the top layer, making the system easier to manage and more flexible.

Start To Code

I use Node.js and some popular packages:

  • Express: A Node.js web framework used for building web applications and APIs.
  • Joi: A package used to validate user input, ensuring data integrity and security.

basic code

const express = require("express");
const app = express();
const joi = require("joi");
app.use(express.json());

//data
customers = [
    {name : "user1", id : 1},
    {name : "user2", id : 2},
    {name : "user3", id : 3}
]

//listen
const port = process.env.PORT || 8080;
app.listen(port, ()=> console.log("listening on ",port));

//function
function validateUserName(customer){
    schema = joi.object({
	name : joi.string().min(3).required()
    });
    return schema.validate(customer)
}

GET

GET is used to retrieve data from the server. the response code is 200 if successful.

app.get('/api/customers',(req,res)=>{
    res.send(customers);
});

get specific user details

app.get('/api/customer/:id', (req,res)=>{
    const user_details = customers.find(user => req.params.id == user.id );
    if(!user_details){
        res.status(404).send("Data Not Found");
    }else{
        res.status(200).send(user_details)
    }
});

POST

The POST method is used to upload data to the server. The response code is 201, and I used the validateUserName function to validate a username.

app.post('/api/customer/add',(req, res)=>{
    const {error} = validateUserName(req.body);
    if(error){	
	res.status(400).send(error.details[0].message);
    }
    else{
	customer = {
	    name : req.body.name,
	    id   : customers.length + 1
	}
	customers.push(customer);
	res.status(201).send("data inserted successfully");
    }
});

 

PATCH

The PATCH method is used to update existing data partially. To update the entire user data, the PUT method should be used.

app.patch('/api/customer/:id', (req, res)=>{
    const customer = customers.find(user => user.id == req.params.id);
    const {error} = validateUserName(req.body);
    if(!customer){
	res.status(404).send("Data Not Found");
    }
    else if(error){
	console.log(error)
	res.status(400).send(error.details[0].message);
    }
    else{
	customer.name = req.body.name;
	res.status(200).send("successfully updated");
    }
});

 

DELETE

The DELETE method is used to remove user data.

app.delete('/api/customer/:id', (req,res)=>{
    const user = customers.find(user => user.id == req.params.id);
    index = customers.indexOf(user);
    if(!user){
	console.log("test")
	res.status(404).send("Data Not Found");
    }
    else{
	customers.splice(index,1);
	res.status(200).send("successfully deleted");
    }
});

 

What I Learned

CRUD Operations with REST API

I learned the basics of REST API and CRUD operations, including the uniform methods GET, POST, PUT, PATCH, and DELETE.

Status Codes

REST APIs strictly follow status codes:

  • 200 – OK
  • 201 – Created successfully
  • 400 – Bad request
  • 204 – No content
  • 404 – Page not found

Joi Package

For server-side validation, the Joi package is used. It helps verify user data easily.

Middleware

Using app.use(express.json()) as middleware ensures that for POST, PATCH, and PUT methods, JSON-formatted user data is parsed into an object accessible via req.body.

 

Minimal Typing Practice Application in Python

By: krishna
30 January 2025 at 09:40

Introduction

This is a Python-based single-file application designed for typing practice. It provides a simple interface to improve typing accuracy and speed. Over time, this minimal program has gradually increased my typing skill.

What I Learned from This Project

  • 2D Array Validation
    I first simply used a 1D array to store user input, but I noticed some issues. After implementing a 2D array, I understood why the 2D array was more appropriate for handling user inputs.
  • Tkinter
    I wanted to visually see and update correct, wrong, and incomplete typing inputs, but I didn’t know how to implement it in the terminal. So, I used a simple Tkinter gui window

Run This Program

It depends on the following applications:

  • Python 3
  • python3-tk

Installation Command on Debian-Based Systems

sudo apt install python3 python3-tk

Clone repository and run program

git clone https://github.com/github-CS-krishna/TerminalTyping
cd TerminalTyping
python3 terminalType.py

Links

For more details, refer to the README documentation on GitHub.

This will help you understand how to use it.

source code(github)

Build a Product Rental App in Node.js

By: krishna
29 January 2025 at 10:47

Introduction

I created a website called Vinmeen that allows users to rent products for temporary needs at a low cost. The goal was to design a simple UI for users to easily rent things they need temporarily.

Technologies Used

  • Node.js & Express
  • Node Packages
    • Express
    • EJS
    • Nodemailer
    • Bcrypt
    • Multer
    • Sync-SQL
    • MySQL
  • MySQL

What I Learned from This Project

This project helped me understand how dynamic websites work and how template rendering is done. I used EJS for rendering templates, MySQL for database handling, and Bcrypt for securely storing user passwords through hashing. I also learned how to send email notifications with OTP and rent requests, among other things.

Hosting

I hosted the site using two different services

Website Hosting – Render.com

Render provides free hosting for experimentation and student projects. This plan has minimal resources, but it’s great for learning and testing.

MySQL Database – Filess.io:

Files.io offers a free MySQL database with a 10MB size limit and a maximum of 5 concurrent connections. It’s ideal for students and self-study projects, but not recommended for startups or businesses.

Links

❌
❌