Dought Flow

React Child data transfer to Parent

Parent Comonent
javascript
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [dataFromChild, setDataFromChild] = useState(null);

  const handleDataFromChild = (data) => {
    setDataFromChild(data);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <p>Data from Child: {dataFromChild}</p>
      <ChildComponent sendDataToParent={handleDataFromChild} />
    </div>
  );
};

export default ParentComponent;
Child Component
javascript
import React from 'react';

const ChildComponent = ({ sendDataToParent }) => {
  const sendData = () => {
    const data = 'Hello from Child';
    sendDataToParent(data);
  };

  return (
    <div>
      <h2>Child Component</h2>
      <button onClick={sendData}>Send Data to Parent</button>
    </div>
  );
};

export default ChildComponent;
.env FILE

.env FILE

Some common problems with "dot env files"

16-bit encoding

  • Some times the ".env" file is not able to recognize, by the React/Node Applications.
  • This may be due to the encoding is 16-bit
  • In this case delete the ".env" file , and create a new file in file Explorer as file.txt
  • come to VS Code and rename the file to .env

Restarting the development Server

  • If still the issue persists, close the terminal .
  • Restart the development server, by running the command npm start
  • every time you add new env variable you have to do this .

React "Child data transfer to Parent"

Parent Comonent
javascript
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [dataFromChild, setDataFromChild] = useState(null);

  const handleDataFromChild = (data) => {
    setDataFromChild(data);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <p>Data from Child: {dataFromChild}</p>
      <ChildComponent sendDataToParent={handleDataFromChild} />
    </div>
  );
};

export default ParentComponent;
Child Component
javascript
import React from 'react';

const ChildComponent = ({ sendDataToParent }) => {
  const sendData = () => {
    const data = 'Hello from Child';
    sendDataToParent(data);
  };

  return (
    <div>
      <h2>Child Component</h2>
      <button onClick={sendData}>Send Data to Parent</button>
    </div>
  );
};

export default ChildComponent;

"Scroll bar" changes in HTML and React

code
/* Target the scrollbar */
::-webkit-scrollbar {
  width: 8px;  /* Width for vertical scrollbars */
  height: 8px; /* Height for horizontal scrollbars */
}

/* Track (the background of the scrollbar) */
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

/* Handle (the draggable part of the scrollbar) */
::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 10px;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: #555;
}
Creating Ubuntu machine on AWS

Creating Ubuntu machine on AWS

go to AWS and search for EC2

Click on launch Instance

Creation of Virtual machine
  1. give a name to VM. You may give any name , at the console this is the name you identify.
  2. Select OS type as Ubuntu .
  3. Choose t2.micro (or) t3.micro[for large server]
  4. create a new key pair .
  5. This key pair will be used for login to VM from your local machine.
  6. Note : This key pair will not be stored any where else, keep it safe.
  7. any one with this key pair can handle entire VM , so be aware.
  8. Click on Allow HTTP traffic from the internet
  9. Click on Allow HTTPS traffic from the internet
  10. Final step :- Click on launch instance to create VM.

  • now your AWS Ubuntu VM is ready to use.
  • this is same as a local machine
  • you can host any kind of applications.
  • For hosting and other services
  • Download necessary libraries and packages.
  • get the code from gitHub repository by cloning
  • move to that directory, and make what you want .

Danger zone
code
-> make sure you terminate the instance after you feel its use is completed.

-> other wise you may be charged additionally.

-> you may even suspend the VM , and later you can resume it.
Running a server on Ubuntu machine on AWS

Running a server on Ubuntu machine on AWS

pre requisites
  1. A Ubuntu/Linux Virtual machine , preferebly "Ubuntu".
  2. first login as root user

code
sudo su -

for any kind of server Git is important , install it.

code
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

install NVM (Node Version Manager)

code
. ~/.nvm/nvm.sh

to check weather node is installed or not , you may run below commands.

code
node -v
npm -v

run below command to install and update git ecosystem

code
sudo apt-get update -y
sudo apt-get install git -y

to check weather git is installed or not

code
git — version

get the code from gitHub to local VM

code
git clone remote_url_link

"example remote_url_link :-"

https://github.com/goutham469/nss.git

  1. Now the code is on our VM.
  2. By default main branch of repository is loaded to current working directory.
  3. you may change it by

code
git checkout branch_name
  • for security reasons : you may create a .env file here and add varaible here.
  • run respective commands , for your application
  • for Node

code
node server.js

Progress Bar

Simple and beautiful notification Bar
Post content
javascript
import React, { useEffect, useState } from 'react';
import { IoClose } from 'react-icons/io5'; // Import the close icon
import './ProgressBar.css';

export default function Notification({ message, color, duration = 3000, onClose }) {
    const [visible, setVisible] = useState(true);
    const [progress, setProgress] = useState(100); // Progress starts at 100%

    useEffect(() => {
        // Interval to update the progress bar
        const interval = setInterval(() => {
            setProgress((prev) => (prev > 0 ? prev - 100 / (duration / 100) : 0));
        }, 100);

        // Timeout to hide the notification after the given duration
        const timer = setTimeout(() => {
            setVisible(false);
            if (onClose) onClose(); // Call onClose callback when the notification disappears
        }, duration);

        // Cleanup intervals and timeout on unmount
        return () => {
            clearTimeout(timer);
            clearInterval(interval);
        };
    }, [duration, onClose]);

    if (!visible) return null; // Return null if the notification is no longer visible

    return (
        <div className="notification-popup" style={{ backgroundColor: color }}>
            <div className="notification-content">
                {message}
                <IoClose
                    className="close-icon"
                    onClick={() => {
                        setVisible(false);
                        if (onClose) onClose(); // Handle immediate close
                    }}
                />
            </div>
            <div className="progress-bar" style={{ width: `${progress}%`, backgroundColor: 'white' }} />
        </div>
    );
}
use case
javascript
const [notification, setNotification] = useState(null);

{notification && (
    <Notification 
        message={notification.message} 
        color={notification.color}
        onClose={() => setNotification(null)} 
    />
)}

setNotification({ message: 'Code copied to clipboard', color: 'green' });

middle part i.e rendring part to be kept at bottom of any Component

You may also use "setTimeout()" , to strictly allow the notification bar .

This kind of approach is useful when dealing with navigate() .

code
if (output.acknowledged) {
    setNotification({ message: 'Post published', color: 'green' });

    // Delay navigate() by 5 seconds (5000 milliseconds)
    setTimeout(() => {
        navigate('/');
    }, 5000);
}

tags test

sample tags test
JavaScriptSQLPythonMachine LearningDevelopment

Drag and Drop , in react

javascript
import React, { useState } from 'react';
import './DragDrop.css';

const availableTags = ['HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'MongoDB', 'Python', 'Java', 'SQL', 'Machine Learning', 'Development', 'AWS', 'GCP'];

const TechTags = ({ handler }) => {
  const [selectedTags, setSelectedTags] = useState([]);
  const [draggedTag, setDraggedTag] = useState(null);

  const handleDragStart = (tag) => {
    setDraggedTag(tag);
  };

  const handleDropAvailable = () => {
    if (draggedTag) {
      const updatedTags = selectedTags.filter((tag) => tag !== draggedTag); // Remove tag from selected
      setSelectedTags(updatedTags);
      setDraggedTag(null);

      handler(updatedTags); // Pass the updated list to the handler
    }
  };

  const handleDropSelected = () => {
    if (draggedTag && !selectedTags.includes(draggedTag)) {
      const updatedTags = [...selectedTags, draggedTag]; // Add tag to selected
      setSelectedTags(updatedTags);
      setDraggedTag(null);
      
      handler(updatedTags); // Pass the updated list to the handler
    }
  };

  return (
    <div className="tech-tags-container">
      <div className="tags-list">
        <h3>Available Tags</h3>
        <div className="available-tags" onDrop={handleDropAvailable} onDragOver={(e) => e.preventDefault()}>
          {availableTags.filter(tag => !selectedTags.includes(tag)).map((tag) => (
            <div
              key={tag}
              className="tag"
              draggable
              onDragStart={() => handleDragStart(tag)}
            >
              {tag}
            </div>
          ))}
        </div>
      </div>

      <div className="tags-list">
        <h3>Selected Tags</h3>
        <div className="selected-tags" onDrop={handleDropSelected} onDragOver={(e) => e.preventDefault()}>
          {selectedTags.map((tag) => (
            <div
              key={tag}
              className="tag"
              draggable
              onDragStart={() => handleDragStart(tag)}
            >
              {tag}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default TechTags;
DevelopmentReact

Netlify redirects issue , toml file

we can avoid page url malformed issue , using "netlify.toml" file
code
[[redirects]]
from = "/*"
to = "/index.html"
status = 200

Save the above file with netlify.toml extension .

In the root directory of React application .

ReactDevelopment
Dark mode and light mode

Dark mode and light mode

Simply switch b/w dark and light mode .

Place the below code snippet in "index.css" of root directory .

code
:root {
  --background-color: #ffffff; /* Light mode */
  --text-color: #000000;
  --primary-color: #007bff;
  --background-color-primary:#cccccc;
  /* Add other variables as needed */
}

[data-theme="dark"] {
  --background-color: #000000; /* Dark mode */
  --background-color-primary:#252525;
  --text-color: #ffffff;
  --primary-color: #1e90ff;
}

place the below code at the toggling component .

code
<span className='toggle-theme-icon profile-button'>
            {
                theme ?
                theme === "light" ? 
              <IoMoonOutline onClick={()=>toggleTheme("dark")} />
              :
              <IoSunnyOutline onClick={()=>toggleTheme("light")} />
              :
              <IoMoonOutline onClick={()=>toggleTheme("light")} />
            }
          </span>

Toggle handler function

javascript
function toggleTheme(cur_theme) 
{

    const currentTheme = document.documentElement.getAttribute("data-theme");
    const newTheme = cur_theme
    document.documentElement.setAttribute("data-theme", newTheme);
    
    localStorage.setItem("theme", newTheme);
    setTheme(newTheme);
  }
CSSReactHTML
Web scrapping using Python.

Web scrapping using Python.

Web scrapping using BeautifulSoup
python
import requests,json
from bs4 import BeautifulSoup

def search(url) :
    HEADERS = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Encoding': 'gzip, deflate, br',
                }
    response = requests.get(url , headers = HEADERS)

    # Check if the correct encoding is detected
    if response.encoding is None:
        response.encoding = 'utf-8'
    
    soup = BeautifulSoup(response.text, 'html.parser')

    imagesData = [img['src'] for img in soup.find_all('img') if 'src' in img.attrs]

    output = []
    for index, img_url in enumerate(imagesData):
        # Handle relative URLs by converting them to absolute URLs
        if not img_url.startswith("http"):
            img_url = requests.compat.urljoin(url, img_url)

        output.append(img_url)

    return output


url = "https://www.flaticon.com/search?word=mail"
data = search(url)

json_data = json.dumps(data, indent=4)

with open("sample.json" , "w") as file :
    file.write(json_data)

print(json_data)

Above code will fetch the url and output the data Images in the form of .json file .

PythonDevelopment
Google SEO .

Google SEO .

Improve Google page rankings
Format the index.html file in public folder.
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

    

    <meta name="google-site-verification" content="iFfz-4GCNVcB7Vp6IQ5MZXeCoCTbJBzzc_uq94KxMHg" />
    <meta name="description" content="a application for postiong solutions for doughts in tech .">
    <meta name="keywords" content="doughtflow , dought , dought flow , doughtnet ,Goutham, Goutham469, Goutham Reddy,Uppunuri Goutham Reddy, developer, JavaScript, full-stack, MERN, React">


    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Stackoverflow stack overflow goutham gouthamreddy dought"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>Dought Flow</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>
Important Changes (3) .
code
<meta name="google-site-verification" content="iFfz-4GCNVcB7Vp6IQ5MZXeCoCTbJBzzc_uq94KxMHg" />
    <meta name="description" content="a application for postiong solutions for doughts in tech .">
    <meta name="keywords" content="doughtflow , dought , dought flow , doughtnet ,Goutham, Goutham469, Goutham Reddy,Uppunuri Goutham Reddy, developer, JavaScript, full-stack, MERN, React">

Here the "description" meta , tag shows the highlighting content .

Post content

And "keywords" meta tag is responsible for , search results .

Choose the words those not exists on Google Search engine .

code
For doing all this google-site-verification is mandatory .
and this is first process
ReactGCPDevelopment
API traffic monitor System .

API traffic monitor System .

Monitor the API traffic for your site

This is a simple approach

  1. Create a Middleware named "APICounter.js"
  2. paste the code below
  3. use this middleware at root level
  4. app.use(APICounter)

javascript
function getClientIP(req) {
    let xForwardedFor = req.headers['x-forwarded-for'];
    
    if (xForwardedFor) {
        let ipList = xForwardedFor.split(',');
        return ipList[0].trim(); 
    } else {
        return req.connection.remoteAddress;
    }
}

const APICounter = async (req, res, next) => {
    let userIPAddress = getClientIP(req)


    if (req.metaCollection) {
        await req.metaCollection.updateOne({ id: 1 }, { $inc: { apiCalls: 1 } });

        let data = await req.metaCollection.findOne({ id: 1 });
        data = data.api;

        // IP Address update
        let status = false;
        for (const [idx, obj] of data.ipAdrs.entries()) {
            if (obj.ip === userIPAddress) {
                data.ipAdrs[idx].views += 1;
                status = true;
                break; // Exit the loop once IP is found and updated
            }
        }
        if (!status) {
            let userIP = userIPAddress;
            data.ipAdrs.push({ ip: userIP, views: 1 });
        }

        // Day update
        let today = new Date().getDate() + "/" + new Date().getMonth() + '/' + new Date().getFullYear();
        status = false;
        for (const [idx, obj] of data.stats.daily.entries()) {
            if (obj.date === today) {
                data.stats.daily[idx].views += 1;
                status = true;
                break; // Exit the loop once the date is found and updated
            }
        }
        if (!status) {
            data.stats.daily.push({ date: today, views: 1 });
        }

        // Month update
        let month = new Date().getMonth() + '/' + new Date().getFullYear();
        status = false;
        for (const [idx, obj] of data.stats.monthly.entries()) {
            if (obj.month === month) {
                data.stats.monthly[idx].views += 1;
                status = true;
                break; // Exit the loop once the month is found and updated
            }
        }
        if (!status) {
            data.stats.monthly.push({ month: month, views: 1 });
        }

        await req.metaCollection.updateOne({ id: 1 }, { $set: { api: data } });
    }

    next()
}

module.exports = APICounter;
Database requirement

Sample meta Collection .

code
{
  "_id": "67149c31cba7f0093b115429",
  "id": 1,
  "apiCalls": 836,
  "websiteCalls": 0,
  "counter": "100e",
  "website": {
    "ipAdrs": [],
    "stats": {
      "daily": [],
      "monthly": []
    }
  },
  "api": {
    "ipAdrs": [
      {
        "ip": "35.233.167.61",
        "views": 1
      },
      {
        "ip": "103.248.208.101",
        "views": 104
      }
    ],
    "stats": {
      "daily": [
        {
          "date": "20/9/2024",
          "views": 143
        },
        {
          "date": "21/9/2024",
          "views": 507
        },
        {
          "date": "22/9/2024",
          "views": 180
        }
      ],
      "monthly": [
        {
          "month": "9/2024",
          "views": 830
        }
      ]
    },
    "apiCalls": 5
  }
}
Node.jsMongoDBDevelopment
MongoDB connection , with node.js

MongoDB connection , with node.js

javascript
const mclient = require("mongodb").MongoClient


mclient.connect(process.env.MONGODB_URL).then(client => {
    const db = client.db('mailer')

    const usersCollection = db.collection("users")
    const metaCollection = db.collection("meta")
    const mailsCollection = db.collection("mails")

    app.set("usersCollection" , usersCollection)
    app.set("metaCollection" , metaCollection)
    app.set("mailsCollection" , mailsCollection)

    console.log("mongoDB connection success !")
}).catch(err=>{
    console.log("Problem at connection with mongoDB .")
    console.log(err)
})

dependencies :-

code
npm i mongodb dotenv express
Node.jsMongoDB

Single Login route .

single route for login and signup .
javascript
usersAPI.post('/login' , async (req,res)=>{
    let response = await req.usersCollection.find({email:req.body.email}).toArray()
    if(response.length > 0)
    {
       res.send({status:true , message:"login success"})
    }
    else
    {
       response = await req.usersCollection.insertOne({"email":req.body.email,"img":req.body.img})
       res.send(response)
    }
})
Node.jsMongoDB
AWS Lambda deploy.

AWS Lambda deploy.

Install serverless framework
code
npm install -g serverless
create serverless.yml file
code
org: goutham469
app: my-express-app
service: nodejs-doughtflow-server

provider:
  name: aws
  runtime: nodejs18.x
  region: ap-south-1  # Mumbai region (ap-south-1)

functions:
  app:
    handler: dist/app.handler
    memorySize: 128  # Memory size (128MB)
    events:
      - http: ANY /
      - http: ANY /{proxy+}

Here, service : nodejs-douaghtflow-server

this service name should be unique.

By default this on this service name all your lambda function setup will be created.

Some common problems :-
  1. DB is not being setup properly.

to handle DB configuration issues.

Use try catch blocks , and send the responses with the error.

javascript
postsAPI.get('/all-posts',async(req,res)=>{
    console.log("\n\nall posts called .\n\n")

    try
    {
        if(!req.postsCollection)
        {
            let response = await req.app.get('postsCollection').find().toArray()
            // console.log(response[0])
            res.send(response)
        }
        else
        {
            let response = await req.postsCollection.find().toArray()
            // console.log(response[0])
            res.send(response)
        }
        
    }
    catch(err)
    {
        console.log(err)
        res.send({message:"an error occured.",success:false,error:true,errorMessage:err.message})
    }
})
MongoDB connection undefined error.

-> To address this issue use Promises.

javascript
let mongoClientPromise = MongoClient.connect(process.env.MONGO_DB_URL)
    .then(client => {
        const DB = client.db('doughtflow');
        const usersCollection = DB.collection('users');
        const postsCollection = DB.collection('posts');
        const metaCollection = DB.collection('meta');

        app.set('usersCollection', usersCollection);
        app.set('postsCollection', postsCollection);
        app.set('metaCollection', metaCollection);

        isMongoConnected = true;
        console.log("MongoDB connection successful");
    })
    .catch(err => {
        console.error("MongoDB connection failed:", err);
        process.exit(1); // Exit process on failure
    });

// Middleware to wait for MongoDB connection
app.use(async (req, res, next) => {
    if (!isMongoConnected) {
        try {
            await mongoClientPromise; // Wait for the MongoDB connection
            next(); // Proceed if connected
        } catch (err) {
            return res.status(500).send({ message: "MongoDB not connected yet" });
        }
    } else {
        next();
    }
});
AWSNode.jsDevelopment

curl

code
C:\Users\gouth>curl --help
Usage: curl [options...] <url>
 -d, --data <data>           HTTP POST data
 -f, --fail                  Fail fast with no output on HTTP errors
 -h, --help <category>       Get help for commands
 -i, --include               Include response headers in output
 -o, --output <file>         Write to file instead of stdout
 -O, --remote-name           Write output to file named as remote file
 -s, --silent                Silent mode
 -T, --upload-file <file>    Transfer local FILE to destination
 -u, --user <user:password>  Server user and password
 -A, --user-agent <name>     Send User-Agent <name> to server
 -v, --verbose               Make the operation more talkative
 -V, --version               Show version number and quit

This is not the full help; this menu is split into categories.
Use "--help category" to get an overview of all categories, which are:
auth, connection, curl, deprecated, dns, file, ftp, global, http, imap, ldap, output, pop3, post, proxy, scp, sftp,
smtp, ssh, telnet, tftp, timeout, tls, upload, verbose.
For all options use the manual or "--help all".
code
curl https://google.com

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">

<TITLE>302 Moved</TITLE></HEAD><BODY>

<H1>302 Moved</H1>

The document has moved

<A HREF="https://www.google.com/sorry/index?continue=https://google.com/&amp;q=EgRn-NBmGK7et7oGIikhZT-oMPd8rSVO7bVhQnuKXFk1hRZSsofbiBRzVMcZJ67cul7iXx68ITIBcloBQw">here</A>.

</BODY></HTML>

OracleDB 21C XE , Connection with Python.

python
import oracledb

# Connect to the Oracle Database
try:
    connection = oracledb.connect(
        user="system",
        password="root",
        dsn="localhost:1521/XE"
    )
    
    # Create a cursor to interact with the database
    cursor = connection.cursor()

    # Execute a sample query
    cursor.execute("SELECT * FROM students")
    tables = cursor.fetchall()

    print("Tables in the current schema:")
    for table in tables:
        print(list(table))

    # Close the cursor and connection
    cursor.close()
    connection.close()

except oracledb.DatabaseError as e:
    print(f"An error occurred: {e}")

above is code for simple Connection with DataBase

-> write operation

python
import requests
import oracledb

def getData():
    # Fetch data from placeholder API
    response = requests.get('https://jsonplaceholder.typicode.com/posts')
    data = response.json()
    
    # Extract relevant data (id, title, body)
    data = [ (post['id'], post['title'], post['body']) for post in data[:20] ]
    
    return data

def write(data):
    try:
        # Establish a connection to the Oracle Database
        with oracledb.connect(user="system", password="root", dsn="localhost:1521/XE") as connection:
            with connection.cursor() as cursor:
                # Insert data into the table using parameter binding
                insert_stmt = "INSERT INTO posts (id, title, body) VALUES (:1, :2, :3)"
                
                for post in data:
                    cursor.execute(insert_stmt, post)

                # Commit the transaction
                connection.commit()

    except oracledb.DatabaseError as e:
        print(f"An error occurred: {e}")

# Get data from the API
data = getData()

# Write the data to the Oracle database
write(data)
PythonSQL

Footer

Simple footer

javascript
import React from "react";
import './Footer.css'
import logoIcon from '../assets/logo.png'
import { FaWhatsapp } from "react-icons/fa6";
import Version from "./Version";

export const Client_URL = import.meta.env.VITE_CLIENT_URL;

const Footer = () => {

  const handleWhatsAppRedirect = () => {
    const phoneNumber = '918977300290';
    const message = 'Hello, I would like to know more about your services.';
    const encodedMessage = encodeURIComponent(message);
    window.open(`https://wa.me/${phoneNumber}?text=${encodedMessage}` , "_blank")
  }; 

  

  return (
    <footer class="footer">
        <div class="footer-top section">
            <div class="container">
 

                <div class="footer-link-box">

                    <ul class="footer-list">

                        <li>
                            <p class="footer-list-title">Contact Us</p>
                        </li>

                        <li>
                            <address class="footer-link">
                    <ion-icon name="location"></ion-icon>

                    <span class="footer-link-text">
                        Hyderabad,Telangana,INDIA
                    </span>
                  </address>
                        </li>

                        <li>
                            <a href="tel:+918977300290" target="_blank" class="footer-link">
                                <ion-icon name="call"></ion-icon>

                                <span class="footer-link-text">+91 89773 00290</span>
                            </a>
                        </li>

                        <li>
                            <a href="mailto:attellisanjaykumar29@gmail.com" target="_blank" class="footer-link">
                                <ion-icon name="mail"></ion-icon>

                                <span class="footer-link-text">editwithsanjay@gmail.com</span>
                            </a>
                        </li>

                    </ul>

                    <ul class="footer-list">

                        <li>
                            <p class="footer-list-title">My Account</p>
                        </li>

                        <li>
                            <a href={`${Client_URL}/dashboard/profile`}  class="footer-link">
                                <ion-icon name="chevron-forward-outline"></ion-icon>

                                <span class="footer-link-text">My Account</span>
                            </a>
                        </li>

                        <li>
                            <a  href={`${Client_URL}/checkout`} class="footer-link">
                                <ion-icon name="chevron-forward-outline"></ion-icon>

                                <span class="footer-link-text">View Cart</span>
                            </a>
                        </li>

                        <li>
                            <a href={`${Client_URL}/dashboard/myorders`}    class="footer-link">
                                <ion-icon name="chevron-forward-outline"></ion-icon>

                                <span class="footer-link-text">My Orders</span>
                            </a>
                        </li>


                        <li>
                            <a href="#" class="footer-link">
                                <ion-icon name="chevron-forward-outline"></ion-icon>

                                <span class="footer-link-text">New Products</span>
                            </a>
                        </li>

                    </ul>

                    <div class="footer-list">

                        <p class="footer-list-title">Categories</p>

                        <table class="footer-table">
                            <tbody>
                                <li>
                                    <a href={`${Client_URL}/After-Effects-Template's--67365c078c2f3f39f73e2cac/CINEMATIC-TITLE'S-6737a6d76a02825477b37d3b`} target="_blank" class="footer-link">
                                        <ion-icon name="chevron-forward-outline"></ion-icon>

                                        <span class="footer-link-text">After Effects</span>
                                    </a>
                                </li>

                                <li>
                                    <a href={`${Client_URL}/Premiere-Pro-Templates-673b6ce9af2ab53e052de8f6/CHANNEL-INTRO'S-673b6db1af2ab53e052de90c`} target="_blank" class="footer-link">
                                        <ion-icon name="chevron-forward-outline"></ion-icon>

                                        <span class="footer-link-text">Premiere Pro</span>
                                    </a>
                                </li>
                                <li>
                                    <a href={`${Client_URL}/Photoshop-Templates-67365d008c2f3f39f73e2d02/GAMING-THUMBNAIL'S-67371075f28bba4b5ad08e4f`} target="_blank"   class="footer-link">
                                        <ion-icon name="chevron-forward-outline"></ion-icon>

                                        <span class="footer-link-text">Photoshop</span>
                                    </a>
                                </li>

                                <li>
                                    <a href={`${Client_URL}/Davinci-Resolve-Templates-6737a49d6a02825477b37c64/CINEMATIC-TITLE'S-6737a4ad6a02825477b37c69`} target="_blank" class="footer-link">
                                        <ion-icon name="chevron-forward-outline"></ion-icon>

                                        <span class="footer-link-text">Davinci Resolve </span>
                                    </a>
                                </li>



                            </tbody>
                        </table>

                    </div>

                    <div class="footer-list">

                        <p class="footer-list-title">Whatsapp</p>

                        <p class="newsletter-text">
                            "Shop Anytime, Support Every Time – 24/7 Assistance at Your Fingertips!" </p>

                        <form action="" class="newsletter-form">
                        <button 
                          className="whatsapp-button"
                          onClick={handleWhatsAppRedirect}
                        >
                          <FaWhatsapp size={25}/>
                          <label style={{marginLeft:"10px"}}>Contact on WhatsApp</label>
                        </button>
                        </form>


                    </div>

                </div>

            </div>
        </div>

        <div class="footer-bottom">
            <div class="container">

              

                <p class="copyright">
                    &copy; 2024 <a href="#" class="copyright-link">@editwithsanjay</a>. All Rights Reserved
                </p>

                <Version/>

                


            </div>
        </div>

    </footer>
    )
};

export default Footer;
HTMLCSSJavaScriptReact

Search Functionality , for Backend.

Simple "search" functionality.

-> the frontend will make a query parameter request to backend API.

The api will use regex to get data from mongoDB

javascript
const express = require('express');
const app = express();
const Product = require('./models/Product'); // Assuming your Product model is in a `models` folder.

app.get('/api/search', async (req, res) => {
    try {
        const searchText = req.query.searchText || ''; // Default to empty string if no search text is provided.

        // Create a regex pattern to match the search text (case-insensitive).
        const regex = new RegExp(searchText, 'i');

        // Search in relevant fields (e.g., name, description, category).
        const products = await Product.find({
            $or: [
                { name: { $regex: regex } },
                { description: { $regex: regex } },
                { category: { $regex: regex } },
            ],
        });

        res.json(products);
    } catch (error) {
        console.error('Error searching products:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
});

const PORT = 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
MongoDB query.
code
db.products.find({ name : { $regex:"hero"} }).limit(2);
ReactMongoDBNode.js

sample Labda function handlers.

sanjay's ecommerce.

app.js

javascript
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';

import connectDB from './config/connectDB.js';
import serverless from 'serverless-http';

import userRouter from './route/user.route.js';
import categoryRouter from './route/category.route.js';
import uploadRouter from './route/upload.router.js';
import subCategoryRouter from './route/subCategory.route.js';
import productRouter from './route/product.route.js';
import cartRouter from './route/cart.route.js';
import addressRouter from './route/address.route.js';
import orderRouter from './route/order.route.js';
import surveyRouter from './route/survey.route.js';

dotenv.config();

const app = express();
let mongoConnection = false;

app.use(cors({ origin: [process.env.FRONTEND_URL, 'http://localhost:5173' , 'http://192.168.137.70:5173'], credentials: true }));
app.use(express.json());
app.use(cookieParser());


// Middleware to ensure MongoDB is connected
app.use(async (req, res, next) => {
    if (!mongoConnection) {
        try {
            await connectDB();
            mongoConnection = true;
            next();
        } catch (err) {
            return res.status(500).json({ message: "MongoDB not connected yet" });
        }
    } else {
        next();
    }
});

// Routes
app.use('/api/user', userRouter);
app.use('/api/category', categoryRouter);
app.use('/api/file', uploadRouter);
app.use('/api/subcategory', subCategoryRouter);
app.use('/api/product', productRouter);
app.use('/api/cart', cartRouter);
app.use('/api/address', addressRouter);
app.use('/api/order', orderRouter);
app.use('/api/survey', surveyRouter);

app.get('/', (req, res) => {
    if (mongoConnection) {
        res.json({ message: 'Server is running!' ,mongoConnection:true});
    } else {
        res.status(500).json({ message: 'MongoDB not connected yet',mongoConnection:false });
    }
});

// Global error handler
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: "Internal Server Error" });
});

// Export the handler for serverless
export const handler = serverless(app);
doughtflow.
javascript
const exp = require('express');
const app = exp();

const serverless = require('serverless-http');
const cors = require('cors');
const compression = require('compression')
require('dotenv').config();
const { MongoClient } = require('mongodb');

const DBAccess = require('./Middlewares/DBAccess');
const APICounter = require('./Middlewares/APICounter');
const WebSiteCounter = require('./Middlewares/WebSiteCounter');
const usersAPI = require('./APIs/users');
const ErrorRoutehandler = require('./Middlewares/ErrorRoutehandler');
const postsAPI = require('./APIs/posts');
const mediaAPI = require('./APIs/media');

app.use(exp.json());
app.use(exp.urlencoded({ extended: true }));
app.use(cors());

console.log(process.env.MONGO_DB_URL);

// Global variable to store MongoDB connection status
let isMongoConnected = false;

// MongoDB setup
let mongoClientPromise = MongoClient.connect(process.env.MONGO_DB_URL)
    .then(client => {
        const DB = client.db('doughtflow');
        const usersCollection = DB.collection('users');
        const postsCollection = DB.collection('posts');
        const metaCollection = DB.collection('meta');

        app.set('usersCollection', usersCollection);
        app.set('postsCollection', postsCollection);
        app.set('metaCollection', metaCollection);

        isMongoConnected = true;
        console.log("MongoDB connection successful");
    })
    .catch(err => {
        console.error("MongoDB connection failed:", err);
        process.exit(1); // Exit process on failure
    });

// Middleware to wait for MongoDB connection
app.use(async (req, res, next) => {
    if (!isMongoConnected) {
        try {
            await mongoClientPromise; // Wait for the MongoDB connection
            next(); // Proceed if connected
        } catch (err) {
            return res.status(500).send({ message: "MongoDB not connected yet" });
        }
    } else {
        next();
    }
});

// Middleware for database access
app.use(DBAccess);
app.use(APICounter);
app.use(compression())

// Routes
app.get('/', (req, res) => {
    res.send("<h1>Dought Flow</h1>");
});

app.get('/client', WebSiteCounter, async (req, res) => {
    try {
        let response = await req.metaCollection.find().toArray();
        res.send(response[0]);
    } catch (err) {
        res.status(500).send({ error: "Failed to fetch meta data" });
    }
});

app.get('/meta', async (req, res) => {
    try {
        let response = await req.metaCollection.find().toArray();
        res.send(response[0]);
    } catch (err) {
        res.status(500).send({ error: "Failed to fetch meta data" });
    }
});

// Routes management
app.use('/users', usersAPI);
app.use('/posts', postsAPI);
app.use('/media', mediaAPI);
app.use('*', ErrorRoutehandler);

// Export serverless handler
module.exports.handler = serverless(app);
AWSNode.js

DSA in 4 months.

To gain a complete grip on DSA for Oracle (or similar companies) in 4 months, you need a structured and disciplined approach that includes learning concepts, practicing problems, and simulating real interviews. Here’s a month-by-month roadmap:

1. Understand Oracle’s Expectations

Oracle typically tests:

Problem-solving using Data Structures and Algorithms (medium to hard level problems).

Strong understanding of time and space complexity.

Good coding skills in languages like Python, Java, or C++.

System design basics (if applicable for senior roles).

Clear and concise communication during problem-solving.

Month 1: Master the Fundamentals

Focus on understanding basic and intermediate concepts. Choose a preferred language (e.g., Python, Java) and stick to it.

Topics to Learn

Arrays:

Basics, Prefix Sum, Sliding Window, Kadane’s Algorithm.

Problems: Subarrays, subsequences, rotations.

Strings:

Palindromes, pattern matching, anagrams, character frequency.

Common techniques like two pointers.

Linked Lists:

Singly, doubly, circular linked lists.

Reversals, merges, and detecting cycles (Floyd’s Algorithm).

Stacks and Queues:

Use cases: parenthesis matching, stock span, min/max element.

Implement stacks/queues using arrays or linked lists.

Recursion:

Basics of recursion and backtracking.

Problems: N-Queens, Sudoku Solver, Permutations.

Action Plan

Spend 2-3 hours/day:

1 hour: Study concepts from tutorials or books like CLRS or Cracking the Coding Interview.

1 hour: Solve 2-3 beginner problems (e.g., LeetCode Easy, HackerRank).

30 minutes: Revise and reflect on time/space complexities.

Resources:

YouTube Channels: Apna College, Striver (TakeUForward).

Platforms: LeetCode (Easy/Medium), GFG’s “Must-Do Coding Questions”.

Month 2: Dive into Core DSA

Start tackling medium-level problems and deeper topics.

Topics to Learn

Sorting and Searching:

Binary Search (standard and variations).

Quick Sort, Merge Sort, Heap Sort.

Problems: Rotated Array Search, Search in 2D Matrix.

Trees:

Binary Trees, Binary Search Trees, AVL Trees.

Traversals (inorder, preorder, postorder, level order).

Problems: Diameter, LCA, Path Sums.

Hashing:

Hash maps, hash sets, collision handling.

Use cases: two-sum, subarray sums, frequency counts.

Greedy Algorithms:

Interval scheduling, Huffman coding, activity selection.

Problems: Job Scheduling, Minimum Platforms.

Action Plan

Spend 3-4 hours/day:

1-1.5 hours: Study and implement core concepts.

2-3 problems/day from LeetCode Medium or GeeksforGeeks Practice.

Revisit topics from Month 1 if needed.

Resources:

Striver’s DSA Sheet: Follow the sequence for structured learning.

Books: Elements of Programming Interviews (EPI).

Month 3: Advanced DSA + Mock Practice

Work on advanced algorithms and simulate real interview conditions.

Topics to Learn

Dynamic Programming (DP):

Basics: Fibonacci, Knapsack (0/1, unbounded).

Problems: Longest Common Subsequence, Subset Sum, Matrix Chain Multiplication.

Graphs:

Representations: Adjacency list/matrix.

Algorithms: BFS, DFS, Dijkstra, Kruskal, Prim.

Problems: Shortest Path, Detect Cycle, Topological Sort.

Backtracking:

Problems: Word Search, Subset Generation, Combinations.

Tries and Segment Trees (if time permits):

Use cases like prefix search, range queries.

Action Plan

Spend 4-5 hours/day:

1.5 hours: Learn advanced topics.

3-4 problems/day from LeetCode Medium/Hard.

2 mock interviews per week on platforms like Pramp, InterviewBit, or CodePair.

Resources:

Neetcode (for concise problem walkthroughs).

Codeforces/CodeChef for competitive programming.

Month 4: Interview Simulations + Problem Solving

Refine your problem-solving and communication skills.

Plan

Solve Mixed Problems:

Pick random problems (Easy/Medium/Hard) to simulate interview scenarios.

Focus on Oracle-like topics (e.g., array manipulations, graphs, DP).

Mock Interviews:

Weekly mock sessions with peers or platforms like Pramp or LeetCode Premium.

Time yourself while solving questions.

Review Oracle-Specific Questions:

Check platforms like Glassdoor for previously asked Oracle questions.

Solve Oracle-specific problem sets on GFG and LeetCode.

System Design Basics (for experienced roles):

Learn how to design scalable systems (e.g., URL shortener, parking lot).

Focus on concepts like load balancing, caching, and database design.

Action Plan

Spend 4-6 hours/day:

2 hours: Mixed problem-solving.

2 hours: Mock interviews or time-bound problem-solving.

1-2 hours: Revisit weak areas.

Resources:

Cracking the Coding Interview (mock problems).

Oracle-specific discussion forums.

Key Tips for Success

Consistency Over Intensity:

Solve problems daily; avoid burnout.

Focus on Problem-Solving Techniques:

Two pointers, divide and conquer, sliding window, and more.

Analyze Every Problem:

After solving, understand the optimal solution and improve.

Communicate During Mock Interviews:

Explain your thought process clearly and logically.

By following this roadmap with consistent effort, you'll develop a strong grip on DSA in 4 months and confidently tackle Oracle interviews.

Python

updating an array dynamically using useState([])

updating an array using useState() , will vary as per the need.
  1. adding an element
  2. removing an element
  3. updating an element

adding an element.

javascript
import React, { useState } from 'react';

function AddElementExample() {
    const [array, setArray] = useState([1, 2, 3]);

    const addElement = () => {
        const newElement = 4;
        setArray((prevArray) => [...prevArray, newElement]); // Using spread operator
    };

    return (
        <div>
            <button onClick={addElement}>Add 4</button>
            <p>{array.join(', ')}</p>
        </div>
    );
}

export default AddElementExample;

Removing an Element

javascript
function RemoveElementExample() {
    const [array, setArray] = useState([1, 2, 3]);

    const removeElement = (elementToRemove) => {
        setArray((prevArray) => prevArray.filter((el) => el !== elementToRemove));
    };

    return (
        <div>
            <button onClick={() => removeElement(2)}>Remove 2</button>
            <p>{array.join(', ')}</p>
        </div>
    );
}

Updating an Element

javascript
function UpdateElementExample() {
    const [array, setArray] = useState([{ id: 1, value: 'a' }, { id: 2, value: 'b' }]);

    const updateElement = (id, newValue) => {
        setArray((prevArray) =>
            prevArray.map((el) =>
                el.id === id ? { ...el, value: newValue } : el // Update matching element
            )
        );
    };

    return (
        <div>
            <button onClick={() => updateElement(2, 'updated')}>Update 2</button>
            <ul>
                {array.map((el) => (
                    <li key={el.id}>
                        {el.id}: {el.value}
                    </li>
                ))}
            </ul>
        </div>
    );
}
JavaScriptReact

Cloudinary image upload widget

here i use two components , one as paret and other as child

the child is the uploadWidget

parent Component

javascript
import React, { useState } from 'react';
import ImageUploader from './ImageUploader';

function Sample() {
    const [msg, setMsg] = useState();

    function handleUpload(url) {
        console.log("Image uploaded, URL = ", url);
        setMsg(url);
    }

    return (
        <div>
            <ImageUploader handleUpload={handleUpload} />
            {msg && (
                <div>
                    <h4>Uploaded Image:</h4>
                    <img src={msg} alt="Uploaded" style={{ maxWidth: '300px' }} />
                </div>
            )}
        </div>
    );
}

export default Sample;

Child Component / ImageUpload

javascript
import React, { useState } from 'react';

function ImageUploader({ handleUpload }) {
    const openWidget = () => {
        window.cloudinary.openUploadWidget(
            {
                cloudName: 'dxvjbmgta', // Replace with your Cloudinary cloud name
                uploadPreset: process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET, // Set your upload preset
                sources: ['local', 'url', 'camera'], // Sources to upload from
                multiple: false, // Set to true for multiple uploads
                maxFileSize: 5000000, // Limit max file size to 5MB
                resourceType: 'image', // Default is 'image'
            },
            (error, result) => {
                if (error) {
                    console.error('Upload Widget Error:', error);
                    return;
                }

                if (result.event === 'success') {
                    console.log('Upload Success:', result.info);
                    handleUpload(result.info.secure_url); // Pass the URL to the parent
                }
            }
        );
    };

    return (
        <div>
            <button onClick={openWidget}>Upload Image</button>
        </div>
    );
}

export default ImageUploader;

-> You can find the upload "preset" , in the settings sections of cloudinary.

JavaScriptReactDevelopment

Push notifications in js

follow the below link
JavaScript

JWT Authentication and rate limitter.

app.js

javascript
const exp = require('express')
const app = exp()
const jwt = require('jsonwebtoken')
const rateLimit = require('express-rate-limit')
const CORS = require('cors')

const limiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1 minute
    max: 10,
    message: {
        success: false,
        message: 'Too many requests. Please try again later.',
    },
});


app.use(limiter)
app.use(CORS( {  origin:['http://localhost:3000']    } ))


app.use(exp.json())

let users = [ { id:1,userName:'goutham',password:'123'} ]
const SECRET_KEY = '123456789'


app.post('/login' , (req,res)=>{
    const {userName , password} = req.body;

    const result = users.find( (user)=> user.userName == userName && user.password == password );
    
    if(result){
        const token = jwt.sign({userName:userName , password:result.password} , SECRET_KEY , {expiresIn:'5s' })
        res.status(200).json({
            success:true,
            token:token
        })
    }else{
        res.status(401).json({
            success:false,
            message:'invalid credentials.'
        })
    }
})

function authenticateJWT(req,res,next)
{
    const authHeader = req.headers.authorization;

    if(authHeader){
        const token = authHeader.split(' ')[1]
        
        jwt.verify(token , SECRET_KEY , (err,userData)=>{
            if(err){
                res.status(403).json({
                    success:false,
                    message:'Forbidden !'
                })
            }else{
                res.userData = userData;
                next();
            }
        })
    }else{
        res.status(401).json({
            success:false,
            message:'Un-authorized access.'
        })
    }
}
app.get('/users', authenticateJWT , (req,res)=>{
    res.send(users)
})

app.listen(4000 , ()=>console.log("server running on PORT 4000..."))

this also includes rate limitter , using express default rate limitter.

requests.http

code
GET http://localhost:4000/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6ImdvdXRoYW0iLCJwYXNzd29yZCI6IjEyMyIsImlhdCI6MTczNTE0MDA1MiwiZXhwIjoxNzM1MTQ1MDUyfQ.YkHj7McHYM4aBOhs2KeCabWeKYO_u-dF8HeBTlx1p8o
###
POST http://localhost:4000/login
Content-Type: application/json

{
    "userName":"goutham",
    "password":"123"
}

client side implementation.

javascript
const response = await fetch('http://localhost:4000/users', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${encryptedToken}`, // Include token in the Authorization header
            },
        });
JavaScriptReactDevelopment

griet results

griet results

https://gradesresults.griet.in/getresult.php

python
import requests
from bs4 import BeautifulSoup
import json
import time

def get_student_result(rollno):
    url = "https://gradesresults.griet.in/getresult.php"
    payload = {
        "rollno": rollno,
        "result": "GR22:2023-24:A:220:REGULAR:SEPTEMBER",
        "submit": "Get Result"
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }

    try:
        response = requests.post(url, data=payload, headers=headers, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        return {"rollno": rollno, "error": str(e)}

    soup = BeautifulSoup(response.text, 'html.parser')

    name_tag = soup.find('td', text="Name")
    name = name_tag.find_next('td').find_next('td').text.strip() if name_tag else "Name not found"

    sgpa_table = soup.find('table', width="620")
    sgpa = sgpa_table.find_all('td')[3].text.strip() if sgpa_table else "SGPA not found"

    return {"rollno": rollno, "name": name, "sgpa": sgpa}

def generate_roll_numbers():
    rolls = [f"22241A12{str(i).zfill(2)}" for i in range(10, 100)]
    letter = 'a'
    cnt = 0

    while f"{letter}{cnt}" != 'p0':
        if cnt == 10:
            cnt = 0
            letter = chr(ord(letter) + 1)
            if letter > 'z':  # Stop if letter exceeds 'z'
                break
        rolls.append(f"22241A12{letter}{cnt}")
        cnt += 1

    return rolls

def main():
    data = generate_roll_numbers()
    results = []

    for rollno in data:
        result = get_student_result(rollno)
        print(result)
        results.append(result)
        time.sleep(1)  # Delay to avoid server overload

    with open('results.json', 'w') as file:
        json.dump(results, file, indent=4)

if __name__ == "__main__":
    main()
code
###
POST https://gradesresults.griet.in/getresult.php
Content-Type: application/x-www-form-urlencoded

rollno=22241A12K0&result=GR22%3A2023-24%3AA%3A220%3AREGULAR%3ASEPTEMBER&submit=Get+Result
Development

android app projects

all apps are in the uppinurigouthamreddy@gmail.com , email lo.

JavaScriptDevelopment

app ideas thoughts feelings

https://chatgpt.com/share/6776654a-80a0-800d-8a3d-5c2682610b9e

code
Engineering Notes Repository

Features:
Digital notes for each semester and subject.
Video explanations of difficult topics.
User-contributed notes with voting/ranking for quality.
Revenue:
Subscription for premium content or ad-free experience.
Development

Key Motivations for Iterative Development (IID)

Key Motivations for Iterative Development (IID)

Lower Risk:

Empirical evidence shows IID reduces risk and improves success rates, productivity, and defect rates compared to the waterfall model.

Supported by organizations like the USA DoD.

Early Risk Mitigation:

Tackles hard, risky problems (e.g., architecture, integration) early.

Reveals team and tool capabilities while exposing hidden risks.

Adaptability to Change:

Accommodates high-change environments, aligning with software project realities.

Manageable Complexity:

Breaks down complex projects into small, manageable iterations, reducing failure rates and improving productivity.

Confidence and Satisfaction:

Frequent, short iterations provide a sense of completion and boost team morale.

Builds customer confidence through early, visible progress.

Early Partial Product:

Provides early demos and potential for early product shipment with fewer features.

Opens new business opportunities.

Progress Tracking & Predictability:

Tracks meaningful progress with tested software in each iteration (Agile Principle 7).

Offers reliable progress data for future planning and estimation.

Higher Quality:

Emphasizes frequent testing (load, performance, usability, etc.) and iterative refinement.

Aligns final product closer to client desires via feedback.

Process Improvement:

Encourages regular per-iteration assessments for process refinement.

Promotes improvement across all disciplines (programming, testing, requirements, etc.).

Enhanced Communication & Engagement:

Forces coordination through early integration and per-iteration demos.

Boosts client engagement via iteration planning and feedback.

IKIWISI (I’ll Know It When I See It):

Handles user-interface and requirement ambiguity by providing prototypes and iterative feedback to refine client vision.

learn DSA in short time

To quickly learn and revise DSA for interviews in two months, here's a structured plan you can follow:

Week 1-2: Foundation and Core Concepts

Arrays and Strings

Learn basics like traversals, sorting, and searching.

Practice problems on Two Pointers, Sliding Window, and Subarrays.

Linked Lists

Cover singly and doubly linked lists, reversing a list, and detecting cycles.

Practice iterative and recursive solutions.

Stacks and Queues

Understand their implementations and applications like valid parentheses, next greater element, etc.

Learn about Monotonic Stacks.

Hashing

Focus on hashmaps and hashsets for solving problems like two-sum and frequency counting.

Week 3-4: Intermediate Topics

Binary Trees and Binary Search Trees

Practice traversals (inorder, preorder, postorder), height calculation, and common ancestors.

Solve problems on BST properties like range sums.

Binary Search

Master variations like finding the first/last occurrence, search in rotated sorted arrays.

Solve matrix-related binary search problems.

Recursion and Backtracking

Cover subset generation, permutations, N-Queens, and Sudoku solver.

Greedy Algorithms

Understand when greedy works and solve problems like activity selection and interval scheduling.

Week 5-6: Advanced Topics

Dynamic Programming (DP)

Focus on classical problems: Fibonacci, Knapsack, Longest Common Subsequence (LCS), and Matrix Chain Multiplication.

Solve problems using Tabulation and Memoization.

Graph Algorithms

Cover BFS, DFS, Dijkstra’s, and Union-Find.

Solve problems on shortest paths, cycles, and connected components.

Trie

Practice problems on prefix search, autocomplete, and word search.

Heap/Priority Queue

Learn its applications in merging arrays, finding Kth largest/smallest, and scheduling tasks.

Week 7-8: Mock Interviews and Revision

Mock Interviews

Simulate interview scenarios by solving problems in a timed environment.

Practice explaining your approach out loud.

Revision

Focus on weak areas and revisit commonly asked problems.

Review your notes and solutions for tricky problems.

Company-specific Problems

Solve problems from platforms like LeetCode, HackerRank, or Codeforces that are tagged with the companies you’re targeting.

Key Resources

Practice Platforms: LeetCode, GeeksforGeeks, HackerRank, and Codeforces.

Videos: Check out free DSA playlists on YouTube by Love Babbar, Abdul Bari, or Neetcode.

Books: “Cracking the Coding Interview” by Gayle Laakmann McDowell.

Daily Routine

4-6 hours/day: Allocate specific time slots for learning, coding, and reviewing.

Problem Count: Aim for 3-5 problems/day on weekdays and 8-10 problems on weekends.

Consistency and discipline are key. With this plan, you'll cover the essentials and build confidence for your interviews.

Python

rapid api code execution HTML code

javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Python Compiler</title>
</head>
<body>
    <h3>Online Python Compiler</h3>
    
    <textarea 
        placeholder="Write your code here..." 
        class="codeInput"
        rows="10"
        cols="50"
    ></textarea>
    
    <br>
    
    <button class="codeRunButton">Run</button>
    
    <div class="codeOutput"></div>

    <script>
        document.querySelector('.codeRunButton').addEventListener('click', async () => 
        {
            const code = document.querySelector('.codeInput').value;
            const outputDiv = document.querySelector('.codeOutput');

            const url = 'https://online-code-compiler.p.rapidapi.com/v1/';
            const options = {
                method: 'POST',
                headers: {
                    'x-rapidapi-key': '1134d8b70bmshc54af44fa6225e2p178aadjsnce1601f6675e', 
                    'x-rapidapi-host': 'online-code-compiler.p.rapidapi.com',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    language: 'python3',
                    version: 'latest',
                    code: code,
                    input: ""
                })
            };

            try {
                const response = await fetch(url, options);
                const result = await response.json(); // Fix: parse JSON properly

                if (result.output) {
                    outputDiv.innerHTML = `<pre>${result.output}</pre>`;
                } else if (result.error) {
                    outputDiv.innerHTML = `<pre style="color: red;">${result.error}</pre>`;
                }
            } catch (error) {
                console.error(error);
                outputDiv.innerHTML = `<pre style="color: red;">API Error: ${error.message}</pre>`;
            }
        });
    </script>
</body>
</html>
JavaScriptHTMLDevelopment

change background theme randomly.

javascript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Background Color</title>
    <style>
        body {
            background-color: rgb(55, 102, 20);
            font-family: Arial, sans-serif;
        }
    </style>
</head>

<body class="body">
    <h1>Changing Background Color</h1>

    <script>
        function changeTheme() {
            setInterval(() => {
                // Generate random RGB values
                let r = Math.floor(Math.random() * 56);
                let g = Math.floor(Math.random() * 56);
                let b = Math.floor(Math.random() * 56);

                // Apply the random color to the body's background
                document.body.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
            }, 500);
        }

        // Call the function to start changing the background color
        changeTheme();
    </script>
</body>

</html>
JavaScriptHTMLCSS
AWS dynamoDB connection

AWS dynamoDB connection

javascript
require("dotenv").config();
const express = require("express");
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, PutCommand, GetCommand, UpdateCommand, DeleteCommand } = require("@aws-sdk/lib-dynamodb");

const app = express();
app.use(express.json());

const client = new DynamoDBClient({
    region: process.env.AWS_REGION,
    credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    },
});

const dynamoDB = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME;

// 📌 CREATE User (POST)
app.post("/users", async (req, res) => {
    const { userId, name, email } = req.body;
    if (!userId || !name || !email) return res.status(400).json({ error: "Missing fields" });

    try {
        await dynamoDB.send(new PutCommand({
            TableName: TABLE_NAME,
            Item: { id:userId, name, email },
        }));
        res.status(201).json({ message: "User created", user: { userId, name, email } });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


// 📌 READ User (GET)
app.get("/users/:userId", async (req, res) => {
    try {
        const data = await dynamoDB.send(new GetCommand({
            TableName: TABLE_NAME,
            Key: { id: req.params.userId },
        }));
        if (!data.Item) return res.status(404).json({ error: "User not found" });
        res.json(data.Item);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});



// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

environment variables

code
AWS_ACCESS_KEY_ID = AKIAYS2NS64LMVPYUAXM
AWS_SECRET_ACCESS_KEY = 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
AWS_REGION = ap-south-1
TABLE_NAME = users

requests simulation

code
GET http://localhost:5000/users/b
###
POST http://localhost:5000/users
Content-Type: application/json

{
    "userId":"c",
    "name":"reddy",
    "email":"reddy@mdp.in",
    "address":{
        "village":"hyderabad",
        "mandal":"hyderabad",
        "district":"hyderabad"
    }
}
refer this page if needed
AWSDevelopmentNode.js

resume

\documentclass[10pt, letterpaper]{article}

% Packages:

\usepackage[

ignoreheadfoot, % set margins without considering header and footer

top=2 cm, % seperation between body and page edge from the top

bottom=2 cm, % seperation between body and page edge from the bottom

left=2 cm, % seperation between body and page edge from the left

right=2 cm, % seperation between body and page edge from the right

footskip=1.0 cm, % seperation between body and footer

% showframe % for debugging

]{geometry} % for adjusting page geometry

\usepackage{titlesec} % for customizing section titles

\usepackage{tabularx} % for making tables with fixed width columns

\usepackage{array} % tabularx requires this

\usepackage[dvipsnames]{xcolor} % for coloring text

\definecolor{primaryColor}{RGB}{0, 0, 0} % define primary color

\usepackage{enumitem} % for customizing lists

\usepackage{fontawesome5} % for using icons

\usepackage{amsmath} % for math

\usepackage[

pdftitle={Goutham Reddy CV},

pdfauthor={Goutham Reddy},

pdfcreator={LaTeX with RenderCV},

colorlinks=true,

urlcolor=primaryColor

]{hyperref} % for links, metadata and bookmarks

\usepackage[pscoord]{eso-pic} % for floating text on the page

\usepackage{calc} % for calculating lengths

\usepackage{bookmark} % for bookmarks

\usepackage{lastpage} % for getting the total number of pages

\usepackage{changepage} % for one column entries (adjustwidth environment)

\usepackage{paracol} % for two and three column entries

\usepackage{ifthen} % for conditional statements

\usepackage{needspace} % for avoiding page brake right after the section title

\usepackage{iftex} % check if engine is pdflatex, xetex or luatex

\usepackage{graphicx}

\usepackage{xcolor} % For coloring the text

% Ensure that generate pdf is machine readable/ATS parsable:

\ifPDFTeX

\input{glyphtounicode}

\pdfgentounicode=1

\usepackage[T1]{fontenc}

\usepackage[utf8]{inputenc}

\usepackage{lmodern}

\fi

\hypersetup{

colorlinks=true, % Enables colored links

linkcolor=blue, % Sets color for internal links

urlcolor=blue % Sets color for external links

}

\usepackage{charter}

% Some settings:

\raggedright

\AtBeginEnvironment{adjustwidth}{\partopsep0pt} % remove space before adjustwidth environment

\pagestyle{empty} % no header or footer

\setcounter{secnumdepth}{0} % no section numbering

\setlength{\parindent}{0pt} % no indentation

\setlength{\topskip}{0pt} % no top skip

\setlength{\columnsep}{0.15cm} % set column seperation

\pagenumbering{gobble} % no page numbering

\titleformat{\section}{\needspace{4\baselineskip}\bfseries\large}{}{0pt}{}[\vspace{1pt}\titlerule]

\titlespacing{\section}{

% left space:

-1pt

}{

% top space:

0.3 cm

}{

% bottom space:

0.2 cm

} % section title spacing

\renewcommand\labelitemi{$\vcenter{\hbox{\small$\bullet$}}$} % custom bullet points

\newenvironment{highlights}{

\begin{itemize}[

topsep=0.10 cm,

parsep=0.10 cm,

partopsep=0pt,

itemsep=0pt,

leftmargin=0 cm + 10pt

]

}{

\end{itemize}

} % new environment for highlights

\newenvironment{highlightsforbulletentries}{

\begin{itemize}[

topsep=0.10 cm,

parsep=0.10 cm,

partopsep=0pt,

itemsep=0pt,

leftmargin=10pt

]

}{

\end{itemize}

} % new environment for highlights for bullet entries

\newenvironment{onecolentry}{

\begin{adjustwidth}{

0 cm + 0.00001 cm

}{

0 cm + 0.00001 cm

}

}{

\end{adjustwidth}

} % new environment for one column entries

\newenvironment{twocolentry}[2][]{

\onecolentry

\def\secondColumn{#2}

\setcolumnwidth{\fill, 4.5 cm}

\begin{paracol}{2}

}{

\switchcolumn \raggedleft \secondColumn

\end{paracol}

\endonecolentry

} % new environment for two column entries

\newenvironment{threecolentry}[3][]{

\onecolentry

\def\thirdColumn{#3}

\setcolumnwidth{, \fill, 4.5 cm}

\begin{paracol}{3}

{\raggedright #2} \switchcolumn

}{

\switchcolumn \raggedleft \thirdColumn

\end{paracol}

\endonecolentry

} % new environment for three column entries

\newenvironment{header}{

\setlength{\topsep}{0pt}\par\kern\topsep\centering\linespread{1.5}

}{

\par\kern\topsep

} % new environment for the header

\newcommand{\placelastupdatedtext}{% \placetextbox{<horizontal pos>}{<vertical pos>}{<stuff>}

\AddToShipoutPictureFG*{% Add <stuff> to current page foreground

\put(

\LenToUnit{\paperwidth-2 cm-0 cm+0.05cm},

\LenToUnit{\paperheight-1.0 cm}

){\vtop{{\null}\makebox[0pt][c]{

\small\color{gray}\textit{Last updated in January 2025}\hspace{\widthof{Last updated in January 2025}}

}}}%

}%

}%

% save the original href command in a new command:

\let\hrefWithoutArrow\href

% new command for external links:

\begin{document}

\newcommand{\AND}{\unskip

\cleaders\copy\ANDbox\hskip\wd\ANDbox

\ignorespaces

}

\newsavebox\ANDbox

\sbox\ANDbox{$|$}

\begin{header}

\noindent

\begin{minipage}[c]{0.7\textwidth} % Left side: 70% of the page width

\fontsize{25pt}{25pt}\selectfont Uppunuri Goutham Reddy

\vspace{5pt}

\normalsize

{\faEnvelope} \textbf{Email:}

\href{mailto:uppinurigouthamreddy@gmail.com}{uppinurigouthamreddy@gmail.com} \\

{\faPhone} \textbf{Phone:} \href{tel:+91 9398141963}{+91 9398141963} \\

{\faGlobe} \textbf{Portfolio:} \href{https://goutham469.netlify.app/}{goutham469.app} \\

{\faLinkedin} \textbf{LinkedIn:} \href{https://www.linkedin.com/in/gouthamreddy2005}{linkedin.com/in/gouthamreddy2005} \\

{\faGithub} \textbf{GitHub:} \href{https://github.com/goutham469}{github.com/goutham469}

\end{minipage}%

\hfill

\begin{minipage}[c]{0.25\textwidth} % Right side: 25% of the page width

\centering

\includegraphics[width=3.5cm,height=3.5cm]{placeholder.jpeg} % Adjust size as needed

\end{minipage}

\end{header}

\vspace{5 pt - 0.3 cm}

\section{Quick Summary }

\begin{onecolentry}

{Hello! I am a 3rd-year IT undergraduate with a passion for web development and a knack for problem-solving. My expertise lies in the MERN stack, enabling me to build robust and dynamic web applications! }.

\end{onecolentry}

\vspace{0.2 cm}

\begin{onecolentry}

"Crafting dynamic web solutions with passion and precision"

\end{onecolentry}

\section{Education}

\begin{twocolentry}{

Nov 2022 – Dec 2026

}

\textbf{ VNR VJIET Engineering College}, Information Technology;

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item GPA: 8.8

\item \textbf{Coursework:} Operating Systems, UI/UX Designing, Mernstack Development, Problem-Solving

\end{highlights}

\end{onecolentry}

\section{Skills Summary}

\begin{onecolentry}

\begin{highlightsforbulletentries}

\item \textbf{Languages}: Python, Javascript, NodeJs, C, Java, Html, Css

\item \textbf{Frameworks/Libraries}: ReactJs, Express, Bootstrap, TailwindCSS, Material-UI, React Native

\item \textbf{Cloud-computing}: AWS, Netlify, Render, Amplify, Vercel

\item \textbf{machine Learning}: ML, Deep-Learning, TensorFlow

\item \textbf{Tools}:VS Code, Git, AWS EC2

\end{highlightsforbulletentries} \end{onecolentry}

\section{Experience}

\begin{twocolentry}{

Nov 2023 - Present

}

\textbf{Web Developer }, National Service Scheme · Full-time\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "I have been a dedicated volunteer with the National Service Scheme for the past year, actively participating in various community service projects. Through this experience, I have developed valuable skills and a strong commitment to social responsibility."

\end{highlights}

\end{onecolentry}

\begin{twocolentry}{

February 2025 - Present

}

\textbf{Full Stack Developer}, Scholar IT Solutions Inc. Intern Developer\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "I am currently working in a startup company remotely, enhancing my skills through hands-on experience. This opportunity helps me tackle real-world projects, collaborate with professionals, and prepare for consistent development work after college. My goal is to continuously improve in web development and software engineering."

\end{highlights}

\end{onecolentry}

\section{Certifications}

\begin{itemize}

\item \href{https://smartinterviews.in/certificate/8b3f409c}{\textbf{Smart Interviews}: Data structures and algorithms} \hfill \textit{Nov, 2024}

\item \href{hhttps://drive.google.com/file/d/147kEvDpjaUKWC8TmHPaNLqYTxslBsvV3/view}{\textbf{Simple Learn}: Introduction to SQL and Database } \hfill \textit{Oct, 2024}

\end{itemize}

\section{Strengths \& Core Competencies}

\begin{onecolentry}

\begin{highlightsforbulletentries}

\item \textbf{Problem-Solving}: Ability to approach complex challenges and break them down into manageable parts.

\item \textbf{Adaptability}: Comfortable with quickly learning new frameworks and tools, adapting to fast-paced environments.

\item \textbf{Collaboration}: Effective communicator in both team environments and client-facing situations, willing to share knowledge and learn from others.

\item \textbf{Attention to Detail}: Ensuring code quality and optimizing for performance, while keeping user experience top of mind.

\end{highlightsforbulletentries}

\end{onecolentry}

\section{Projects}

\vspace{0.4 cm}

\begin{twocolentry}{

}

\textbf{Website Traffic Analyzer with Real-Time Views} \href{https://traff.netlify.app/}{-Explore the project}

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "I developed a website traffic analyzer that provides real-time insights across multiple dimensions of website views. The tool helps in tracking user behavior, monitoring traffic sources, and analyzing engagement patterns. It offers accurate analytics, user-friendly interfaces, and instant data tracking to enhance website performance."

\item Development Focus: A modern and responsive UI design, real-time analysis with accurate results, and easy-to-use features with optimized performance.

\item Designed and developed in collaboration with my friend, who contributed to the user interface design.

\item Tools Used: ReactJS, NodeJS, MongoDB, AWS Lambda, AWS Amplify, Figma Design, Tailwand-CSS

\end{highlights}

\end{onecolentry}

\vspace{0.2 cm}

\begin{twocolentry}{

}

\textbf{Digital Store for Digital Products with Real-Time Sales}

\href{https://buywithsanjay.netlify.app/}{-Explore the project}

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "A Collaborative Project, developed a digital store, editwithsanjay.in, to sell digital products with real-time sales tracking and payment integration through social media marketing."

\item Developed in collaboration with my friend, who contributed to the real-time marketing and customer generation strategy.

\item Tools Used: ReactJS, NodeJS, MongoDB, AWS Lambda, AWS Amplify, Figma Design, Tailwind CSS, Razorpay, Cashfree

\end{highlights}

\end{onecolentry}

\begin{twocolentry}{

}

\textbf{FeedBook - A Facebook Clone for Social Connectivity}

\href{https://feedbook.netlify.app/}{-Explore the project}

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "FeedBook is a Facebook clone built for social connectivity, offering real-time chat, user profiles, and payment integration for in-app purchases."

\item Tools Used: ReactJS, NodeJS, MongoDB, AWS Lambda, AWS Amplify, Figma Design, Tailwind CSS, Razorpay, Cashfree

\end{highlights}

\end{onecolentry}

\vspace{0.2 cm}

\begin{twocolentry}{

}

\textbf{ShortURL - URL Shortener Tool}

\href{https://sambandamlink.netlify.app/}{-Explore the project}

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "ShortURL is a tool that shortens long URLs, making them easy to share on websites, chats, and emails. It also tracks traffic on short URLs and allows for efficient link management."

\item Tools Used: ReactJS, NodeJS, MongoDB, AWS Lambda, AWS Amplify, Razorpay, Tailwind CSS

\item "The platform ensures quick redirection to the original URL while offering analytics for each shortened link, helping users track engagement and improve marketing strategies."

\end{highlights}

\end{onecolentry}

\vspace{0.2 cm}

\begin{twocolentry}{

}

\textbf{Dought Flow - Project Management Platform}

\href{https://doughtflow.netlify.app/}{-Explore the project}

\end{twocolentry}

\vspace{0.10 cm}

\begin{onecolentry}

\begin{highlights}

\item "Dought Flow is a collaborative platform designed to manage and track projects using Kanban boards. It enhances team collaboration and streamlines project management with real-time updates."

\item Tools Used: ReactJS, NodeJS, MongoDB, AWS Lambda, AWS Amplify, Tailwind CSS

\item "The platform allows seamless task management, prioritization, and progress tracking, making it easy for teams to stay on top of their projects."

\end{highlights}

\end{onecolentry}

\vspace{0.2 cm}

\section{Achievements}

\begin{onecolentry}

\begin{highlightsforbulletentries}

\item \textbf{E-commerce Success}: Generated a significant amount of revenue from an e-commerce digital store by collaborating with a friend on a successful social media marketing campaign.

\item \textbf{Website Traffic Analysis}: Developed a real-time traffic analyzer tool that provides views and analysis, successfully driving leads and consumer engagement for websites.

\item \textbf{GDSC Hackathon - 2nd Runner Up}: Secured the 2nd Runner-Up position in the GDSC Hackathon in the Web Development track for building a high-impact project.

\item \textbf{Campus Automation - Hackathon Runner-Up}: Achieved Runner-Up in a campus automation project hackathon, contributing to the development of software solutions for college management across various streams.

\end{highlightsforbulletentries}

\end{onecolentry}

\end{document}

"Custom version of Stack-overflow"

"Custom version of Stack-overflow"

this is a simple post demonstration the use of doughtflow

a custom stack overflow , for goutham reddy.

here i can save all my development doughts , this application highly enhanced my development speed

HTMLCSSJavaScriptNode.jsAWS

url search params

javascript
import React from 'react'

function SingleTask() {

  let params = new URLSearchParams(window.location.search)
  params = params.get("id")

  console.log(params)
  return (
    <div>
      SINGLE TASK
    </div>
  )
}

export default SingleTask
JavaScriptReact

smtp send mail

javascript
import nodemailer from "nodemailer"

async function sendEmail(toEmail, subject ,  htmlBody) 
{
    try 
    {
        // Configure the transporter (SMTP settings)
        const transporter = nodemailer.createTransport({
            service: "gmail", // Use the email provider's SMTP server
            auth: {
                user: process.env.SENDER_EMAIL, // Your email
                pass: process.env.EMAIL_PASS , // App password (Enable 2FA & generate an app password)
            },
        });

        // Email options
        const mailOptions = {
            from: process.env.SENDER_EMAIL ,
            to: toEmail,
            subject: subject,
            html: htmlBody, // Email content in HTML format
        };

        // Send email
        const info = await transporter.sendMail(mailOptions);
        console.log("Email sent successfully:", info.response);
        return info.response;
    } 
    catch (error) 
    {
        console.error("Error sending email:", error);
        throw error;
    }
}

export default sendEmail

Node.jsDevelopment

whatsapp automation messaging

javascript
const qs = require("querystring");
const https = require("https");

function sendWhatsAppMessage(number, message) {
    const options = {
        method: "POST",
        hostname: "api.ultramsg.com",
        port: null,
        path: "/instance106953/messages/chat",
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        }
    };

    const req = https.request(options, (res) => {
        let chunks = [];

        res.on("data", (chunk) => {
            chunks.push(chunk);
        });

        res.on("end", () => {
            const body = Buffer.concat(chunks);
            console.log("Response from UltraMsg:", body.toString());
        });
    });

    const postData = qs.stringify({
        "token": process.env.WHATS_APP_TOKEN,  // Ensure you store this securely
        "to": `+91${number}`,
        "body": message
    });

    req.write(postData);
    req.end();
}

module.exports = sendWhatsAppMessage;
// Example Usage:
// sendWhatsAppMessage("8919200290", "Hello, this is a test message from UltraMsg.");
JavaScriptNode.jsDevelopment

cashfree payment integration

Totla 5 steps involved in making this application
2 steps in react 3 steps in nodejs

Step-1 : Generate a cashfree order

javascript
import React, { useState } from 'react'
// import Checkout from './PaymentComponent'
import SummaryApi, { clientURL } from '../common/SummaryApi'
import { baseURL } from '../App'
import Axios from '../utils/Axios'
import Checkout from './PaymentComponent'

function CreateCashFreeOrder( { list_items, addressId, subTotalAmt, totalAmt,userDetails } ) {
    const [order_generated , setOrderGenerated] = useState('')
 

    async function createOrder(amount_total = totalAmt , phone_no='' , customer_id1 ='customer_id')
    {
        console.log("cashfree initiation started.")

        try{
            let data = await Axios({
                ...SummaryApi.cashfree_initiate, 
                data : {
                  list_items : list_items,
                  addressId : addressId,
                  subTotalAmt : subTotalAmt,
                  "order_amount": amount_total,
                    "order_currency": "INR",
                    "order_id": `devstudio_${ Date.now() }`,
                    "customer_details": {
                        "customer_id": customer_id1,
                        "customer_phone": phone_no
                    },
                    "order_meta": {
                        "return_url": `${clientURL}/dashboard/myorders`,
                        "notify_url":`${baseURL}/api/order/payment-webhook`
                    }
                }
              })

            console.log(data)

            if(data?.data?.success){
                setOrderGenerated(data?.data?.orderId)
                // alert("payment id generated !")
                console.log(data)
            }
            
        }catch(err){
            alert("payment initiation failed.")
            console.log(err.message)
        }
    }
  return (
    <div>
        {
            order_generated?
            <Checkout  payment_id={order_generated} />
            :
            <button onClick={()=>createOrder()}  className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"  >
                Pay with Cashfree
            </button>
        }
    </div>
  )
} 

export default CreateCashFreeOrder

Step-2 : make payment in new tab cashfree

javascript
import { load } from "@cashfreepayments/cashfree-js";
import { baseURL, clientURL } from "../common/SummaryApi";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";

function Checkout( { payment_id } ) {
    const navigate = useNavigate();

    let cashfree;
    var initializeSDK = async function () {          
        cashfree = await load({
            mode: "production"
        });
    }
    initializeSDK();
 
    const doPayment = async () => {
        let checkoutOptions = {
            paymentSessionId: payment_id,
            redirectTarget: `${clientURL}/cashfree/?orderId=${payment_id}`,
        };
       try{
          let status = await cashfree.checkout(checkoutOptions);
          console.log("status : " , status);

        //   let status2 = await handlePaymentSuccess(payment_id);
        //   console.log("status2 : ",status2)
       }catch(err)
       {
        alert("payment failed");
        console.log(err.message)
       }
    };

    async function sendEmail( id )
    {
        await fetch(`${baseURL}/api/services/send-product` , {
            headers:{"Content-Type":"application/json"},
            method:"POST",
            body:JSON.stringify( {  id:id } )
        })
    }

    const handlePaymentSuccess = async ( payment_id) => {
      // alert(`payment_id = ${payment_id}`)
      

      let verify_payment = await fetch(`${baseURL}/api/order/verify-payment`,{
                          method:"POST",
                          headers:{"Content-Type":"application/json"},
                          body:JSON.stringify({orderId:payment_id})
                        })
      
        verify_payment = await verify_payment.json()
        console.log("verify_payment : ",verify_payment)
 
        if(verify_payment.data.modifiedCount > 0){
            // alert("transaction success.")
            // sendEmail( payment_id )
            toast.success("transaction success")
            navigate('/dashboard/myorders')

        }else{
            // alert("unauthorized transaction.")
            toast.error("unauthorized transaction.")
        }

      console.log("every thing is OK !");

    }

    return (
        <div class="row">
            <button type="submit" className="bg-green-700 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"  id="renderBtn" onClick={doPayment}>
                Pay Now
            </button>
        </div>
    );
}
export default Checkout;

Step-3 : initiate a payment at server

javascript
// cashfree integrations
Cashfree.XClientId = process.env.CASHFREE_CLIENT_ID
Cashfree.XClientSecret = process.env.CASHFREE_CLIENT_SECRET
Cashfree.XEnvironment = Cashfree.Environment.PRODUCTION;

async function generateCashFreeOrder(customer_details) {
  try {
      const response = await Cashfree.PGCreateOrder("2023-08-01", customer_details);
      console.log("CashFree Order created successfully:", response.data);
      return response.data; // Return the order data
  } catch (error) {
      console.error("cashfree generation function :-\n Error:", error.response?.data?.message || error.message);
      return {}; // Return an empty object on error
  }
}

Step-4 : Cashfree payment initiation with adding orderId and other details

javascript
// cashfree payment initiation
export async function CashFreeOnlinePaymentInitiatorController(req,res)
{
  // console.log("\n\nnew payment came via cashFree : ")
  console.log("CashFreeOnlinePaymentInitiatorController")
  console.log(req.body)
  try {
    const userId = req.userId; // authenticated user ID
    const { list_items, order_amount, addressId, subTotalAmt,order_id } = req.body;

    // console.log("userId created by auth middleware : ",userId)

    // Create a Razorpay order
    const cashfreeOrder = await generateCashFreeOrder({
        "order_amount": order_amount ,
        "order_currency": "INR",
        "order_id": order_id ,
        "customer_details": {
            "customer_id": userId,
            "customer_phone": "9398141936",
            "customer_name":order_id
        },
        "order_meta": {
            "return_url": `${process.env.FRONTEND_URL}/dashboard/myorders`,
            "notify_url":`${process.env.SERVER_URL}/api/order/payment-webhook`
        }
    })

    console.log(cashfreeOrder)

    const orderIdAsString = cashfreeOrder.payment_session_id;
    // console.log("orderIdAsString : ",orderIdAsString)

    // Prepare payload for MongoDB
    const payload = list_items?.map((el) => ({
      userId: userId,
      orderId: order_id ,
      productId: el.productId._id,
      product_details: {
        name: el.productId.name,
        image: el.productId.image,
        more_details: el.productId.more_details
      },
      paymentId: "", // Will update after successful payment
      payment_status: "PENDING",
      delivery_address: 'addressId',
      subTotalAmt: subTotalAmt,
      totalAmt: order_amount,
    }));

    // console.log("payload to insert into DB : ",payload) 



    // console.log("new payload : ",payload)
    let generatedOrder = ''

    try
    {
      generatedOrder = await OrderModel.insertMany(payload);
    }
    catch(err){
      console.log("problem in insertion at DB")
      console.log(err)

      return res.status(500).json({
        message: err.message || 'problem in insertion at DB',
        error: true,
        success: false
      });
    }

    

    ///remove from the cart
    const removeCartItems = await CartProductModel.deleteMany({ userId : userId })
    const updateInUser = await UserModel.updateOne({ _id : userId }, { shopping_cart : [] })

    // console.log("removeCartItems : ",removeCartItems)
    // console.log("updateInUser : ",updateInUser)

    return res.json({
      message: "Order initiated",
      error: false,
      success: true,
      orderId: cashfreeOrder.payment_session_id, // Send this to frontend
      data: generatedOrder
    });
  } catch (error) {
    return res.status(500).json({
      message: error.message || error,
      error: true,
      success: false
    });
  }
}

Step-5 : web hook integration

this end point is invoked by cashfree server to conform the payment

javascript
// web hook
export async function cashfreeWebhook(req, res) {
  console.log("cashfree-webhook")

  console.log(req.body)
  const paymentStatus = req.body; // Cashfree sends payment status here

  console.log("paymentStatus.data : ",paymentStatus.data)
  console.log("paymentStatus.data.payment" , paymentStatus.data.payment)

  // Check if the payment was successful
  if (paymentStatus?.data.payment?.payment_status == 'SUCCESS') {
      // Handle success (e.g., update order status in your DB)
      console.log('Payment Successful for Order:', paymentStatus.data.order.order_id  );

      // Update order details in DB upon successful payment
      const updatedOrder = await OrderModel.updateMany(
        { orderId: paymentStatus.data.order.order_id },
        {
          paymentId: paymentStatus.data.order.order_id,
          payment_status: "PAID"
        }
      );

      let orders = await OrderModel.find(  { orderId: paymentStatus.data.order.order_id  }   ).populate("userId").exec();
      console.log(orders);

      for (const order of orders) {
        console.log("drive url : ", order?.product_details?.more_details?.driveLink);
        console.log("userEmail : ", order?.userId?.email);
        console.log("product name : ", order?.product_details?.name);
      
        const template = product_template(order?.product_details?.more_details?.driveLink);
        try {
          const email_status = await sendEmail(order?.userId?.email, order?.product_details?.name, template);
          console.log(email_status);
        } catch (emailError) {
          console.error("Error sending email:", emailError);
        }
      }

      console.log("updatedOrder : ",updatedOrder)


      return res.json({
        message: "Payment successful",
        error: false,
        success: true,
        data: updatedOrder
      });

  } else {
      console.log('Payment Failed for Order:', paymentStatus.orderId);
      return res.status(400).send('Payment Failed');
  }
}
ReactDevelopmentNode.js

Cloudinary upload preset

javascript
export async function cloudinary_upload(image) {
    if (!image) {
        console.error("No image provided");
        return null;
    }

    const formData = new FormData();
    formData.append("file", image);
    formData.append("upload_preset", "ramesh");

    try {
        const response = await fetch("https://api.cloudinary.com/v1_1/dffmffcng/image/upload", {
            method: "POST",
            body: formData,
        });

        const data = await response.json();
        console.log(data);

        return data.url; // Returns the URL of the uploaded image
    } catch (error) {
        console.error("Cloudinary upload failed", error);
        return null;
    }
}
JavaScriptReactDevelopment

Lazy loading in react cloudinary

javascript
import React, { useState, useEffect, useRef } from "react";

const LazyLoadImage = ({ src, alt, placeholder }) => 
{
    const [isLoaded, setIsLoaded] = useState(false);
    const imgRef = useRef(null);

    useEffect(() => 
    {
        const observer = new IntersectionObserver(
            (entries) => 
            {
                if (entries[0].isIntersecting) 
                {
                    setIsLoaded(true);
                    observer.disconnect();
                }
            },
            { threshold: 0.1 }
        );

        if (imgRef.current) 
        {
            observer.observe(imgRef.current);
        }

        return () => observer.disconnect();
    }, []);

    return (
        <img
            ref={imgRef}
            src={isLoaded ? src : placeholder} // Load the real image only when visible
            alt={alt}
            style={{ width: "100%", height: "auto", transition: "opacity 0.3s ease-in-out" }}
        />
    );
};

export default LazyLoadImage;
javascript
import LazyLoadImage from "./LazyLoadImage";

const App = () => 
{
    return (
        <div>
            <h2>Lazy Loaded Images</h2>
            <LazyLoadImage
                src="https://res.cloudinary.com/your-cloudinary/image/upload/v123456/image.jpg"
                placeholder="https://via.placeholder.com/150"
                alt="Cloudinary Image"
            />
        </div>
    );
};

export default App;
JavaScriptReactDevelopment

development operations , requirements , project management

Creating a complete project document requires a structured approach that evolves as the project progresses. Here’s a streamlined process to help you achieve this efficiently:

1. Start with a Lightweight Documentation for Kickstart

When starting a project, focus on minimal documentation, just enough to define the problem and scope:

  1. ✅ Project Overview – Describe the project in 2-3 lines.
  2. ✅ Key Features – List major features or functionalities.
  3. ✅ Technology Stack – Define frontend, backend, database, and cloud services.
  4. ✅ Basic Wireframes – Sketch a rough UI structure.
  5. ✅ Initial API Endpoints – Define core API actions (e.g., /auth/login, /user/profile).

2. Transition to Full-Fledged Documentation as You Scale

Once development starts, evolve the documentation into a structured format:

  • 📌 Project Structure & Development Roadmap
  • Modules Breakdown – Define modules (e.g., User Management, Payments, Notifications).
  • Development Phases – Create milestones (e.g., "MVP in 4 weeks, Beta in 8 weeks").
  • Component Dependencies – Identify which modules should be built first.

📌 Detailed API Documentation

  • Use OpenAPI (Swagger) – Generate interactive API docs.
  • Define Request & Response Models – Example:
  • json
  • Copy
  • Edit

code
{
  "method": "POST",
  "endpoint": "/api/user/register",
  "request": { "name": "John", "email": "john@example.com", "password": "123456" },
  "response": { "status": "success", "userId": 101 }
}
📌 Database Schema & ER Diagrams
  1. Use draw.io or DBDiagram.io for visual ER models.
  2. Document table relations clearly.

📌 Architecture & Workflow Diagrams
  • UML Diagrams – Show how data flows in the system.
  • Sequence Diagrams – Define request-response cycles.

3. Automate Documentation to Reduce Effort

Instead of manually maintaining everything, automate as much as possible:

  • ✅ Swagger for API Documentation – Auto-generate REST API docs.
  • ✅ Mermaid.js for Diagrams – Use Markdown-based diagrams.
  • ✅ Notion / Confluence / Google Docs – Centralize all documentation.
  • ✅ Postman for API Testing & Collection – Save and document API requests.
  • ✅ JIRA / Trello – Track development phases and assign tasks.

Development

postgress SQL database connection with nodejs

javascript
require('dotenv').config();
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: { rejectUnauthorized: false }  // Required for NeonDB
});

module.exports = pool;

with checking weather the connection is made with DB or not.

javascript
require('dotenv').config();
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: { rejectUnauthorized: false }, // NeonDB requires SSL
});

pool.connect()
  .then(() => console.log('✅ Connected to NeonDB PostgreSQL'))
  .catch(err => console.error('❌ Database Connection Error:', err));

module.exports = pool;
Handling API endpoints with postgress
javascript
const pool = require('../db'); // Import the DB connection

// Corrected function
async function getUserByUserName(req, res) 
{
    const { userId } = req.params; // Extract username from request params

    try {
        const data = await pool.query(
            `SELECT * FROM users WHERE username = $1`, 
            [userId]  // Secure parameterized query
        );

        res.json({ success: true, data: data.rows }); // Send query results
    } 
    catch (err) 
    {
        res.status(500).json({ success: false, message: "Error at server", error: err.message });
    }
}

// Export the function correctly
module.exports = { getUserByUserName };
Node.jsSQLDevelopment

chatgpt easier reponse saving mechanism

javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat History</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; padding: 20px; background-color: #f4f4f4; }
        .chat-container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .message { margin-bottom: 15px; padding: 10px; border-radius: 5px; }
        .user { background-color: #d1e7ff; text-align: left; }
        .assistant { background-color: #e6e6e6; text-align: left; }
        pre { background-color: #272822; color: #f8f8f2; padding: 10px; border-radius: 5px; overflow-x: auto; }
        code { font-family: monospace; }
    </style>
</head>
<body>
    <div class="chat-container">
        <h2>Chat History</h2>
        <div class="message user"><strong>You:</strong> I am now facing a program with ChatGPT</div>
        <div class="message assistant"><strong>ChatGPT:</strong> Could you clarify what issue you're facing with ChatGPT? Are you integrating it into your project, or is there an error you're encountering? Let me know the details so I can help!</div>
        <div class="message user"><strong>You:</strong> For every chat I am chatting about is saved at your servers, and can be accessible to me only if I am on the internet. So I want to convert this all to an HTML code / some other format that can be parsed within another application, so I can use it easily later.</div>
        <div class="message assistant"><strong>ChatGPT:</strong> You can export your chats in a structured format like <strong>HTML, JSON, or Markdown</strong> so that they can be parsed and used within another application later...</div>
        <div class="message user"><strong>You:</strong> HTML</div>
        <div class="message assistant"><strong>ChatGPT:</strong> Great choice! Here’s how you can <strong>efficiently store your chat history in an HTML file</strong> without hitting token limits:
            <pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Chat History&lt;/title&gt;
    &lt;style&gt;
        body { font-family: Arial, sans-serif; }
        .message { padding: 10px; border-radius: 5px; }
        .user { background-color: #d1e7ff; }
        .assistant { background-color: #e6e6e6; }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="chat-container"&gt;
        &lt;h2&gt;Chat History&lt;/h2&gt;
    &lt;/div&gt;
    &lt;script&gt;
        function appendMessage(role, message) {
            let chatContainer = document.querySelector(".chat-container");
            let messageDiv = document.createElement("div");
            messageDiv.classList.add("message", role);
            messageDiv.innerHTML = "&lt;strong&gt;" + (role === 'user' ? 'You' : 'ChatGPT') + "&lt;/strong&gt;: " + message;
            chatContainer.appendChild(messageDiv);
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
        </div>
    </div>
</body>
</html>
HTMLDevelopment

aws lambda smtp mail service

javascript
const nodemailer = require("nodemailer");

async function sendEmail(toEmail, subject, htmlBody) 
{
    try 
    {
        const transporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user: process.env.SENDER_EMAIL,
                pass: process.env.EMAIL_PASS,
            },
            tls: {
                rejectUnauthorized: false,
            },
            port: 587, // Use 587 for TLS
            secure: false, // Must be false for port 587
        });

        const mailOptions = {
            from: process.env.SENDER_EMAIL,
            to: toEmail,
            subject: subject,
            html: htmlBody,
        };

        const info = await transporter.sendMail(mailOptions);
        console.log("✅ Email sent successfully:", info.response);
        return info.response;
    } 
    catch (error) 
    {
        console.error("❌ Error sending email:", error);
        throw new Error("Email sending failed");
    }
}

module.exports = sendEmail;
javascript
const newUserRegistrationTemplate = require("../templates/new_user.template");
const generateRandomString = require("../utils/generatePassword");
const sendEmail = require("../utils/sendEmail"); // Fix the import

async function loginWithGoogle(req, res) 
{
    try 
    {
        const { email, image } = req.body;

        if (!email) {
            return res.status(400).json({ success: false, message: "Email is required" });
        }

        const status = await req.db.query("SELECT * FROM users WHERE email=$1", [email]);

        if (status.rows.length === 0) 
        {
            // Generate password securely
            const password = generateRandomString(10);

            // Insert user
            const createStatus = await req.db.query(
                "INSERT INTO users (email, image, password) VALUES ($1, $2, $3) RETURNING *",
                [email, image, password]
            );

            const newUser = createStatus.rows[0];

            // Send welcome email
            try {
                const emailStatus = await sendEmail(
                    email,
                    "🎉 Welcome to Question Track!",
                    newUserRegistrationTemplate(email)
                );
                console.log("Email sent status:", emailStatus);
            } catch (emailError) {
                console.error("Failed to send email:", emailError);
            }

            return res.json({ success: true, message: "Account created", data: newUser });
        } 
        else 
        {
            return res.json({ success: true, message: "Login success", data: status.rows[0] });
        }
    } 
    catch (err) 
    {
        console.error("Error in loginWithGoogle:", err);
        res.status(500).json({ success: false, message: "Something went wrong", error: err.message });
    }
}
Node.jsDevelopment

cloudinary transformations , for reduced bandwidth consumption

javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cloudinary Image Optimization</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 900px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        }
        code {
            background: #eee;
            padding: 5px;
            border-radius: 5px;
            display: block;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Cloudinary Image Optimization</h1>
        
        <h2>1. Serve Different Sizes Based on Device</h2>
        <p>Use <code>srcset</code> in HTML to serve optimized images:</p>
        <code>
&lt;img 
  src="https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_2000,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID" 
  srcset="
    https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_500,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID 500w,
    https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_1000,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID 1000w,
    https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_1500,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID 1500w,
    https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_2000,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID 2000w"
  sizes="(max-width: 600px) 500px, (max-width: 1200px) 1000px, (max-width: 1800px) 1500px, 2000px"
  alt="Your Image"&gt;
        </code>

        <h2>2. Use JavaScript to Detect Screen Width</h2>
        <code>
const getImageURL = () => {
  const width = window.innerWidth;
  if (width <= 600) {
    return "https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_500,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID";
  } else if (width <= 1200) {
    return "https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_1000,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID";
  } else {
    return "https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_2000,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID";
  }
};

document.getElementById("dynamicImage").src = getImageURL();
        </code>
        <p>HTML:</p>
        <code>
&lt;img id="dynamicImage" alt="Your Image"&gt;
        </code>

        <h2>3. Cloudinary Auto-Optimization</h2>
        <p>Use <code>w_auto, dpr_auto, q_auto, f_auto</code> for a single optimized URL:</p>
        <code>
https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/w_auto,dpr_auto,q_auto,f_auto/YOUR_IMAGE_PUBLIC_ID
        </code>

        <h2>📉 Bandwidth Savings</h2>
        <table border="1" cellpadding="5">
            <tr>
                <th>Scenario</th>
                <th>Without Optimization</th>
                <th>With Cloudinary</th>
                <th>Savings</th>
            </tr>
            <tr>
                <td>Mobile (400px width)</td>
                <td>5MB</td>
                <td>300-500KB</td>
                <td>90%</td>
            </tr>
            <tr>
                <td>Tablet (800px width)</td>
                <td>5MB</td>
                <td>600KB - 1MB</td>
                <td>80%</td>
            </tr>
            <tr>
                <td>Desktop (Full HD)</td>
                <td>5MB</td>
                <td>1.5-2MB</td>
                <td>60-70%</td>
            </tr>
        </table>

        <h2>✅ Best Practices</h2>
        <ul>
            <li>Use <code>srcset</code> for responsive images.</li>
            <li>Enable <code>q_auto</code> and <code>f_auto</code> to reduce image size.</li>
            <li>Use <code>w_auto, dpr_auto</code> for dynamic scaling.</li>
            <li>Leverage Cloudinary's CDN for caching.</li>
        </ul>
    </div>
</body>
</html>
JavaScriptHTMLDevelopment

vs code , screen time usage extension

javascript
// src/extension.ts
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';

let startTime: number | null = null;
let totalTime = 0;
let statusBarItem: vscode.StatusBarItem;

export function activate(context: vscode.ExtensionContext) {
    // Load saved time
    totalTime = context.globalState.get<number>("totalTime", 0);
    
    // Create status bar item
    statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = `VS Code Time: ${formatTime(totalTime)}`;
    statusBarItem.show();
    context.subscriptions.push(statusBarItem);
    
    // Track window state
    vscode.window.onDidChangeWindowState((state) => {
        if (state.focused) {
            startTime = Date.now();
        } else if (startTime) {
            totalTime += Date.now() - startTime;
            startTime = null;
            context.globalState.update("totalTime", totalTime);
            statusBarItem.text = `VS Code Time: ${formatTime(totalTime)}`;
        }
    });
    
    // Register export command
    let disposable = vscode.commands.registerCommand('extension.exportTimeData', () => {
        exportTimeData(totalTime);
    });
    context.subscriptions.push(disposable);
}

export function deactivate() {
    if (startTime) {
        totalTime += Date.now() - startTime;
    }
}

function formatTime(ms: number): string {
    let seconds = Math.floor(ms / 1000);
    let minutes = Math.floor(seconds / 60);
    let hours = Math.floor(minutes / 60);
    return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
}

function exportTimeData(totalTime: number) {
    const filePath = path.join(vscode.workspace.rootPath || __dirname, 'vs-code-time-log.json');
    const data = {
        project: vscode.workspace.name || "Unknown Project",
        totalTime: formatTime(totalTime),
        timestamp: new Date().toISOString()
    };
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
    vscode.window.showInformationMessage(`Time data exported to ${filePath}`);
}
DevelopmentJavaScript

change title of webpage dynamically , in react

javascript
import { useEffect, useState } from "react";

const DynamicTitle = () => {
  const [title, setTitle] = useState("Initial Title");

  useEffect(() => {
    document.title = title;
  }, [title]); // Updates when `title` changes

  return (
    <div>
      <h1>Change Page Title</h1>
      <button onClick={() => setTitle("New Title 1")}>Title 1</button>
      <button onClick={() => setTitle("New Title 2")}>Title 2</button>
    </div>
  );
};

export default DynamicTitle;

for better SEO , use react-helmet

javascript
import { Helmet } from "react-helmet";

const HelmetTitle = () => {
  return (
    <div>
      <Helmet>
        <title>New Helmet Title</title>
      </Helmet>
      <h1>React Helmet Example</h1>
    </div>
  );
};

export default HelmetTitle;
HTMLJavaScriptReact

SECURED data transfer b/w client and server , with encryption and decryption

stages
  1. client form data
  2. encrypted_data = encrypy(form_data)
  3. POST /login {data:encrypted_data}
  4. decrypt middleware (req.body = decrypted)
  5. process data at server
  6. encryted_data = encrypt(JSON.stringify(processed_data))
  7. res.send({data:encrypted_data})
  8. await res.json()
  9. decrypted = decrypt(res.body.data)
  10. continue further

App.jsx

javascript
import { useState } from "react";
// import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { encrypt } from "./api/encrypt";
import { SERVER_URL } from "./api/secrets";
import { decrypt } from "./api/decrypt";

function App() {


  const [form , setForm] = useState({})
  async function login(e)
  {
    e.preventDefault();
    console.log(form)
    const encrypted = encrypt(form);
    console.log(encrypted);

    console.log(SERVER_URL)

    let response = await fetch(`${SERVER_URL}/login` , {
      method:"POST",
      headers:{ "Content-Type":"application/json" },
      body:JSON.stringify({data:encrypted})
    });

    console.log(response);
    response = await response.json();

    response = decrypt(response.data);

    console.log(response);
  }

  return (
    <div >
      {/* <RouterProvider router={router} /> */}
      <div>
        <input
         type="text"
         placeholder="email"
         className="bg-red-200 m-2 p-2"
         onChange={ (e)=>setForm( data => ({ ...data , email:e.target.value })) }
        />
        <br/>
        <input 
        type="password"
        placeholder="password"
        className="bg-red-200 m-2 p-2"
        onChange={ (e)=>setForm( data => ({ ...data , password:e.target.value })) }
        />
        <br/>
        <button
         onClick={(e)=>login(e)}
         className="bg-red-200 m-2 p-2 cursor-pointer"
        >Login</button>
      </div>
    </div>
  );
}

export default App;

client - encrypt.js file

javascript
import CryptoJS from "crypto-js";

const JWT_SECRET = import.meta.env.VITE_JWT_SECRET;

export function encrypt(data) {
    return CryptoJS.AES.encrypt(JSON.stringify(data), JWT_SECRET).toString();
}

client decrypt.js file

javascript
import CryptoJS from "crypto-js";

const JWT_SECRET = import.meta.env.VITE_JWT_SECRET;

export function decrypt(data) {
    // console.log("Encrypted Data:", data);

    try {
        const bytes = CryptoJS.AES.decrypt(data, JWT_SECRET);
        // console.log(bytes)
        const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
        // console.log(decryptedData)

        if (!decryptedData) throw new Error("Decryption failed");

        return JSON.parse(decryptedData);
    } catch (error) {
        console.error("Error decrypting data:", error);
        return null; // Handle decryption failure gracefully
    }
}

server.js

javascript
const exp = require("express")
const CORS = require("cors")
const encrypt = require("./middlewares/encrypt")
const decrypt = require("./middlewares/decrypt")
require("dotenv").config()
const app = exp()

// middlewares
app.use(exp.json())
app.use(CORS())

// routes
app.get('/' , (req,res) => res.send("root level"))



app.post("/login" , decrypt , (req,res) => {
    console.log(req.body);

    const responseData = { status:"login success" }

    const message =  encrypt(responseData)
    console.log(message)

    res.send({data:message})
})

// others
app.listen( 4000 , ()=> console.log("server running on PORT 4000..."))

server encrypt.js file

javascript

const CryptoJS = require("crypto-js")

function encrypt(data)
{
    return CryptoJS.AES.encrypt(JSON.stringify(data), process.env.JWT_SECRET).toString();
}

module.exports = encrypt;

server decrypt.js file

javascript

const CryptoJS = require("crypto-js")

const decrypt = (req,res,next) => {
    console.log("inside decrypt : ",req.body);
    console.log("secret : ",process.env.JWT_SECRET)

    const bytes = CryptoJS.AES.decrypt(req.body.data, process.env.JWT_SECRET);
    req.body = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));

    next();
};

module.exports = decrypt;
JavaScriptDevelopment

Google oauth login

code
npm install @react-oauth/google
code
<GoogleOAuthProvider clientId={ GOOGLE_AUTH_CLIENT_ID } >
        <RouterProvider router={ router } /> 
      </GoogleOAuthProvider>
javascript
async function onSuccess(params) {
    console.log(params.credential)
    const credential = jwtDecode(params.credential);
    console.log(credential)
  }
code
 npm i jwt-decode
ReactDevelopment

flask API

python
from flask import Flask, request, jsonify

app = Flask(__name__)

class User:
    def __init__(self, id, user_name, name, password):
        self.id = id
        self.user_name = user_name
        self.name = name
        self.password = password

    def change_name(self, new_name):
        self.name = new_name
        return self

    def change_password(self, new_password):
        self.password = new_password
        return self
    def match_user_name(self , user_name):
        s = set( [ char for char in self.user_name ] )
        S = set( [ char for char in user_name ] )
        if len(s) >= S :
            return True

    def to_dict(self):  # Convert User object to a dictionary
        return {
            "id": self.id,
            "user_name": self.user_name,
            "name": self.name,
            "password": self.password  # Ideally, don't return passwords in production
        }

class DB:
    def __init__(self):
        self.users = []

    def add_user(self, user_data):
        try:
            for user in self.users:
                if user.user_name == user_data["user_name"]:
                    return jsonify({"error": "Username already exists"}), 400
            
            user_obj = User(user_data["id"], user_data["user_name"], user_data["name"], user_data["password"])
            self.users.append(user_obj)
            return jsonify({"message": "User added successfully", "users": self.get_users()}), 201
        except Exception as e:
            return jsonify({"error": f"Server error: {str(e)}"}), 500

    def get_users(self):
        return [user.to_dict() for user in self.users]
    def change_name(self , data ) :
        for user in self.users :
            if user.user_name == data['user_name'] :
                user = user.change_name( data['new_name'] )
        return jsonify( { "message":"user_name changed" , "users":self.get_users() } )
    def change_password( self , data ) :
        for user in self.users :
            if user.user_name == data['user_name'] :
                user = user.change_password( data['new_password'] )
        return jsonify( self.get_users() )
    def search_user( self , user_name ) :
        users = []
        for user in self.users :
            if user.match_user_name( user_name ) :
                users.append( user )
            
        return jsonify(users)

db = DB()

# Get all users
@app.route("/user", methods=["GET"])
def get_users():
    return jsonify(db.get_users())

# Add user
@app.route("/user", methods=["POST"])
def add_user():
    new_user = request.get_json()
    if not new_user:
        return jsonify({"error": "Invalid JSON"}), 400
    return db.add_user(new_user)
# change name
@app.route("/change-name" , methods=['POST'])
def update_user_name() :
    body = request.get_json()
    return db.change_name( body )
# change password
@app.route("/change-password" , methods=['PUT'])
def update_password() :
    body = request.get_json()
    return db.change_password( body )
# search by username
@app.route("/search-user" , methods=['GET'])
def search_user() :
    user_name = request.args.get("username")

    return db.search_user( user_name ) if db.get_users() else []



if __name__ == "__main__":
    app.run(debug=True)
PythonDevelopment

flask ml house price prediction , python, server

python
from flask import Flask, jsonify, request, render_template
import joblib
import numpy as np

app = Flask(__name__)

@app.route("/", methods=['GET'])
def root():
    return render_template("form.html")

@app.route("/predict", methods=['POST'])
def predict():
    try:
        model = joblib.load("house_price_prediction_model.pkl")
        data = request.json  # or use request.get_json()

        # Validate input
        required_fields = ["bedrooms", "bathrooms", "sqft_living", "sqft_lot", 
                           "floors", "condition", "sqft_above", "sqft_basement", 
                           "yr_built", "yr_renovated"]
        
        if not all(field in data for field in required_fields):
            return jsonify({"error": "Missing required fields"}), 400

        arr = np.array([[data[field] for field in required_fields]])
        prediction = model.predict(arr)

        return jsonify({"predicted_price": float(prediction[0])})

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)
PythonDevelopment

tomato disease prediction , CNN , Machine Learning(ML)

python
import kagglehub

# Download latest version
path = kagglehub.dataset_download("mamtag/tomato-village")

print("Path to dataset files:", path)
python
import os

absolute_path = os.path.abspath(path)
print("Absolute Path:", absolute_path)
code
os.listdir( absolute_path )
Loading image_dataset using tensorflow
code
import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory

train_dataset = image_dataset_from_directory(
    path+"/Variant-a(Multiclass Classification)/train",
    image_size=(224,224),
    batch_size=32
)

test_dataset = image_dataset_from_directory(
    path+"/Variant-a(Multiclass Classification)/test",
    image_size=(224,224),
    batch_size=32
)
obtaining class names from the above
css
class_names = train_dataset.class_names
class_names
Conv2D neural network
code
from tensorflow.keras import models,layers

model = models.Sequential([
    layers.Rescaling(1./255, input_shape=(224, 224, 3)),  # Normalize
    layers.Conv2D(32, (3, 3), activation='relu', padding='same'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu', padding='same'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(128, (3, 3), activation='relu', padding='same'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(len(class_names), activation='softmax')  # Output layer
])
Compiling model
code
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
training model
code
model.fit( train_dataset , epochs=10 )
predicting the results
code
import numpy as np

y_true = np.concatenate([y.numpy() for x, y in test_dataset ])
code
y_pred_probs = model.predict( test_dataset )
y_pred = np.argmax( y_pred_probs , axis=1 )
code
from sklearn.metrics import confusion_matrix

mat = confusion_matrix( y_true , y_pred )
mat
code
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)

# Plot confusion matrix
plt.figure(figsize=(8,6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=range(10), yticklabels=range(10))
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()
Machine LearningPython

sanjay aws credentials

access_key = "RYhJu1HBALTX2G4YySHtgRBGC1NeP9suEAS80GJr"

"Secret access key" = "RYhJu1HBALTX2G4YySHtgRBGC1NeP9suEAS80GJr"

DevelopmentAWS

deploying AWS service to client a/c , via powershell

  1. get the AWS CLI installed on your system
  2. get the AWS "access key" and "secret access key"
  3. configure the profile(client) in the powershell
  4. make the serverless.yml file in the project directory
  5. deploy the service

the access key , secret access key

code
PS D:\applications\aws\lambda+api_gateway> aws sts get-caller-identity --profile sanjay
{
    "UserId": "AIDA4WJPWL5JNJHVLTOFD",
    "Account": "872515264338",
    "Arn": "arn:aws:iam::872515264338:user/goutham"
}

PS D:\applications\aws\lambda+api_gateway>
code
"access key" = "AKIA4WJPWL5JCOJHYS4A "
"secret access key" = "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"

configuring the aws credentials in powershell

code
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Users\gouth> aws

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

aws: error: the following arguments are required: command

PS C:\Users\gouth> aws --version
aws-cli/2.26.1 Python/3.13.2 Windows/11 exe/AMD64
PS C:\Users\gouth> aws configure --profile sanjay
AWS Access Key ID [None]: RYhJu1HBALTX2G4YySHtgRBGC1NeP9suEAS80GJr
AWS Secret Access Key [None]:
PS C:\Users\gouth> ^C
PS C:\Users\gouth> ^C
PS C:\Users\gouth> ^C
PS C:\Users\gouth> aws configure --profile sanjay
AWS Access Key ID [None]: AKIA4WJPWL5JCOJHYS4A
AWS Secret Access Key [None]: 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
Default region name [None]: ap-south-1
Default output format [None]:
PS C:\Users\gouth>

serverless.yml

code
service: test-client-node-api

provider:
  name: aws
  runtime: nodejs18.x
  region: ap-south-1
  profile: sanjay
  stage: dev

functions:
  api:
    handler: app.handler
    events:
      - http: ANY /
      - http: ANY /{proxy+}

in case of production of release use state : prod

deploy the service

code
serverless deploy

Give the required roles,access to the given user

the main role is :-

AdministratorAccess

You can modify the permissions in "Permissions policies"

You can find that in :-

IAM>users>user_name(goutham)

references
AWSDevelopment

s3 golbal access

Bucket policy
code
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowAuthenticatedUploads",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::goutham469uploads",
                "arn:aws:s3:::goutham469uploads/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}

file url structure

https://goutham469uploads.s3.ap-south-1.amazonaws.com/google-map3.jpg

React upload preset code
javascript
import React, { useState } from 'react';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const DirectS3Upload = ({ onUploadSuccess }) => {
  const [file, setFile] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);
  const [imageURL, setImageURL] = useState("");

  const handleFileChange = (e) => {
    if (e.target.files[0]) {
      setFile(e.target.files[0]);
      setError(null);
    }
  };

  const uploadToS3 = async () => {
    if (!file) {
      setError('Please select a file first');
      return;
    }

    try {
      setUploading(true);
      setProgress(0);
      
      // Initialize S3 client
      const s3Client = new S3Client({
        region: 'ap-south-1',
        credentials: {
          accessKeyId: import.meta.env.ACCESS_KEY,
          secretAccessKey: import.meta.env.SECRET_ACCESS_KEY
        }
      });
      
      // Generate a unique filename
      const fileName = `${Date.now()}-${file.name}`;
      const key = `uploads/${fileName}`;
      
      // Read file as ArrayBuffer
      const fileContent = await readFileAsArrayBuffer(file);
      
      // Create upload command
      const command = new PutObjectCommand({
        Bucket: 'goutham469uploads',
        Key: key,
        Body: fileContent,
        ContentType: file.type
      });
      
      // Upload file
      await s3Client.send(command);
      
      // Construct the file URL
      const fileUrl = `https://goutham469uploads.s3.amazonaws.com/${key}`;
      
      setImageURL(fileUrl);
      setUploading(false);
      
      if (typeof onUploadSuccess === 'function') {
        onUploadSuccess(fileUrl);
      }
    } catch (err) {
      console.error('Upload error:', err);
      setError('Upload failed: ' + err.message);
      setUploading(false);
    }
  };

  // Helper function to read file as ArrayBuffer
  const readFileAsArrayBuffer = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
      reader.readAsArrayBuffer(file);
    });
  };

  return (
    <div>
      <input 
        type="file"
        onChange={handleFileChange}
        className='bg-cyan-900 cursor-pointer rounded-sm p-2 text-black'
      />
      <button 
        onClick={uploadToS3} 
        disabled={!file || uploading}
        className='bg-cyan-500 cursor-pointer rounded-sm p-2 text-black'
      >
        {uploading ? 'Uploading...' : 'Upload'}
      </button>

      {uploading && <div>Progress: {progress}%</div>}
      {error && <div style={{ color: 'red' }}>{error}</div>}

      {imageURL && 
        <img 
          src={imageURL} 
          alt="Uploaded image" 
          style={{ maxWidth: '100%', marginTop: '10px' }} 
        />
      }
    </div>
  );
};

export default DirectS3Upload;

-> Access key , secret access key are to be stored as environment variables in the application, these can be accessed with IAM users with s3 complete accesss policy.

AWS