Thursday, May 8, 2025

IoT (Internet of Things) Automation - Smart Energy Usage Tracker

 


Notes:

  • Problem Solved: Logs and analyzes power usage from smart meters.

  • Customization Benefits: Track per-device energy and set alerts.

  • Further Adoption: Sync to cloud dashboards or billing tools.

Python Code:


import random
import csv
from datetime import datetime

def simulate_energy_reading():
    return round(random.uniform(0.1, 2.5), 2)  # kWh usage

with open("energy_log.csv", "a", newline="") as f:
    writer = csv.writer(f)
    usage = simulate_energy_reading()
    timestamp = datetime.now().isoformat()
    writer.writerow([timestamp, usage])
    print(f"Logged: {timestamp} - {usage} kWh")

IoT (Internet of Things) Automation - RFID-Based Access Control

 


Notes:

  • Problem Solved: Authenticates user entry via RFID tags for security.

  • Customization Benefits: Maintain a dynamic list of allowed users.

  • Further Adoption: Integrate with cameras or audit logs.

Python Code:


AUTHORIZED_TAGS = {"1234567890ABC", "AABBCCDDEEFF"}

def read_rfid():
    return input("Scan RFID Tag: ")

def check_access(tag):
    if tag in AUTHORIZED_TAGS:
        print("✅ Access Granted")
    else:
        print("❌ Access Denied")

tag = read_rfid()
check_access(tag)

IoT (Internet of Things) Automation - Real-Time Air Quality Monitor

 


Notes:

  • Problem Solved: Continuously monitors air quality from a sensor and triggers alerts.

  • Customization Benefits: Adjust thresholds or integrate SMS/email alerts.

  • Further Adoption: Push data to cloud dashboards or IoT edge devices.

Python Code:


import random
import time

def read_sensor():
    return random.randint(0, 500)  # Simulated AQI reading

def check_air_quality(aqi):
    if aqi > 150:
        print("⚠️ Poor air quality! Consider ventilation.")
    elif aqi > 100:
        print("🟡 Moderate air quality.")
    else:
        print("🟢 Good air quality.")

while True:
    aqi = read_sensor()
    print(f"Current AQI: {aqi}")
    check_air_quality(aqi)
    time.sleep(10)

IoT (Internet of Things) Automation - Smart Irrigation System

 


Notes:

  • Problem Solved: Activates irrigation based on soil moisture data and weather forecast.

  • Customization Benefits: Calibrate for crop types or integrate with APIs.

  • Further Adoption: Link with physical relay systems and IoT dashboards.

Python Code:


import requests

def should_irrigate(moisture_level, weather_api_key):
    if moisture_level > 30:
        return False
    forecast = requests.get(f"https://api.weatherapi.com/v1/forecast.json?key={weather_api_key}&q=your_city&days=1").json()
    rain_chance = forecast['forecast']['forecastday'][0]['day']['daily_chance_of_rain']
    return rain_chance < 50

# Example usage
if should_irrigate(moisture_level=25, weather_api_key='your_api_key'):
    print("Activate irrigation.")
else:
    print("Irrigation not needed.")

IoT (Internet of Things) Automation - MQTT Sensor Data Logger

 


Notes:

  • Problem Solved: Collects real-time data from IoT sensors via MQTT and stores it locally.

  • Customization Benefits: Add support for multiple topics or cloud sync.

  • Further Adoption: Integrate with InfluxDB, Grafana, or AWS IoT.

Python Code:


import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    with open('sensor_log.csv', 'a') as f:
        f.write(f"{msg.topic},{msg.payload.decode()}\n")
    print(f"Logged: {msg.topic} -> {msg.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.subscribe("iot/temperature")

print("Listening for sensor data...")
client.loop_forever()

IoT (Internet of Things) Automation - Smart Thermostat Control

 


Notes:

  • Problem Solved: Automatically adjusts temperature based on time of day and occupancy.

  • Customization Benefits: Set your own temperature profiles or integrate weather data.

  • Further Adoption: Connect to smart home systems (Home Assistant, OpenHAB).

Python Code:


from datetime import datetime

def get_temperature_schedule(hour, is_home):
    if not is_home:
        return 18  # Eco mode
    if 6 <= hour < 9:
        return 22  # Morning
    elif 9 <= hour < 17:
        return 20  # Daytime
    elif 17 <= hour < 23:
        return 23  # Evening
    else:
        return 19  # Night

# Example usage
now = datetime.now()
temperature = get_temperature_schedule(now.hour, is_home=True)
print(f"Set thermostat to {temperature}°C")

Web Scraping and Data Extraction - Website Change Tracker

 


Notes:

  • Problem Solved: Monitors a webpage for any HTML/textual changes over time.

  • Customization Benefits: Set up alerts or track competitor website updates.

  • Further Adoption: Integrate with Slack/email APIs to send alerts.

Python Code:


import hashlib
import requests
import time

def get_page_hash(url):
    response = requests.get(url)
    return hashlib.sha256(response.text.encode()).hexdigest()

def track_changes(url, interval=60):
    old_hash = get_page_hash(url)
    print("Monitoring started...")
    while True:
        time.sleep(interval)
        new_hash = get_page_hash(url)
        if new_hash != old_hash:
            print("Website content changed!")
            break
        else:
            print("No change detected...")

# Example usage
# track_changes("https://example.com", interval=300)

Web Scraping and Data Extraction - Social Media Hashtag Monitor

 


Notes:

  • Problem Solved: Scrapes Twitter for real-time hashtag mentions.

  • Customization Benefits: Track campaigns, analyze sentiment, or discover influencers.

  • Further Adoption: Store in a database, analyze sentiment, or trigger alerts.

Python Code:


import snscrape.modules.twitter as sntwitter

def get_tweets_by_hashtag(hashtag, max_tweets=50):
    tweets = []
    for i, tweet in enumerate(sntwitter.TwitterHashtagScraper(hashtag).get_items()):
        if i >= max_tweets:
            break
        tweets.append({'user': tweet.user.username, 'content': tweet.content})
    return tweets

# Example usage
tweets = get_tweets_by_hashtag("AI")
for t in tweets[:5]:
    print(f"{t['user']}: {t['content'][:80]}")


Web Scraping and Data Extraction - PDF Invoice Parser

 


Notes:

  • Problem Solved: Extracts structured data (like totals, dates) from PDF invoices.

  • Customization Benefits: Works with invoice templates or billing automation systems.

  • Further Adoption: Connect to accounting software or ERP platforms.

Python Code:


import pdfplumber

def extract_invoice_data(pdf_path):
    with pdfplumber.open(pdf_path) as pdf:
        text = pdf.pages[0].extract_text()
    lines = text.split('\n')
    data = {}
    for line in lines:
        if "Invoice Number" in line:
            data['invoice_number'] = line.split(":")[-1].strip()
        elif "Total Amount" in line:
            data['total_amount'] = line.split(":")[-1].strip()
        elif "Date" in line:
            data['date'] = line.split(":")[-1].strip()
    return data

# Example usage
# print(extract_invoice_data("invoice_sample.pdf"))

Web Scraping and Data Extraction - Real-Time News Extractor

 


Notes:

  • Problem Solved: Extracts headlines from news websites in real time.

  • Customization Benefits: Filter by topic or sentiment, or push to dashboards.

  • Further Adoption: Use for trend analysis, sentiment detection, or alert systems.

Python Code:


import feedparser

def get_news_rss(feed_url):
    feed = feedparser.parse(feed_url)
    return [{'title': entry.title, 'link': entry.link} for entry in feed.entries]

rss_url = "http://feeds.bbci.co.uk/news/rss.xml"
headlines = get_news_rss(rss_url)
for news in headlines[:5]:
    print(news['title'], "-", news['link'])

Web Scraping and Data Extraction - Job Listing Aggregator

 


Notes:

  • Problem Solved: Extracts job postings from multiple job boards.

  • Customization Benefits: Filter by keywords, location, or salary.

  • Further Adoption: Feed into job boards, CRMs, or recruitment analytics platforms.

Python Code:


import requests
from bs4 import BeautifulSoup

def scrape_indeed_jobs(query, location):
    base_url = "https://www.indeed.com/jobs"
    params = {"q": query, "l": location}
    response = requests.get(base_url, params=params)
    soup = BeautifulSoup(response.text, 'html.parser')
    jobs = []
    for job_card in soup.select('.result'):
        title = job_card.select_one('h2.jobTitle').text.strip()
        company = job_card.select_one('.companyName').text.strip()
        jobs.append({'title': title, 'company': company})
    return jobs

print(scrape_indeed_jobs("data analyst", "New York, NY"))

Web Scraping and Data Extraction - E-commerce Price Tracker

 


Notes:

  • Problem Solved: Tracks product prices across e-commerce sites (e.g., Amazon, Flipkart).

  • Customization Benefits: Monitor competitors, automate pricing strategies, or trigger alerts.

  • Further Adoption: Integrate with BI tools, pricing engines, or push notifications.

Python Code:


import requests
from bs4 import BeautifulSoup

def get_amazon_price(product_url, headers):
    response = requests.get(product_url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    title = soup.find(id="productTitle").get_text(strip=True)
    price = soup.find('span', {'class': 'a-offscreen'}).get_text(strip=True)
    return {'title': title, 'price': price}

# Example usage
headers = {'User-Agent': 'Mozilla/5.0'}
url = 'https://www.amazon.com/dp/B08N5WRWNW'  # Example product
print(get_amazon_price(url, headers))

Customer Relationship Management (CRM) - Voice of Customer Analyzer

 


Notes:

  • Problem Solved: Performs sentiment analysis on customer reviews or NPS responses.

  • Customization Benefits: Tailor sentiment thresholds or keywords per product.

  • Further Adoption: Feed results into product improvement or alerting systems.

Python Code:


from textblob import TextBlob
import pandas as pd

def analyze_sentiment(text):
    return TextBlob(text).sentiment.polarity

feedback_df = pd.read_csv("customer_feedback.csv")  # Column: 'feedback'
feedback_df['sentiment_score'] = feedback_df['feedback'].apply(analyze_sentiment)

# Categorize feedback
feedback_df['sentiment_label'] = feedback_df['sentiment_score'].apply(
    lambda x: 'Positive' if x > 0.1 else ('Negative' if x < -0.1 else 'Neutral')
)
print(feedback_df[['feedback', 'sentiment_label']])

Customer Relationship Management (CRM) - Sales Forecasting Tool

 


Notes:

  • Problem Solved: Predicts future sales based on pipeline data and historical trends.

  • Customization Benefits: Incorporate external data like seasonality or macroeconomic factors.

  • Further Adoption: Display results in BI dashboards or CRM widgets.

Python Code:


import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df = pd.read_csv("sales_pipeline.csv")  # Columns: 'month', 'opportunities', 'closed_deals'
X = df[['opportunities']]
y = df['closed_deals']

model = LinearRegression()
model.fit(X, y)

# Forecast next month's sales
next_opps = pd.DataFrame({'opportunities': [150]})
forecast = model.predict(next_opps)
print(f"Predicted sales for next month: {forecast[0]:.2f}")

Customer Relationship Management (CRM) - Support Ticket Classifier

 


Notes:

  • Problem Solved: Automatically classifies incoming support tickets into categories for efficient triage.

  • Customization Benefits: Train it on your historical ticket data for improved accuracy.

  • Further Adoption: Route classified tickets into tools like Zendesk or Freshdesk.

Python Code:


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import pandas as pd

# Sample data: 'ticket_text', 'category'
df = pd.read_csv("support_tickets.csv")
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['ticket_text'])
y = df['category']

model = MultinomialNB()
model.fit(X, y)

# Predict new tickets
new_tickets = ["I need a refund for my purchase", "System is down, can't login"]
X_new = vectorizer.transform(new_tickets)
predictions = model.predict(X_new)
print(list(zip(new_tickets, predictions)))

Customer Relationship Management (CRM) - Email Campaign Scheduler

 


Notes:

  • Problem Solved: Automates personalized email campaign delivery based on customer actions or lifecycle stage.

  • Customization Benefits: Integrate with customer segmentation or A/B testing engines.

  • Further Adoption: Plug into SendGrid, Mailchimp, or SMTP for live delivery.

Python Code:


import smtplib
from email.mime.text import MIMEText
import pandas as pd

def send_email(recipient, subject, body):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'crm@yourcompany.com'
    msg['To'] = recipient

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('crm@yourcompany.com', 'yourpassword')
        server.send_message(msg)

def schedule_campaign(csv_path):
    df = pd.read_csv(csv_path)
    for _, row in df.iterrows():
        subject = f"Special Offer for {row['first_name']}"
        body = f"Hi {row['first_name']},\n\nHere's something just for you: {row['offer']}\n\nBest,\nCRM Team"
        send_email(row['email'], subject, body)

# Usage
# schedule_campaign("email_campaign_data.csv")

Customer Relationship Management (CRM) - Customer Churn Predictor

 


Notes:

  • Problem Solved: Predicts which customers are likely to stop using your product/service.

  • Customization Benefits: Train the model with your own data for improved accuracy.

  • Further Adoption: Trigger proactive retention campaigns based on churn scores.

Python Code:


import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

df = pd.read_csv("customer_data.csv")  # Must include 'churned' column (1=yes, 0=no)
features = df.drop(columns=['customer_id', 'churned'])
target = df['churned']

X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2)
model = RandomForestClassifier()
model.fit(X_train, y_train)

# Predict churn
df['churn_probability'] = model.predict_proba(features)[:, 1]
print(df[['customer_id', 'churn_probability']].sort_values(by='churn_probability', ascending=False))

Customer Relationship Management (CRM) - Lead Scoring Engine

 


Notes:

  • Problem Solved: Automatically scores leads based on engagement and fit, prioritizing sales follow-ups.

  • Customization Benefits: Adjust scoring logic based on your customer persona or sales cycle.

  • Further Adoption: Integrate with email systems, web tracking, or CRM platforms like Salesforce or HubSpot.

Python Code:


import pandas as pd

def score_leads(df):
    def calculate_score(row):
        score = 0
        if row['industry'] in ['tech', 'finance']: score += 20
        if row['email_opened'] > 3: score += 10
        if row['website_visits'] > 5: score += 15
        if row['demo_requested']: score += 30
        return score

    df['lead_score'] = df.apply(calculate_score, axis=1)
    return df.sort_values(by='lead_score', ascending=False)

# Example
lead_data = pd.DataFrame([
    {'name': 'Alice', 'industry': 'tech', 'email_opened': 5, 'website_visits': 7, 'demo_requested': True},
    {'name': 'Bob', 'industry': 'retail', 'email_opened': 1, 'website_visits': 2, 'demo_requested': False}
])
print(score_leads(lead_data))

Human Resources Automation - Smart Job Description Generator

 


Notes:

  • Problem Solved: Dynamically creates job descriptions based on title, department, and responsibilities.

  • Customization Benefits: Tailor tone, language, or format.

  • Further Adoption: Integrate with posting systems or chatbots.

Python Code:


def generate_job_description(title, department, responsibilities):
    template = f"""
    Job Title: {title}
    Department: {department}

    Responsibilities:
    {'; '.join(responsibilities)}

    We are seeking a dedicated {title} to join our {department} team. This role involves {responsibilities[0].lower()} and more.
    """
    return template.strip()

job_desc = generate_job_description(
    title="Data Analyst",
    department="Business Intelligence",
    responsibilities=["Analyzing data trends", "Generating reports", "Collaborating with cross-functional teams"]
)

print(job_desc)

Human Resources Automation - Workforce Attrition Predictor

 


Notes:

  • Problem Solved: Predicts likelihood of employee resignation using machine learning.

  • Customization Benefits: Retrain model on your own HR data.

  • Further Adoption: Embed in dashboards or retention tools.

Python Code:


import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

df = pd.read_csv("employee_data.csv")  # Includes 'left_company' (1=yes, 0=no)
features = df.drop(columns=['employee_id', 'left_company'])
target = df['left_company']

X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
model = RandomForestClassifier()
model.fit(X_train, y_train)

# Predict attrition
predictions = model.predict(X_test)
print("Prediction Sample:", predictions[:5])

Human Resources Automation - Interview Feedback Aggregator

 


Notes:

  • Problem Solved: Aggregates qualitative interviewer feedback and scores candidates.

  • Customization Benefits: Change scoring logic or sentiment thresholds.

  • Further Adoption: Feed into candidate ranking or hiring decisions.

Python Code:


import pandas as pd
from textblob import TextBlob

feedback_data = pd.read_csv("interview_feedback.csv")  # Columns: candidate, feedback_text

def analyze_feedback(feedback):
    sentiment = TextBlob(feedback).sentiment.polarity
    return round(sentiment, 2)

feedback_data['Sentiment Score'] = feedback_data['feedback_text'].apply(analyze_feedback)
candidate_scores = feedback_data.groupby("candidate")['Sentiment Score'].mean().sort_values(ascending=False)
print(candidate_scores)

Human Resources Automation - Payroll Compliance Checker

 


Notes:

  • Problem Solved: Flags salary or hour inconsistencies based on labor laws.

  • Customization Benefits: Adjust rules per region or job role.

  • Further Adoption: Connect to payroll systems or accounting software.

Python Code:


import pandas as pd

df = pd.read_csv("employee_hours.csv")  # Columns: employee_id, hours_worked, salary

def check_compliance(row):
    hourly_rate = row['salary'] / row['hours_worked']
    if hourly_rate < 15:  # Example: $15/hr minimum wage
        return "Non-Compliant"
    return "Compliant"

df['Compliance Status'] = df.apply(check_compliance, axis=1)
print(df[['employee_id', 'Compliance Status']])

Human Resources Automation - Diversity Hiring Dashboard

 

Notes:

  • Problem Solved: Tracks diversity metrics in hiring pipelines.

  • Customization Benefits: Add filters for role, department, or hiring manager.

  • Further Adoption: Visualize using dashboards like Plotly Dash or Tableau.

Python Code:


import pandas as pd

data = pd.read_csv("hiring_data.csv")  # Columns: name, gender, ethnicity, stage
diversity_summary = data.groupby(['gender', 'ethnicity', 'stage']).size().unstack(fill_value=0)
print("Diversity Metrics by Hiring Stage:\n", diversity_summary)

Human Resources Automation - Resume Skill Extractor

 


Notes:

  • Problem Solved: Automates skill extraction from resumes to support faster candidate screening.

  • Customization Benefits: Adjust for specific job descriptions or keyword databases.

  • Further Adoption: Integrate with an ATS or recruitment chatbot for end-to-end automation.

Python Code:


import docx2txt
import spacy

nlp = spacy.load("en_core_web_sm")
SKILL_KEYWORDS = {"python", "excel", "project management", "machine learning", "communication", "leadership"}

def extract_skills_from_resume(file_path):
    text = docx2txt.process(file_path)
    doc = nlp(text.lower())
    found_skills = {token.text for token in doc if token.text in SKILL_KEYWORDS}
    return list(found_skills)

# Example usage
resume_file = "candidate_resume.docx"
skills = extract_skills_from_resume(resume_file)
print("Extracted Skills:", skills)

Tuesday, May 6, 2025

Supply Chain and Inventory Management – Shipment ETA Predictor

 


Notes:

  • Problem Solved: Predicts estimated time of arrival (ETA) for shipments based on carrier, distance, and historical data.

  • Benefits: Enhances planning accuracy and provides customers with reliable delivery expectations.

  • Adoption: Can be embedded in customer-facing shipment tracking portals or used internally.

Python Code:


import pandas as pd

from sklearn.linear_model import LinearRegression

import numpy as np


class ETAPredictor:

    def __init__(self, training_data):

        self.df = pd.DataFrame(training_data)

        self.model = LinearRegression()


    def train(self):

        X = self.df[['DistanceKm', 'CarrierRating']]

        y = self.df['DeliveryDays']

        self.model.fit(X, y)


    def predict_eta(self, distance_km, carrier_rating):

        input_data = np.array([[distance_km, carrier_rating]])

        return self.model.predict(input_data)[0]


# Sample historical data

data = [

    {'DistanceKm': 100, 'CarrierRating': 4.5, 'DeliveryDays': 2},

    {'DistanceKm': 300, 'CarrierRating': 4.0, 'DeliveryDays': 4},

    {'DistanceKm': 50, 'CarrierRating': 5.0, 'DeliveryDays': 1},

    {'DistanceKm': 400, 'CarrierRating': 3.5, 'DeliveryDays': 5},

]


predictor = ETAPredictor(data)

predictor.train()


# Predict ETA for a new shipment

eta = predictor.predict_eta(250, 4.3)

print(f"Predicted ETA (days): {round(eta, 2)}")


Supply Chain and Inventory Management – Backorder Management System

 


Notes:

  • Problem Solved: Automatically identifies and tracks backorders, alerting when items are replenished.

  • Benefits: Enhances customer satisfaction by reducing missed or delayed orders.

  • Adoption: Can be tied into order management systems for real-time backorder tracking.

Python Code:


import pandas as pd


class BackorderManager:

    def __init__(self, orders_df, inventory_df):

        self.orders = pd.DataFrame(orders_df)

        self.inventory = pd.DataFrame(inventory_df)


    def check_backorders(self):

        merged = pd.merge(self.orders, self.inventory, on='ProductID', how='left')

        merged['BackorderedQty'] = merged['OrderQty'] - merged['InStock']

        merged['BackorderedQty'] = merged['BackorderedQty'].apply(lambda x: max(0, x))

        return merged[['OrderID', 'ProductID', 'BackorderedQty']]


# Sample data

orders = [

    {'OrderID': 'O1', 'ProductID': 'P100', 'OrderQty': 50},

    {'OrderID': 'O2', 'ProductID': 'P101', 'OrderQty': 20},

    {'OrderID': 'O3', 'ProductID': 'P102', 'OrderQty': 10},

]


inventory = [

    {'ProductID': 'P100', 'InStock': 30},

    {'ProductID': 'P101', 'InStock': 25},

    {'ProductID': 'P102', 'InStock': 0},

]


manager = BackorderManager(orders, inventory)

backorders = manager.check_backorders()

print(backorders)


Supply Chain and Inventory Management – Warehouse Space Optimizer

 


Notes:

  • Problem Solved: Optimizes placement of items in a warehouse to minimize retrieval time and maximize space usage.

  • Benefits: Improves picking efficiency and reduces labor costs in warehousing operations.

  • Adoption: Integrate with WMS (Warehouse Management Systems) for real-time bin allocation.

Python Code:


import pandas as pd


class SpaceOptimizer:

    def __init__(self, item_data):

        self.df = pd.DataFrame(item_data)


    def optimize(self):

        # Sort items by frequency of picking (descending)

        self.df = self.df.sort_values('PickFrequency', ascending=False)

        self.df['AssignedZone'] = ['Front' if i < len(self.df)*0.3 else 'Middle' if i < len(self.df)*0.7 else 'Back'

                                   for i in range(len(self.df))]

        return self.df[['ItemID', 'PickFrequency', 'AssignedZone']]


# Sample item data

items = [

    {'ItemID': 'X1', 'PickFrequency': 120},

    {'ItemID': 'X2', 'PickFrequency': 75},

    {'ItemID': 'X3', 'PickFrequency': 30},

    {'ItemID': 'X4', 'PickFrequency': 10},

    {'ItemID': 'X5', 'PickFrequency': 50},

]


optimizer = SpaceOptimizer(items)

optimized_layout = optimizer.optimize()

print(optimized_layout)


Supply Chain and Inventory Management – Reorder Point Calculator

 


Notes:

  • Problem Solved: Computes the optimal reorder point based on demand rate and lead time.

  • Benefits: Ensures inventory is replenished just in time to meet demand without excess stock.

  • Adoption: Can be automated as part of an inventory planning module.

Python Code:


class ReorderPointCalculator:

    def __init__(self, daily_demand, lead_time_days, safety_stock):

        self.daily_demand = daily_demand

        self.lead_time_days = lead_time_days

        self.safety_stock = safety_stock


    def calculate_reorder_point(self):

        return (self.daily_demand * self.lead_time_days) + self.safety_stock


# Example values

daily_demand = 30  # units per day

lead_time_days = 7

safety_stock = 100


rpc = ReorderPointCalculator(daily_demand, lead_time_days, safety_stock)

reorder_point = rpc.calculate_reorder_point()

print(f"Reorder Point: {reorder_point} units")


Supply Chain and Inventory Management – Inventory Turnover Analyzer

 


Notes:

  • Problem Solved: Calculates inventory turnover ratio to evaluate how efficiently inventory is managed.

  • Benefits: Helps identify slow-moving products, reduce holding costs, and improve working capital.

  • Adoption: Use this script in monthly financial reviews or ERP integration.

Python Code:


import pandas as pd


class TurnoverAnalyzer:

    def __init__(self, inventory_df):

        self.df = pd.DataFrame(inventory_df)


    def calculate_turnover(self):

        self.df['TurnoverRatio'] = self.df['COGS'] / self.df['AverageInventory']

        self.df['DaysInInventory'] = 365 / self.df['TurnoverRatio']

        return self.df[['SKU', 'TurnoverRatio', 'DaysInInventory']]


# Sample inventory data

data = [

    {'SKU': 'Item001', 'COGS': 50000, 'AverageInventory': 10000},

    {'SKU': 'Item002', 'COGS': 30000, 'AverageInventory': 5000},

    {'SKU': 'Item003', 'COGS': 80000, 'AverageInventory': 16000},

]


analyzer = TurnoverAnalyzer(data)

result = analyzer.calculate_turnover()

print(result)


Supply Chain and Inventory Management – Supplier Performance Monitor

 


Notes:

  • Problem Solved: Tracks and scores supplier performance based on delivery timeliness, quality, and cost.

  • Benefits: Businesses can identify top-performing suppliers and negotiate better terms.

  • Adoption: Can be extended into dashboards or monthly supplier performance reports.

Python Code:


import pandas as pd


class SupplierPerformance:

    def __init__(self, performance_data):

        self.df = pd.DataFrame(performance_data)


    def calculate_scores(self):

        self.df['Score'] = (

            self.df['OnTimeDelivery'] * 0.4 +

            self.df['QualityRating'] * 0.4 +

            (100 - self.df['CostVariance']) * 0.2

        )

        return self.df.sort_values('Score', ascending=False)


# Sample supplier performance data

data = [

    {'Supplier': 'Supplier A', 'OnTimeDelivery': 95, 'QualityRating': 90, 'CostVariance': 5},

    {'Supplier': 'Supplier B', 'OnTimeDelivery': 85, 'QualityRating': 88, 'CostVariance': 3},

    {'Supplier': 'Supplier C', 'OnTimeDelivery': 98, 'QualityRating': 92, 'CostVariance': 10},

]


sp = SupplierPerformance(data)

scores_df = sp.calculate_scores()

print(scores_df[['Supplier', 'Score']])


Supply Chain and Inventory Management – ABC Inventory Classification

 


Notes:

  • Problem Solved: Classifies inventory into A, B, and C categories based on annual consumption value.

  • Benefits: Helps businesses prioritize inventory control efforts and optimize stock holding.

  • Adoption: Can be scheduled to run monthly for continuous reclassification of SKUs.

Python Code:


import pandas as pd


class ABCClassifier:

    def __init__(self, inventory_df):

        self.df = inventory_df


    def classify(self):

        self.df['AnnualConsumption'] = self.df['UnitCost'] * self.df['AnnualDemand']

        self.df = self.df.sort_values('AnnualConsumption', ascending=False)

        self.df['Cumulative%'] = self.df['AnnualConsumption'].cumsum() / self.df['AnnualConsumption'].sum()


        def assign_class(row):

            if row['Cumulative%'] <= 0.7:

                return 'A'

            elif row['Cumulative%'] <= 0.9:

                return 'B'

            else:

                return 'C'


        self.df['Category'] = self.df.apply(assign_class, axis=1)

        return self.df[['SKU', 'AnnualConsumption', 'Category']]


# Sample data

data = [

    {'SKU': 'P001', 'UnitCost': 10, 'AnnualDemand': 1000},

    {'SKU': 'P002', 'UnitCost': 5, 'AnnualDemand': 500},

    {'SKU': 'P003', 'UnitCost': 50, 'AnnualDemand': 100},

    {'SKU': 'P004', 'UnitCost': 20, 'AnnualDemand': 300},

    {'SKU': 'P005', 'UnitCost': 2, 'AnnualDemand': 2000},

]


df = pd.DataFrame(data)

classifier = ABCClassifier(df)

classified_df = classifier.classify()


print(classified_df)


Supply Chain and Inventory Management – Safety Stock Calculator

 


Notes:

  • Problem Solved: Calculates optimal safety stock based on demand variability and lead time.

  • Benefits: Prevents stockouts by ensuring buffer inventory, minimizing lost sales.

  • Adoption: Businesses can plug this into ERP systems to auto-adjust inventory reorder levels.

Python Code:


import math


class SafetyStockCalculator:

    def __init__(self, z_score, std_dev_demand, lead_time_days):

        self.z_score = z_score

        self.std_dev_demand = std_dev_demand

        self.lead_time_days = lead_time_days


    def calculate_safety_stock(self):

        return round(self.z_score * self.std_dev_demand * math.sqrt(self.lead_time_days), 2)


# Example parameters

z_score = 1.65  # 95% service level

std_dev_demand = 20  # Standard deviation of daily demand

lead_time_days = 7  # Lead time in days


calculator = SafetyStockCalculator(z_score, std_dev_demand, lead_time_days)

safety_stock = calculator.calculate_safety_stock()


print(f"Recommended Safety Stock: {safety_stock} units")


Supply Chain and Inventory Management – Route Optimization Engine

 


Notes:

  • Problem Solved: Finds the most efficient delivery routes, reducing fuel costs and delivery times.

  • Benefits: Businesses can lower logistics costs and improve customer satisfaction through faster delivery.

  • Adoption: Can be integrated with delivery dispatch systems or used to evaluate alternative route plans.

Python Code:


import networkx as nx


class RouteOptimizer:

    def __init__(self):

        self.graph = nx.Graph()


    def add_route(self, source, destination, distance):

        self.graph.add_edge(source, destination, weight=distance)


    def find_shortest_path(self, start, end):

        return nx.shortest_path(self.graph, source=start, target=end, weight='weight')


    def path_distance(self, path):

        return sum(self.graph[u][v]['weight'] for u, v in zip(path[:-1], path[1:]))


# Define routes

optimizer = RouteOptimizer()

routes = [

    ('Warehouse', 'CityA', 10),

    ('Warehouse', 'CityB', 15),

    ('CityA', 'CityC', 12),

    ('CityB', 'CityC', 10),

    ('CityC', 'Customer', 5)

]


for route in routes:

    optimizer.add_route(*route)


# Find shortest path from warehouse to customer

shortest_path = optimizer.find_shortest_path('Warehouse', 'Customer')

distance = optimizer.path_distance(shortest_path)


print(f"Shortest delivery path: {shortest_path} with distance: {distance}")


Supply Chain and Inventory Management – Order Processing System

 


Notes:

  • Problem Solved: Automates the order processing workflow, from order creation to inventory update.

  • Benefits: Streamlines order handling, reduces manual errors, and ensures timely updates to inventory.

  • Adoption: Integrate this system with e-commerce platforms or use it for internal order processing.

Python Code:


import pandas as pd


class OrderProcessor:

    def __init__(self, inventory_data):

        self.inventory_data = pd.DataFrame(inventory_data)


    def process_order(self, order):

        for product_id, quantity in order.items():

            if product_id in self.inventory_data['ProductID'].values:

                stock = self.inventory_data.loc[self.inventory_data['ProductID'] == product_id, 'Quantity'].values[0]

                if stock >= quantity:

                    self.inventory_data.loc[self.inventory_data['ProductID'] == product_id, 'Quantity'] -= quantity

                    print(f"Order for {quantity} units of {product_id} processed.")

                else:

                    print(f"Insufficient stock for {product_id}. Only {stock} units available.")

            else:

                print(f"Product {product_id} not found in inventory.")


    def get_inventory(self):

        return self.inventory_data


# Sample inventory data

inventory_data = [

    {'ProductID': 'A101', 'Quantity': 100},

    {'ProductID': 'B202', 'Quantity': 150},

    {'ProductID': 'C303', 'Quantity': 50},

]


# Initialize processor

processor = OrderProcessor(inventory_data)


# Sample order

order = {'A101': 20, 'B202': 30, 'C303': 60}


# Process order

processor.process_order(order)


# Display updated inventory

print(processor.get_inventory())


Supply Chain and Inventory Management – Demand Forecasting

 


Notes:

  • Problem Solved: Predicts future product demand using historical sales data, aiding in inventory planning.

  • Benefits: Helps businesses plan inventory levels based on forecasted demand, optimizing stock levels.

  • Adoption: Integrate this forecasting model with sales data to generate periodic demand forecasts.

Python Code:


import pandas as pd

from sklearn.linear_model import LinearRegression

import numpy as np


class DemandForecaster:

    def __init__(self, sales_data):

        self.sales_data = pd.DataFrame(sales_data)

        self.model = LinearRegression()


    def train_model(self):

        X = np.array(self.sales_data['Month']).reshape(-1, 1)

        y = self.sales_data['Sales']

        self.model.fit(X, y)


    def forecast_demand(self, months_ahead):

        future_months = np.array(range(len(self.sales_data) + 1, len(self.sales_data) + 1 + months_ahead)).reshape(-1, 1)

        forecast = self.model.predict(future_months)

        return forecast


# Sample sales data

sales_data = [

    {'Month': 1, 'Sales': 200},

    {'Month': 2, 'Sales': 220},

    {'Month': 3, 'Sales': 240},

    {'Month': 4, 'Sales': 260},

    {'Month': 5, 'Sales': 280},

]


# Initialize forecaster

forecaster = DemandForecaster(sales_data)


# Train model

forecaster.train_model()


# Forecast next 3 months

forecast = forecaster.forecast_demand(3)

print(f"Forecasted demand for next 3 months: {forecast}")


Supply Chain and Inventory Management – Real-Time Inventory Tracker

 

Notes:

  • Problem Solved: Provides real-time tracking of inventory levels across multiple warehouses, ensuring accurate stock information.

  • Benefits: Businesses can monitor stock levels in real-time, reducing the risk of stockouts and overstocking.

  • Adoption: Integrate this script with existing inventory systems or use it as a standalone tool for smaller operations.

Python Code:


import pandas as pd


class InventoryTracker:

    def __init__(self, warehouse_data):

        self.warehouse_data = pd.DataFrame(warehouse_data)


    def update_inventory(self, warehouse_id, product_id, quantity):

        self.warehouse_data.loc[

            (self.warehouse_data['WarehouseID'] == warehouse_id) & 

            (self.warehouse_data['ProductID'] == product_id), 'Quantity'] += quantity


    def get_inventory(self):

        return self.warehouse_data


# Sample warehouse data

warehouse_data = [

    {'WarehouseID': 1, 'ProductID': 'A101', 'Quantity': 100},

    {'WarehouseID': 1, 'ProductID': 'B202', 'Quantity': 150},

    {'WarehouseID': 2, 'ProductID': 'A101', 'Quantity': 200},

    {'WarehouseID': 2, 'ProductID': 'C303', 'Quantity': 50},

]


# Initialize tracker

tracker = InventoryTracker(warehouse_data)


# Update inventory

tracker.update_inventory(1, 'A101', 50)


# Display updated inventory

print(tracker.get_inventory())




Sunday, May 4, 2025

Education and Learning Management Systems - Learning Analytics Dashboard

 

Problem: Analyzing students' learning performance manually is time-consuming and lacks visual representation.

Solution: Provides a visual dashboard that displays students' grades, progress, and completion rates.

Benefits: Helps instructors make informed decisions based on data, and gives students clear insights into their progress.

Adoption: This can be expanded by integrating more advanced analytics such as predictive performance or recommendations.

Code:


import matplotlib.pyplot as plt


# Sample student performance data

students = {

    'John Doe': {'Python Programming': 85, 'Data Science': 90},

    'Jane Smith': {'Python Programming': 75, 'Data Science': 80},

    'Alice Brown': {'Machine Learning': 65},

}


# Function to visualize performance

def visualize_performance():

    student_names = list(students.keys())

    course_names = list(students[student_names[0]].keys())

    scores = [list(student.values()) for student in students.values()]

    

    fig, ax = plt.subplots()

    ax.boxplot(scores, labels=course_names)

    ax.set_title('Learning Analytics Dashboard')

    ax.set_xlabel('Courses')

    ax.set_ylabel('Scores')

    plt.xticks(rotation=45)

    plt.show()


# Run the dashboard

visualize_performance()


Education and Learning Management Systems - Course Content Management System

 

Problem: Managing and updating course materials like documents, presentations, and videos is often a manual process.

Solution: Automates the upload and management of course content, categorizing materials by type and course.

Benefits: Ensures that all course materials are easily accessible and up-to-date, reducing manual effort.

Adoption: This can be extended to automatically send content updates to students or integrate with a Learning Management System (LMS).

Code:


import os


# Function to upload course material

def upload_material(course_name, material_type, file_path):

    course_dir = f"{course_name}_materials"

    os.makedirs(course_dir, exist_ok=True)

    

    material_name = os.path.basename(file_path)

    destination_path = os.path.join(course_dir, material_name)

    os.rename(file_path, destination_path)

    

    print(f"{material_name} has been uploaded to {course_name}.")


# Sample file upload (assuming a file exists in the current directory)

upload_material('Python Programming', 'Lecture Notes', 'python_intro.pdf')


Education and Learning Management Systems - Student Profile Management System

 

Problem: Managing detailed student profiles manually is cumbersome and inefficient.

Solution: Provides a way to create, update, and store student profiles including academic and personal information.

Benefits: Streamlines the process of managing student data and improves accessibility for teachers and administrative staff.

Adoption: This system can be integrated with a larger student management system and include functionalities like sending notifications and scheduling meetings.

Code:


import json


# Function to add/update student profiles

def update_profile(student_id, name, age, courses):

    student_data = {

        'ID': student_id,

        'Name': name,

        'Age': age,

        'Courses': courses

    }

    

    with open(f'{student_id}_profile.json', 'w') as file:

        json.dump(student_data, file)

    print(f"Profile updated for {name}.")


# Sample student profile update

update_profile(101, 'John Doe', 20, ['Python Programming', 'Data Science'])


Education and Learning Management Systems - Student Assignment Tracker

 

Problem: Tracking the status and deadlines of student assignments manually can be difficult and prone to errors.

Solution: Automates the tracking of student assignments, their deadlines, and submission status.

Benefits: Helps instructors manage and track assignments effectively and ensures students meet deadlines.

Adoption: This can be expanded to integrate with an online platform that automatically sends reminders and updates to students.

Code:


from datetime import datetime


# Sample assignments data

assignments = {

    'John Doe': {'Python Project': '2025-05-10', 'Data Science Report': '2025-05-15'},

    'Jane Smith': {'Machine Learning Assignment': '2025-05-12'},

}


# Function to track assignments

def track_assignments():

    today = datetime.now().date()

    for student, assignments_list in assignments.items():

        print(f"Assignments for {student}:")

        for assignment, deadline in assignments_list.items():

            deadline_date = datetime.strptime(deadline, '%Y-%m-%d').date()

            status = "Completed" if deadline_date < today else "Pending"

            print(f"  - {assignment}: Deadline {deadline} | Status: {status}")

        print()


# Track assignments

track_assignments()


IoT (Internet of Things) Automation - Smart Energy Usage Tracker

  Notes: Problem Solved: Logs and analyzes power usage from smart meters. Customization Benefits: Track per-device energy and set ale...