Category: Projects

https://cdn3d.iconscout.com/3d/premium/thumb/project-task-management-3d-illustration-download-in-png-blend-fbx-gltf-file-formats–development-checklist-list-design-pack-business-illustrations-4496029.png

  • Fitness Tracker

    Hardware Components

    1. Microcontroller: Arduino Uno or Raspberry Pi
    2. Sensors:
      • Accelerometer (e.g., MPU6050)
      • Heart rate sensor (e.g., MAX30100)
    3. Display (optional): OLED display
    4. Power Supply: Battery or USB power source
    5. Bluetooth Module: HC-05 for communication with a mobile app (if using Arduino)

    Software Components

    1. Arduino IDE: For programming the microcontroller
    2. Mobile App: Could be a simple web app or a native app using frameworks like React Native.

    Sample Code for Arduino

    Setting Up the Accelerometer

    cppCopy code#include <Wire.h>
    #include <MPU6050.h>
    
    MPU6050 mpu;
    
    void setup() {
      Serial.begin(9600);
      Wire.begin();
      mpu.initialize();
      if (!mpu.testConnection()) {
    
    Serial.println("MPU6050 connection failed");
    } } void loop() { int16_t ax, ay, az; mpu.getAcceleration(&ax, &ay, &az); Serial.print("Acceleration X: "); Serial.print(ax); Serial.print(" Y: "); Serial.print(ay); Serial.print(" Z: "); Serial.println(az); delay(1000); }

    Setting Up the Heart Rate Sensor

    cppCopy code#include <Wire.h>
    #include <MAX30100_PulseOximeter.h>
    
    MAX30100_PulseOximeter pox;
    
    void setup() {
      Serial.begin(9600);
      pox.begin();
    }
    
    void loop() {
      pox.update();
      Serial.print("Heart Rate: ");
      Serial.println(pox.getHeartRate());
      delay(1000);
    }
    

    Mobile App Example (Using React Native)

    You can use libraries like react-native-bluetooth-serial to connect to your Arduino.

    Basic Setup

    bashCopy codenpx react-native init FitnessTracker
    cd FitnessTracker
    npm install react-native-bluetooth-serial
    

    Sample Code for App

    javascriptCopy codeimport React, { useEffect, useState } from 'react';
    import { View, Text, Button } from 'react-native';
    import BluetoothSerial from 'react-native-bluetooth-serial';
    
    const App = () => {
      const [data, setData] = useState('');
    
      useEffect(() => {
    
    BluetoothSerial.connect('DEVICE_MAC_ADDRESS')
      .then((res) =&gt; {
        console.log('Connected', res);
      })
      .catch((err) =&gt; console.log(err));
    BluetoothSerial.on('data', (data) =&gt; {
      setData(data);
    });
    return () =&gt; {
      BluetoothSerial.disconnect();
    };
    }, []); return (
    &lt;View&gt;
      &lt;Text&gt;Received Data: {data}&lt;/Text&gt;
      &lt;Button title="Connect" onPress={() =&gt; {/* Add connection logic */}} /&gt;
    &lt;/View&gt;
    ); }; export default App;

    Next Steps

    1. Data Logging: Store data on a cloud server or local storage for long-term tracking.
    2. Visualization: Create graphs to visualize progress over time.
    3. User Interface: Improve the mobile app interface for better user experience.
  • Blog Platform with Custom CMS

    Step 1: Set Up the Project


    Blog Platform with Custom CMS

    Step 1: Set Up the Project

    1. Initialize your project:
    mkdir custom-blog cd custom-blog npm init -y
    1. Install necessary packages:
    npm install express mongoose body-parser ejs

    Step 2: Create Basic Folder Structure

    
    
    
    
    

    Step 3: Set Up the MongoDB Connection

    Create a new file named app.js and set up the Express app with MongoDB:

    javascriptCopy code// app.js
    const express = require('express');
    const mongoose = require('mongoose');
    const bodyParser = require('body-parser');
    const postRoutes = require('./routes/posts');

    const app = express();

    // Connect to MongoDB
    mongoose.connect('mongodb://localhost:27017/custom-blog', {
    useNewUrlParser: true,
    useUnifiedTopology: true
    });

    // Middleware
    app.set('view engine', 'ejs');
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static('public'));

    // Routes
    app.use('/posts', postRoutes);

    app.get('/', (req, res) => {
    res.redirect('/posts');
    });

    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
    });
    

    Step 4: Create the Post Model

    Create a file named Post.js inside the models directory:

    javascriptCopy code// models/Post.js
    const mongoose = require('mongoose');

    const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: String, required: true },
    createdAt: { type: Date, default: Date.now }
    });

    module.exports = mongoose.model('Post', postSchema);
    

    Step 5: Set Up Routes for Posts

    Create a file named posts.js inside the routes directory:

    javascriptCopy code// routes/posts.js
    const express = require('express');
    const Post = require('../models/Post');
    const router = express.Router();

    // Get all posts
    router.get('/', async (req, res) => {
    const posts = await Post.find();
    res.render('index', { posts });
    });

    // Create a new
    1. Initialize your project:
    mkdir custom-blog cd custom-blog npm init -y
    1. Install necessary packages:
    npm install express mongoose body-parser ejs

    Step 2: Create Basic Folder Structure

    plaintextCopy codecustom-blog/
    │
    ├── models/
    │   └── Post.js
    ├── routes/
    │   └── posts.js
    ├── views/
    │   ├── index.ejs
    │   └── post.ejs
    ├── public/
    │   └── styles.css
    ├── app.js
    └── package.json
    

    Step 3: Set Up the MongoDB Connection

    Create a new file named app.js and set up the Express app with MongoDB:

    javascriptCopy code// app.js
    const express = require('express');
    const mongoose = require('mongoose');
    const bodyParser = require('body-parser');
    const postRoutes = require('./routes/posts');
    
    const app = express();
    
    // Connect to MongoDB
    mongoose.connect('mongodb://localhost:27017/custom-blog', {
    
    useNewUrlParser: true,
    useUnifiedTopology: true
    }); // Middleware app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('public')); // Routes app.use('/posts', postRoutes); app.get('/', (req, res) => {
    res.redirect('/posts');
    }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
    });

    Step 4: Create the Post Model

    Create a file named Post.js inside the models directory:

    javascriptCopy code// models/Post.js
    const mongoose = require('mongoose');
    
    const postSchema = new mongoose.Schema({
    
    title: { type: String, required: true },
    content: { type: String, required: true },
    createdAt: { type: Date, default: Date.now }
    }); module.exports = mongoose.model('Post', postSchema);

    Step 5: Set Up Routes for Posts

    Create a file named posts.js inside the routes directory:

    javascriptCopy code// routes/posts.js
    const express = require('express');
    const Post = require('../models/Post');
    const router = express.Router();
    
    // Get all posts
    router.get('/', async (req, res) => {
    
    const posts = await Post.find();
    res.render('index', { posts });
    }); // Create a new post router.get('/new', (req, res) => {
    res.render('post', { post: {} });
    }); router.post('/', async (req, res) => {
    const { title, content } = req.body;
    const post = new Post({ title, content });
    await post.save();
    res.redirect('/posts');
    }); // View a single post router.get('/:id', async (req, res) => {
    const post = await Post.findById(req.params.id);
    res.render('post', { post });
    }); module.exports = router;

    Step 6: Create Views

    index.ejs

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Blog&lt;/title&gt;
    &lt;link rel="stylesheet" href="/styles.css"&gt;
    </head> <body>
    &lt;h1&gt;Blog Posts&lt;/h1&gt;
    &lt;a href="/posts/new"&gt;Create New Post&lt;/a&gt;
    &lt;ul&gt;
        &lt;% posts.forEach(post =&gt; { %&gt;
            &lt;li&gt;
                &lt;a href="/posts/&lt;%= post._id %&gt;"&gt;&lt;%= post.title %&gt;&lt;/a&gt;
            &lt;/li&gt;
        &lt;% }) %&gt;
    &lt;/ul&gt;
    </body> </html>

    post.ejs

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;&lt;%= post.title || 'New Post' %&gt;&lt;/title&gt;
    </head> <body>
    &lt;h1&gt;&lt;%= post.title || 'Create a New Post' %&gt;&lt;/h1&gt;
    &lt;form action="/posts&lt;%= post._id ? '/' + post._id : '' %&gt;" method="POST"&gt;
        &lt;input type="text" name="title" placeholder="Title" value="&lt;%= post.title %&gt;" required&gt;
        &lt;textarea name="content" placeholder="Content" required&gt;&lt;%= post.content %&gt;&lt;/textarea&gt;
        &lt;button type="submit"&gt;Save Post&lt;/button&gt;
    &lt;/form&gt;
    &lt;a href="/posts"&gt;Back to posts&lt;/a&gt;
    </body> </html>

    Step 7: Add Basic Styling

    Create a file named styles.css inside the public directory:

    cssCopy code/* public/styles.css */
    body {
    
    font-family: Arial, sans-serif;
    } h1 {
    color: #333;
    } a {
    text-decoration: none;
    color: blue;
    } ul {
    list-style: none;
    padding: 0;
    } li {
    margin: 10px 0;
    }

    Step 8: Run Your Application

    1. Start your MongoDB server (if you’re using a local instance):bashCopy codemongod
    2. Run your Express app:bashCopy codenode app.js
  • Event Management System

    Prerequisites

    Make sure you have the following installed:

    • Python (3.x)
    • Flask
    • SQLite (or any database of your choice)

    You can install Flask using pip:

    pip install Flask
    

    Directory Structure

    event_management_system/
    │
    ├── app.py
    ├── templates/
    │   ├── base.html
    │   ├── event_list.html
    │   └── event_form.html
    └── static/
    
    └── style.css

    Code Implementation

    1. app.py

    This is the main application file.

    from flask import Flask, render_template, redirect, url_for, request
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///events.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    class Event(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(200), nullable=False)
    date = db.Column(db.String(20), nullable=False)
    def __repr__(self):
        return f'&lt;Event {self.title}>'
    @app.route('/') def index():
    events = Event.query.all()
    return render_template('event_list.html', events=events)
    @app.route('/event/new', methods=['GET', 'POST']) def new_event():
    if request.method == 'POST':
        title = request.form&#91;'title']
        description = request.form&#91;'description']
        date = request.form&#91;'date']
        new_event = Event(title=title, description=description, date=date)
        db.session.add(new_event)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('event_form.html')
    @app.route('/event/edit/<int:event_id>', methods=['GET', 'POST']) def edit_event(event_id):
    event = Event.query.get_or_404(event_id)
    if request.method == 'POST':
        event.title = request.form&#91;'title']
        event.description = request.form&#91;'description']
        event.date = request.form&#91;'date']
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('event_form.html', event=event)
    @app.route('/event/delete/<int:event_id>', methods=['POST']) def delete_event(event_id):
    event = Event.query.get_or_404(event_id)
    db.session.delete(event)
    db.session.commit()
    return redirect(url_for('index'))
    if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

    2. HTML Templates

    Base Template (templates/base.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Event Management System&lt;/title>
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head> <body>
    &lt;div class="container">
        &lt;h1>Event Management System&lt;/h1>
        &lt;nav>
            &lt;a href="{{ url_for('index') }}">Home&lt;/a>
            &lt;a href="{{ url_for('new_event') }}">Create Event&lt;/a>
        &lt;/nav>
        {% block content %}{% endblock %}
    &lt;/div>
    </body> </html>

    Event List Template (templates/event_list.html)

    {% extends 'base.html' %}
    
    {% block content %}
    
    &lt;h2>Event List&lt;/h2>
    &lt;ul>
        {% for event in events %}
            &lt;li>
                &lt;strong>{{ event.title }}&lt;/strong> - {{ event.date }}
                &lt;form action="{{ url_for('delete_event', event_id=event.id) }}" method="POST" style="display:inline;">
                    &lt;button type="submit">Delete&lt;/button>
                &lt;/form>
                &lt;a href="{{ url_for('edit_event', event_id=event.id) }}">Edit&lt;/a>
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    {% endblock %}

    Event Form Template (templates/event_form.html)

    htmlCopy code{% extends 'base.html' %}
    
    {% block content %}
    
    &lt;h2&gt;{% if event %}Edit Event{% else %}New Event{% endif %}&lt;/h2&gt;
    &lt;form method="POST"&gt;
        &lt;label for="title"&gt;Title:&lt;/label&gt;
        &lt;input type="text" name="title" required value="{{ event.title if event else '' }}"&gt;
        &lt;label for="description"&gt;Description:&lt;/label&gt;
        &lt;input type="text" name="description" required value="{{ event.description if event else '' }}"&gt;
        &lt;label for="date"&gt;Date:&lt;/label&gt;
        &lt;input type="text" name="date" required value="{{ event.date if event else '' }}"&gt;
        &lt;button type="submit"&gt;{% if event %}Update{% else %}Create{% endif %}&lt;/button&gt;
    &lt;/form&gt;
    &lt;a href="{{ url_for('index') }}"&gt;Back to Event List&lt;/a&gt;
    {% endblock %}

    3. Basic CSS (optional)

    You can add some basic styling in static/style.css.

    body {
    
    font-family: Arial, sans-serif;
    margin: 20px;
    } .container {
    max-width: 800px;
    margin: auto;
    } nav a {
    margin-right: 15px;
    }

    Running the Application

    1. Navigate to the project directory.
    2. Run the application:
    python app.py
    
    1. Open your web browser and go to http://127.0.0.1:5000.
  • Recipe Sharing Community

    Prerequisites

    Make sure you have the following installed:

    • Python
    • Flask
    • SQLite

    You can install Flask using pip:

    pip install Flask
    

    Basic Structure

    1. Project Directory:
    recipe_sharing/ ├── app.py ├── templates/ │ ├── index.html │ ├── recipe.html │ └── submit.html └── recipes.db
    1. Database Setup: Create a SQLite database to store recipes. You can do this with the following script:pythonCopy code# create_db.py import sqlite3 conn = sqlite3.connect('recipes.db') c = conn.cursor() c.execute(''' CREATE TABLE recipes ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, ingredients TEXT NOT NULL, instructions TEXT NOT NULL ) ''') conn.commit() conn.close() Run this script once to create your database:bashCopy codepython create_db.py
    2. Flask Application (app.py):
    pythonCopy codefrom flask import Flask, render_template, request, redirect import sqlite3 app = Flask(__name__) def get_db_connection(): conn = sqlite3.connect('recipes.db') conn.row_factory = sqlite3.Row return conn @app.route('/') def index(): conn = get_db_connection() recipes = conn.execute('SELECT * FROM recipes').fetchall() conn.close() return render_template('index.html', recipes=recipes) @app.route('/recipe/<int:recipe_id>') def recipe(recipe_id): conn = get_db_connection() recipe = conn.execute('SELECT * FROM recipes WHERE id = ?', (recipe_id,)).fetchone() conn.close() return render_template('recipe.html', recipe=recipe) @app.route('/submit', methods=('GET', 'POST')) def submit(): if request.method == 'POST': title = request.form['title'] ingredients = request.form['ingredients'] instructions = request.form['instructions'] conn = get_db_connection() conn.execute('INSERT INTO recipes (title, ingredients, instructions) VALUES (?, ?, ?)', (title, ingredients, instructions)) conn.commit() conn.close() return redirect('/') return render_template('submit.html') if __name__ == '__main__': app.run(debug=True)
    1. HTML Templates:
      • templates/index.html:
    htmlCopy code<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Recipe Sharing Community</title> </head> <body> <h1>Recipe Sharing Community</h1> <a href="/submit">Submit a Recipe</a> <ul> {% for recipe in recipes %} <li><a href="/recipe/{{ recipe['id'] }}">{{ recipe['title'] }}</a></li> {% endfor %} </ul> </body> </html>
    1. templates/recipe.html:
    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ recipe['title'] }}</title> </head> <body> <h1>{{ recipe['title'] }}</h1> <h2>Ingredients</h2> <p>{{ recipe['ingredients'] }}</p> <h2>Instructions</h2> <p>{{ recipe['instructions'] }}</p> <a href="/">Back to Home</a> </body> </html>
    1. templates/submit.html:
    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Submit a Recipe</title> </head> <body> <h1>Submit a Recipe</h1> <form method="post"> <label for="title">Title:</label> <input type="text" id="title" name="title" required> <label for="ingredients">Ingredients:</label> <textarea id="ingredients" name="ingredients" required></textarea> <label for="instructions">Instructions:</label> <textarea id="instructions" name="instructions" required></textarea> <button type="submit">Submit</button> </form> <a href="/">Back to Home</a> </body> </html>

    Running the Application

    1. Ensure your SQLite database is created with the create_db.py script.
    2. Run your Flask application:bashCopy codepython app.py
    3. Open your web browser and navigate to http://127.0.0.1:5000 to access your recipe-sharing community!
  • Job Board

    HTML (index.html)

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    &lt;title&gt;Job Board&lt;/title&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;Job Board&lt;/h1&gt;
        &lt;form id="jobForm"&gt;
            &lt;input type="text" id="jobTitle" placeholder="Job Title" required&gt;
            &lt;input type="text" id="company" placeholder="Company" required&gt;
            &lt;textarea id="description" placeholder="Job Description" required&gt;&lt;/textarea&gt;
            &lt;button type="submit"&gt;Add Job&lt;/button&gt;
        &lt;/form&gt;
        &lt;div id="jobList" class="job-list"&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    CSS (styles.css)

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    } h1 {
    text-align: center;
    } form {
    display: flex;
    flex-direction: column;
    } input, textarea {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    } button {
    padding: 10px;
    background: #5cb85c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    } button:hover {
    background: #4cae4c;
    } .job {
    padding: 15px;
    border: 1px solid #ddd;
    margin-top: 10px;
    border-radius: 4px;
    background: #fafafa;
    } .job h3 {
    margin: 0;
    } .job p {
    margin: 5px 0;
    }

    JavaScript (script.js)

    javascriptCopy codedocument.getElementById('jobForm').addEventListener('submit', function(event) {
    
    event.preventDefault();
    const jobTitle = document.getElementById('jobTitle').value;
    const company = document.getElementById('company').value;
    const description = document.getElementById('description').value;
    addJob(jobTitle, company, description);
    // Clear form fields
    this.reset();
    }); function addJob(title, company, description) {
    const jobList = document.getElementById('jobList');
    const jobDiv = document.createElement('div');
    jobDiv.className = 'job';
    jobDiv.innerHTML = `
        &lt;h3&gt;${title}&lt;/h3&gt;
        &lt;p&gt;&lt;strong&gt;Company:&lt;/strong&gt; ${company}&lt;/p&gt;
        &lt;p&gt;${description}&lt;/p&gt;
    `;
    jobList.appendChild(jobDiv);
    }

    How to Run the Project

    1. Create the Files: Create three files named index.html, styles.css, and script.js in a folder.
    2. Copy the Code: Copy the respective code into each file.
    3. Open in Browser: Open index.html in a web browser to view your job board.

    Features You Can Add

    • Data Persistence: Use local storage or a backend service (like Firebase or a simple Node.js server) to save job postings.
    • Search Functionality: Implement a search bar to filter job postings.
    • Categories or Tags: Add the ability to categorize jobs.
    • Responsive Design: Enhance the CSS for better responsiveness on mobile devices.
  • Social Media Dashboard

    Prerequisites

    1. Python 3.x: Ensure Python is installed.
    2. Flask: You can install it using pip:bashCopy codepip install Flask
    3. Flask-CORS: For cross-origin resource sharing:bashCopy codepip install Flask-CORS

    Step 1: Setting Up the Flask Backend

    Create a file named app.py for the backend.

    pythonCopy codefrom flask import Flask, jsonify
    from flask_cors import CORS
    import random
    
    app = Flask(__name__)
    CORS(app)
    
    # Dummy data generation
    def generate_data():
    
    return {
        "likes": random.randint(100, 1000),
        "shares": random.randint(50, 500),
        "comments": random.randint(10, 100),
        "followers": random.randint(1000, 5000),
    }
    @app.route('/api/metrics', methods=['GET']) def get_metrics():
    metrics = generate_data()
    return jsonify(metrics)
    if __name__ == '__main__':
    app.run(debug=True)

    Step 2: Creating the Frontend

    Create a folder named static and add an index.html file inside it.

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Social Media Dashboard&lt;/title&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/chart.js"&gt;&lt;/script&gt;
    </head> <body>
    &lt;h1&gt;Social Media Dashboard&lt;/h1&gt;
    &lt;canvas id="myChart" width="400" height="200"&gt;&lt;/canvas&gt;
    
    &lt;script&gt;
        async function fetchMetrics() {
            const response = await fetch('http://127.0.0.1:5000/api/metrics');
            const data = await response.json();
            return data;
        }
        async function renderChart() {
            const data = await fetchMetrics();
            const ctx = document.getElementById('myChart').getContext('2d');
            const myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: &#91;'Likes', 'Shares', 'Comments', 'Followers'],
                    datasets: &#91;{
                        label: 'Engagement Metrics',
                        data: &#91;data.likes, data.shares, data.comments, data.followers],
                        backgroundColor: &#91;
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)',
                            'rgba(255, 99, 132, 0.2)'
                        ],
                        borderColor: &#91;
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)',
                            'rgba(255, 99, 132, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        renderChart();
    &lt;/script&gt;
    </body> </html>

    Step 3: Running the Application

    1. Open your terminal and navigate to the folder where app.py is located.
    2. Run the Flask application:bashCopy codepython app.py
    3. Open a web browser and go to http://127.0.0.1:5000/static/index.html.

    Explanation

    • Backend: The Flask app serves a simple API endpoint /api/metrics that returns random engagement metrics in JSON format.
    • Frontend: The HTML file fetches data from the Flask API and uses Chart.js to render a bar chart of the metrics.

    Extending the Dashboard

    • Data Source: Replace the random data generation with real data from social media APIs (e.g., Twitter, Facebook).
    • Styling: Use CSS frameworks like Bootstrap to style the dashboard.
    • More Features: Add user authentication, historical data tracking, and real-time updates.
  • E-Learning Platform

    Prerequisites

    • Python 3.x
    • Flask
    • SQLite (for simplicity, though you can use any database)
    • HTML/CSS knowledge

    Project Structure

    arduinoCopy codee_learning/
    │
    ├── app.py
    ├── templates/
    │   ├── base.html
    │   ├── index.html
    │   ├── login.html
    │   ├── register.html
    │   └── courses.html
    ├── static/
    │   └── style.css
    └── database.db
    

    Step 1: Install Flask

    Make sure you have Flask installed:

    bashCopy codepip install Flask
    

    Step 2: Create app.py

    This file will contain the main application logic.

    pythonCopy codefrom flask import Flask, render_template, redirect, url_for, request, session
    from flask_sqlalchemy import SQLAlchemy
    from werkzeug.security import generate_password_hash, check_password_hash
    
    app = Flask(__name__)
    app.secret_key = 'your_secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    db = SQLAlchemy(app)
    
    # Database model
    class User(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.String(500), nullable=False)
    db.create_all() # Routes @app.route('/') def index():
    return render_template('index.html')
    @app.route('/login', methods=['GET', 'POST']) def login():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = request.form&#91;'password']
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            session&#91;'user_id'] = user.id
            return redirect(url_for('courses'))
    return render_template('login.html')
    @app.route('/register', methods=['GET', 'POST']) def register():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = generate_password_hash(request.form&#91;'password'], method='sha256')
        new_user = User(username=username, password=password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template('register.html')
    @app.route('/courses') def courses():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    courses = Course.query.all()
    return render_template('courses.html', courses=courses)
    if __name__ == '__main__':
    app.run(debug=True)

    Step 3: Create HTML Templates

    base.html

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"&gt;
    &lt;title&gt;E-Learning Platform&lt;/title&gt;
    </head> <body>
    &lt;header&gt;
        &lt;h1&gt;E-Learning Platform&lt;/h1&gt;
        &lt;nav&gt;
            &lt;a href="{{ url_for('index') }}"&gt;Home&lt;/a&gt;
            {% if 'user_id' not in session %}
                &lt;a href="{{ url_for('login') }}"&gt;Login&lt;/a&gt;
                &lt;a href="{{ url_for('register') }}"&gt;Register&lt;/a&gt;
            {% else %}
                &lt;a href="{{ url_for('courses') }}"&gt;Courses&lt;/a&gt;
                &lt;a href="{{ url_for('logout') }}"&gt;Logout&lt;/a&gt;
            {% endif %}
        &lt;/nav&gt;
    &lt;/header&gt;
    &lt;main&gt;
        {% block content %}{% endblock %}
    &lt;/main&gt;
    </body> </html>

    index.html

    htmlCopy code{% extends 'base.html' %}
    {% block content %}
    <h2>Welcome to the E-Learning Platform</h2>
    <p>Your journey of learning starts here!</p>
    {% endblock %}
    

    login.html

    htmlCopy code{% extends 'base.html' %}
    {% block content %}
    <h2>Login</h2>
    <form method="POST">
    
    &lt;input type="text" name="username" placeholder="Username" required&gt;
    &lt;input type="password" name="password" placeholder="Password" required&gt;
    &lt;button type="submit"&gt;Login&lt;/button&gt;
    </form> {% endblock %}

    register.html

    htmlCopy code{% extends 'base.html' %}
    {% block content %}
    <h2>Register</h2>
    <form method="POST">
    
    &lt;input type="text" name="username" placeholder="Username" required&gt;
    &lt;input type="password" name="password" placeholder="Password" required&gt;
    &lt;button type="submit"&gt;Register&lt;/button&gt;
    </form> {% endblock %}

    courses.html

    htmlCopy code{% extends 'base.html' %}
    {% block content %}
    <h2>Available Courses</h2>
    <ul>
    
    {% for course in courses %}
        &lt;li&gt;{{ course.title }}: {{ course.description }}&lt;/li&gt;
    {% endfor %}
    </ul> {% endblock %}

    Step 4: Create CSS File

    style.css

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    } header {
    background: #333;
    color: #fff;
    padding: 10px 0;
    } nav a {
    color: #fff;
    margin: 0 15px;
    text-decoration: none;
    } h2 {
    color: #333;
    } form {
    display: flex;
    flex-direction: column;
    max-width: 300px;
    }

    Step 5: Run the Application

    1. Initialize the database:bashCopy codepython Then run:pythonCopy codefrom app import db db.create_all() exit()
    2. Start the Flask app:bashCopy codepython app.py
    3. Open your browser and go to http://127.0.0.1:5000.
  • Personal Finance Tracker in Python

    Here’s a basic implementation:

    pythonCopy codeclass FinanceTracker:
    
    def __init__(self):
        self.income = &#91;]
        self.expenses = &#91;]
    def add_income(self, amount, source):
        self.income.append({'amount': amount, 'source': source})
        print(f"Added income: ${amount} from {source}")
    def add_expense(self, amount, category):
        self.expenses.append({'amount': amount, 'category': category})
        print(f"Added expense: ${amount} for {category}")
    def total_income(self):
        return sum(item&#91;'amount'] for item in self.income)
    def total_expenses(self):
        return sum(item&#91;'amount'] for item in self.expenses)
    def balance(self):
        return self.total_income() - self.total_expenses()
    def summary(self):
        print("\n--- Financial Summary ---")
        print(f"Total Income: ${self.total_income()}")
        print(f"Total Expenses: ${self.total_expenses()}")
        print(f"Balance: ${self.balance()}\n")
        print("Income Details:")
        for item in self.income:
            print(f"- ${item&#91;'amount']} from {item&#91;'source']}")
        print("Expense Details:")
        for item in self.expenses:
            print(f"- ${item&#91;'amount']} for {item&#91;'category']}")
    def main():
    tracker = FinanceTracker()
    while True:
        print("1. Add Income")
        print("2. Add Expense")
        print("3. Show Summary")
        print("4. Exit")
        choice = input("Choose an option: ")
        if choice == '1':
            amount = float(input("Enter income amount: "))
            source = input("Enter income source: ")
            tracker.add_income(amount, source)
        elif choice == '2':
            amount = float(input("Enter expense amount: "))
            category = input("Enter expense category: ")
            tracker.add_expense(amount, category)
        elif choice == '3':
            tracker.summary()
        elif choice == '4':
            print("Exiting the finance tracker.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    How to Use This Tracker

    1. Set Up Python Environment: Ensure you have Python installed on your machine. You can download it from python.org.
    2. Run the Code: Copy the code into a Python file (e.g., finance_tracker.py) and run it using the command:bashCopy codepython finance_tracker.py
    3. Add Income and Expenses: Follow the prompts to add income and expenses. You can also view a summary of your finances.
    4. Exit: Choose the exit option when you’re done.