Local File Integrity Monitor

import os

import hashlib

import json

from watchdog.observers import Observer

from watchdog.events import FileSystemEventHandler

import time


HASH_DB = "file_hashes.json"



# -----------------------------------------

# Hash Function

# -----------------------------------------

def calculate_hash(file_path):

    sha256 = hashlib.sha256()


    try:

        with open(file_path, "rb") as f:

            while chunk := f.read(4096):

                sha256.update(chunk)

        return sha256.hexdigest()

    except:

        return None



# -----------------------------------------

# Load & Save Hash Database

# -----------------------------------------

def load_hash_db():

    if os.path.exists(HASH_DB):

        with open(HASH_DB, "r") as f:

            return json.load(f)

    return {}



def save_hash_db(db):

    with open(HASH_DB, "w") as f:

        json.dump(db, f, indent=4)



# -----------------------------------------

# Initial Scan

# -----------------------------------------

def initial_scan(folder_path):

    db = {}


    print(" Performing initial scan...\n")


    for root, dirs, files in os.walk(folder_path):

        for file in files:

            path = os.path.join(root, file)

            file_hash = calculate_hash(path)

            if file_hash:

                db[path] = file_hash


    save_hash_db(db)

    print(" Initial scan complete.")

    return db



# -----------------------------------------

# Event Handler

# -----------------------------------------

class IntegrityHandler(FileSystemEventHandler):

    def __init__(self, folder_path):

        self.folder_path = folder_path

        self.hash_db = load_hash_db()


        if not self.hash_db:

            self.hash_db = initial_scan(folder_path)


    def on_modified(self, event):

        if event.is_directory:

            return


        file_path = event.src_path

        new_hash = calculate_hash(file_path)


        if file_path in self.hash_db:

            if self.hash_db[file_path] != new_hash:

                print(f"⚠ ALERT: File modified → {file_path}")

                self.hash_db[file_path] = new_hash

                save_hash_db(self.hash_db)


        else:

            print(f" New file detected → {file_path}")

            self.hash_db[file_path] = new_hash

            save_hash_db(self.hash_db)


    def on_deleted(self, event):

        if event.src_path in self.hash_db:

            print(f" File deleted → {event.src_path}")

            del self.hash_db[event.src_path]

            save_hash_db(self.hash_db)



# -----------------------------------------

# MAIN

# -----------------------------------------

if __name__ == "__main__":

    folder = input("Enter folder path to monitor: ").strip()


    if not os.path.isdir(folder):

        print(" Invalid folder path.")

        exit()


    print("\n Monitoring started... (Press Ctrl+C to stop)\n")


    event_handler = IntegrityHandler(folder)

    observer = Observer()

    observer.schedule(event_handler, folder, recursive=True)

    observer.start()


    try:

        while True:

            time.sleep(1)

    except KeyboardInterrupt:

        observer.stop()


    observer.join()

DNA Sequence Pattern Finder

import matplotlib.pyplot as plt


# ---------------------------------------

# Basic DNA Validation

# ---------------------------------------

def validate_dna(sequence):

    sequence = sequence.upper()

    valid = set("ATCG")

    return all(base in valid for base in sequence)



# ---------------------------------------

# GC Content Calculation

# ---------------------------------------

def gc_content(sequence):

    gc_count = sequence.count("G") + sequence.count("C")

    return (gc_count / len(sequence)) * 100



# ---------------------------------------

# Motif Finder

# ---------------------------------------

def find_motif(sequence, motif):

    sequence = sequence.upper()

    motif = motif.upper()

    positions = []


    for i in range(len(sequence) - len(motif) + 1):

        if sequence[i:i+len(motif)] == motif:

            positions.append(i)


    return positions



# ---------------------------------------

# Mutation Comparison

# ---------------------------------------

def compare_sequences(seq1, seq2):

    mutations = []


    min_len = min(len(seq1), len(seq2))


    for i in range(min_len):

        if seq1[i] != seq2[i]:

            mutations.append((i, seq1[i], seq2[i]))


    return mutations



# ---------------------------------------

# GC Content Visualization (Sliding Window)

# ---------------------------------------

def gc_sliding_window(sequence, window_size=20):

    gc_values = []


    for i in range(len(sequence) - window_size + 1):

        window = sequence[i:i+window_size]

        gc_values.append(gc_content(window))


    return gc_values



def plot_gc_distribution(sequence):

    window_size = 20

    gc_values = gc_sliding_window(sequence, window_size)


    plt.figure(figsize=(10, 4))

    plt.plot(gc_values)

    plt.title("GC Content Distribution (Sliding Window)")

    plt.xlabel("Position")

    plt.ylabel("GC %")

    plt.show()



# ---------------------------------------

# MAIN

# ---------------------------------------

if __name__ == "__main__":

    dna = input("Enter DNA sequence: ").strip().upper()


    if not validate_dna(dna):

        print("❌ Invalid DNA sequence (Only A, T, C, G allowed)")

        exit()


    print("\n🧬 DNA Analysis Results\n")


    # GC Content

    gc = gc_content(dna)

    print(f"GC Content: {gc:.2f}%")


    # Motif Search

    motif = input("\nEnter motif to search (e.g., ATG): ").strip().upper()

    positions = find_motif(dna, motif)


    if positions:

        print(f"Motif '{motif}' found at positions: {positions}")

    else:

        print(f"Motif '{motif}' not found.")


    # Mutation Comparison

    compare = input("\nCompare with another sequence? (y/n): ").strip().lower()

    if compare == "y":

        dna2 = input("Enter second DNA sequence: ").strip().upper()


        if len(dna) != len(dna2):

            print("⚠ Sequences have different lengths. Comparing minimum length.")


        mutations = compare_sequences(dna, dna2)


        if mutations:

            print("\nMutations found:")

            for pos, base1, base2 in mutations:

                print(f"Position {pos}: {base1} → {base2}")

        else:

            print("No mutations detected.")


    # GC Distribution Plot

    plot = input("\nPlot GC content distribution? (y/n): ").strip().lower()

    if plot == "y":

        plot_gc_distribution(dna)


Color Contrast Accessibility Checker

import tkinter as tk

from tkinter import colorchooser

import math


# ---------------------------------------

# WCAG Calculation Functions

# ---------------------------------------


def hex_to_rgb(hex_color):

    hex_color = hex_color.lstrip("#")

    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))



def linearize(value):

    value = value / 255

    if value <= 0.03928:

        return value / 12.92

    else:

        return ((value + 0.055) / 1.055) ** 2.4



def relative_luminance(rgb):

    r, g, b = rgb

    r = linearize(r)

    g = linearize(g)

    b = linearize(b)


    return 0.2126 * r + 0.7152 * g + 0.0722 * b



def contrast_ratio(color1, color2):

    L1 = relative_luminance(color1)

    L2 = relative_luminance(color2)


    lighter = max(L1, L2)

    darker = min(L1, L2)


    return (lighter + 0.05) / (darker + 0.05)



def wcag_result(ratio):

    result = ""


    if ratio >= 7:

        result += "AAA (Normal Text) \n"

    elif ratio >= 4.5:

        result += "AA (Normal Text) \n"

    else:

        result += "Fails AA (Normal Text) \n"


    if ratio >= 4.5:

        result += "AAA (Large Text) \n"

    elif ratio >= 3:

        result += "AA (Large Text) \n"

    else:

        result += "Fails Large Text \n"


    return result



# ---------------------------------------

# GUI

# ---------------------------------------


class ContrastChecker:

    def __init__(self, root):

        self.root = root

        self.root.title("WCAG Color Contrast Checker")

        self.root.geometry("500x400")


        self.color1 = "#000000"

        self.color2 = "#FFFFFF"


        self.build_ui()


    def build_ui(self):

        tk.Label(self.root, text="Foreground Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 1",

                  command=self.pick_color1).pack()


        tk.Label(self.root, text="Background Color").pack(pady=5)

        tk.Button(self.root, text="Choose Color 2",

                  command=self.pick_color2).pack()


        tk.Button(self.root, text="Check Contrast",

                  command=self.check_contrast).pack(pady=15)


        self.preview = tk.Label(self.root, text="Preview Text",

                                font=("Arial", 16))

        self.preview.pack(pady=10)


        self.result_label = tk.Label(self.root, text="", justify="left")

        self.result_label.pack(pady=10)


    def pick_color1(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color1 = color


    def pick_color2(self):

        color = colorchooser.askcolor()[1]

        if color:

            self.color2 = color


    def check_contrast(self):

        rgb1 = hex_to_rgb(self.color1)

        rgb2 = hex_to_rgb(self.color2)


        ratio = contrast_ratio(rgb1, rgb2)


        self.preview.config(

            fg=self.color1,

            bg=self.color2

        )


        result = f"Contrast Ratio: {ratio:.2f}:1\n\n"

        result += wcag_result(ratio)


        self.result_label.config(text=result)



# ---------------------------------------

# RUN

# ---------------------------------------


if __name__ == "__main__":

    root = tk.Tk()

    app = ContrastChecker(root)

    root.mainloop()


Project Time Tracker with App Detection

import time

import sqlite3

import psutil

import win32gui

from datetime import datetime


DB_NAME = "time_tracker.db"

CHECK_INTERVAL = 1  # seconds



# ----------------------------------------

# Database Setup

# ----------------------------------------

def init_db():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        CREATE TABLE IF NOT EXISTS app_usage (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            app_name TEXT,

            window_title TEXT,

            start_time TEXT,

            end_time TEXT,

            duration REAL

        )

    """)


    conn.commit()

    conn.close()



# ----------------------------------------

# Get Active Window Info

# ----------------------------------------

def get_active_window():

    hwnd = win32gui.GetForegroundWindow()

    window_title = win32gui.GetWindowText(hwnd)


    try:

        pid = win32gui.GetWindowThreadProcessId(hwnd)[1]

        process = psutil.Process(pid)

        app_name = process.name()

    except:

        app_name = "Unknown"


    return app_name, window_title



# ----------------------------------------

# Save Session

# ----------------------------------------

def save_session(app_name, window_title, start_time, end_time):

    duration = (end_time - start_time).total_seconds()


    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        INSERT INTO app_usage (app_name, window_title, start_time, end_time, duration)

        VALUES (?, ?, ?, ?, ?)

    """, (

        app_name,

        window_title,

        start_time.strftime("%Y-%m-%d %H:%M:%S"),

        end_time.strftime("%Y-%m-%d %H:%M:%S"),

        duration

    ))


    conn.commit()

    conn.close()



# ----------------------------------------

# Tracking Loop

# ----------------------------------------

def track_time():

    print("šŸ—‚ Project Time Tracker Started (Press Ctrl+C to stop)\n")


    current_app, current_title = get_active_window()

    start_time = datetime.now()


    try:

        while True:

            time.sleep(CHECK_INTERVAL)

            new_app, new_title = get_active_window()


            if new_app != current_app or new_title != current_title:

                end_time = datetime.now()

                save_session(current_app, current_title, start_time, end_time)


                current_app, current_title = new_app, new_title

                start_time = datetime.now()


    except KeyboardInterrupt:

        print("\nStopping tracker...")

        end_time = datetime.now()

        save_session(current_app, current_title, start_time, end_time)

        print("Session saved.")



# ----------------------------------------

# Summary Report

# ----------------------------------------

def show_summary():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.cursor()


    cursor.execute("""

        SELECT app_name, SUM(duration)/60 as total_minutes

        FROM app_usage

        GROUP BY app_name

        ORDER BY total_minutes DESC

    """)


    results = cursor.fetchall()

    conn.close()


    print("\n Time Usage Summary (Minutes):\n")

    for app, minutes in results:

        print(f"{app:20} {minutes:.2f} min")



# ----------------------------------------

# MAIN

# ----------------------------------------

if __name__ == "__main__":

    init_db()


    print("1. Start Tracking")

    print("2. Show Summary")


    choice = input("Choose option: ").strip()


    if choice == "1":

        track_time()

    elif choice == "2":

        show_summary()

    else:

        print("Invalid choice.")


Smart Log File Analyzer

import re

import pandas as pd

import numpy as np

from sklearn.ensemble import IsolationForest

import matplotlib.pyplot as plt


# -------------------------------------

# Log Pattern (Apache Common Log)

# -------------------------------------

log_pattern = re.compile(

    r'(?P<ip>\S+) - - \[(?P<time>.*?)\] '

    r'"(?P<method>\S+) (?P<url>\S+) \S+" '

    r'(?P<status>\d+) (?P<size>\d+)'

)


# -------------------------------------

# Parse Log File

# -------------------------------------

def parse_log(file_path):

    data = []


    with open(file_path, "r", encoding="utf-8", errors="ignore") as f:

        for line in f:

            match = log_pattern.search(line)

            if match:

                data.append(match.groupdict())


    df = pd.DataFrame(data)


    df["status"] = df["status"].astype(int)

    df["size"] = df["size"].astype(int)


    return df



# -------------------------------------

# Feature Engineering

# -------------------------------------

def extract_features(df):

    ip_counts = df.groupby("ip").size().reset_index(name="request_count")

    status_4xx = df[df["status"].between(400, 499)].groupby("ip").size().reset_index(name="errors")

    status_5xx = df[df["status"].between(500, 599)].groupby("ip").size().reset_index(name="server_errors")


    features = ip_counts.merge(status_4xx, on="ip", how="left")

    features = features.merge(status_5xx, on="ip", how="left")


    features.fillna(0, inplace=True)


    return features



# -------------------------------------

# Anomaly Detection

# -------------------------------------

def detect_anomalies(features):

    model = IsolationForest(contamination=0.05, random_state=42)


    X = features[["request_count", "errors", "server_errors"]]


    features["anomaly_score"] = model.fit_predict(X)

    features["is_suspicious"] = features["anomaly_score"] == -1


    return features



# -------------------------------------

# Visualization

# -------------------------------------

def visualize(features):

    plt.figure(figsize=(10, 5))


    normal = features[features["is_suspicious"] == False]

    suspicious = features[features["is_suspicious"] == True]


    plt.scatter(normal["request_count"], normal["errors"], label="Normal")

    plt.scatter(suspicious["request_count"], suspicious["errors"], label="Suspicious", marker="x")


    plt.xlabel("Request Count")

    plt.ylabel("4xx Errors")

    plt.legend()

    plt.title("Log Anomaly Detection")

    plt.show()



# -------------------------------------

# MAIN

# -------------------------------------

if __name__ == "__main__":

    path = input("Enter log file path: ").strip()


    print("Parsing logs...")

    df = parse_log(path)


    print(f"Loaded {len(df)} log entries.")


    features = extract_features(df)


    print("Detecting anomalies...")

    analyzed = detect_anomalies(features)


    suspicious = analyzed[analyzed["is_suspicious"] == True]


    print("\n Suspicious IP Addresses:\n")

    print(suspicious[["ip", "request_count", "errors", "server_errors"]])


    visualize(analyzed)


    analyzed.to_csv("log_analysis_report.csv", index=False)

    print("\n Report saved as log_analysis_report.csv")