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


Image Perspective Corrector

import cv2

import numpy as np


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

# Order points correctly

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

def order_points(pts):

    rect = np.zeros((4, 2), dtype="float32")


    s = pts.sum(axis=1)

    rect[0] = pts[np.argmin(s)]   # top-left

    rect[2] = pts[np.argmax(s)]   # bottom-right


    diff = np.diff(pts, axis=1)

    rect[1] = pts[np.argmin(diff)]  # top-right

    rect[3] = pts[np.argmax(diff)]  # bottom-left


    return rect



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

# Perspective transform

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

def four_point_transform(image, pts):

    rect = order_points(pts)

    (tl, tr, br, bl) = rect


    widthA = np.linalg.norm(br - bl)

    widthB = np.linalg.norm(tr - tl)

    maxWidth = max(int(widthA), int(widthB))


    heightA = np.linalg.norm(tr - br)

    heightB = np.linalg.norm(tl - bl)

    maxHeight = max(int(heightA), int(heightB))


    dst = np.array([

        [0, 0],

        [maxWidth - 1, 0],

        [maxWidth - 1, maxHeight - 1],

        [0, maxHeight - 1]

    ], dtype="float32")


    M = cv2.getPerspectiveTransform(rect, dst)

    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))


    return warped



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

# Detect document contour

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

def detect_document(image):

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    blurred = cv2.GaussianBlur(gray, (5, 5), 0)


    edged = cv2.Canny(blurred, 75, 200)


    contours, _ = cv2.findContours(

        edged.copy(),

        cv2.RETR_LIST,

        cv2.CHAIN_APPROX_SIMPLE

    )


    contours = sorted(contours, key=cv2.contourArea, reverse=True)


    for contour in contours:

        peri = cv2.arcLength(contour, True)

        approx = cv2.approxPolyDP(contour, 0.02 * peri, True)


        if len(approx) == 4:

            return approx.reshape(4, 2)


    return None



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

# Main

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

if __name__ == "__main__":

    path = input("Enter image path: ").strip()


    image = cv2.imread(path)


    if image is None:

        print(" Could not load image.")

        exit()


    orig = image.copy()

    doc_cnt = detect_document(image)


    if doc_cnt is None:

        print(" Document edges not detected.")

        exit()


    warped = four_point_transform(orig, doc_cnt)


    # Convert to scanned look

    warped_gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

    warped_thresh = cv2.adaptiveThreshold(

        warped_gray, 255,

        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

        cv2.THRESH_BINARY,

        11, 2

    )


    cv2.imshow("Original", orig)

    cv2.imshow("Scanned Output", warped_thresh)


    cv2.imwrite("scanned_output.jpg", warped_thresh)

    print(" Saved as scanned_output.jpg")


    cv2.waitKey(0)

    cv2.destroyAllWindows()


Sudoku Solver with Step Explanation

 import copy


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

# Helper Functions

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


def print_board(board):

    for i in range(9):

        row = ""

        for j in range(9):

            row += str(board[i][j]) + " "

            if j % 3 == 2 and j != 8:

                row += "| "

        print(row)

        if i % 3 == 2 and i != 8:

            print("-" * 21)

    print()



def find_empty(board):

    for r in range(9):

        for c in range(9):

            if board[r][c] == 0:

                return r, c

    return None



def is_valid(board, num, row, col):

    # Row

    if num in board[row]:

        return False


    # Column

    for r in range(9):

        if board[r][col] == num:

            return False


    # 3x3 box

    box_row = (row // 3) * 3

    box_col = (col // 3) * 3


    for r in range(box_row, box_row + 3):

        for c in range(box_col, box_col + 3):

            if board[r][c] == num:

                return False


    return True



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

# Constraint Propagation

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


def get_candidates(board, row, col):

    return [num for num in range(1, 10) if is_valid(board, num, row, col)]



def apply_constraint_propagation(board, steps):

    changed = True

    while changed:

        changed = False

        for r in range(9):

            for c in range(9):

                if board[r][c] == 0:

                    candidates = get_candidates(board, r, c)

                    if len(candidates) == 1:

                        board[r][c] = candidates[0]

                        steps.append(

                            f"Naked Single: Placed {candidates[0]} at ({r+1},{c+1})"

                        )

                        changed = True

    return board



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

# Backtracking with Explanation

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


def solve(board, steps):

    board = apply_constraint_propagation(board, steps)


    empty = find_empty(board)

    if not empty:

        return True


    row, col = empty

    candidates = get_candidates(board, row, col)


    for num in candidates:

        steps.append(f"Trying {num} at ({row+1},{col+1})")

        board[row][col] = num


        if solve(board, steps):

            return True


        steps.append(f"Backtracking from ({row+1},{col+1})")

        board[row][col] = 0


    return False



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

# Example Puzzle

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


if __name__ == "__main__":

    puzzle = [

        [5,3,0,0,7,0,0,0,0],

        [6,0,0,1,9,5,0,0,0],

        [0,9,8,0,0,0,0,6,0],

        [8,0,0,0,6,0,0,0,3],

        [4,0,0,8,0,3,0,0,1],

        [7,0,0,0,2,0,0,0,6],

        [0,6,0,0,0,0,2,8,0],

        [0,0,0,4,1,9,0,0,5],

        [0,0,0,0,8,0,0,7,9],

    ]


    print("Initial Puzzle:\n")

    print_board(puzzle)


    steps = []

    board_copy = copy.deepcopy(puzzle)


    if solve(board_copy, steps):

        print("Solved Puzzle:\n")

        print_board(board_copy)


        print("Step-by-Step Explanation:\n")

        for step in steps:

            print(step)

    else:

        print("No solution found.")