Algorithm Performance Visualizer

import random

import time

import matplotlib.pyplot as plt


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

# Sorting Algorithms

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


def bubble_sort(arr):

    arr = arr.copy()

    n = len(arr)

    for i in range(n):

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr



def insertion_sort(arr):

    arr = arr.copy()

    for i in range(1, len(arr)):

        key = arr[i]

        j = i - 1

        while j >= 0 and key < arr[j]:

            arr[j + 1] = arr[j]

            j -= 1

        arr[j + 1] = key

    return arr



def merge_sort(arr):

    if len(arr) <= 1:

        return arr


    mid = len(arr) // 2

    left = merge_sort(arr[:mid])

    right = merge_sort(arr[mid:])


    return merge(left, right)



def merge(left, right):

    result = []

    i = j = 0


    while i < len(left) and j < len(right):

        if left[i] < right[j]:

            result.append(left[i])

            i += 1

        else:

            result.append(right[j])

            j += 1


    result.extend(left[i:])

    result.extend(right[j:])

    return result



def quick_sort(arr):

    if len(arr) <= 1:

        return arr

    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]

    middle = [x for x in arr if x == pivot]

    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)



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

# Benchmark Function

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


def measure_time(func, arr):

    start = time.time()

    func(arr)

    end = time.time()

    return end - start



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

# Main Visualization

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


if __name__ == "__main__":

    sizes = [100, 500, 1000, 2000]

    results = {

        "Bubble Sort": [],

        "Insertion Sort": [],

        "Merge Sort": [],

        "Quick Sort": []

    }


    for size in sizes:

        print(f"Testing size: {size}")

        data = [random.randint(1, 10000) for _ in range(size)]


        results["Bubble Sort"].append(measure_time(bubble_sort, data))

        results["Insertion Sort"].append(measure_time(insertion_sort, data))

        results["Merge Sort"].append(measure_time(merge_sort, data))

        results["Quick Sort"].append(measure_time(quick_sort, data))


    # Plot Results

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


    for algo, times in results.items():

        plt.plot(sizes, times, marker='o', label=algo)


    plt.xlabel("Input Size")

    plt.ylabel("Execution Time (seconds)")

    plt.title("Sorting Algorithm Performance Comparison")

    plt.legend()

    plt.grid(True)

    plt.show()

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.")