Network Packet Visualizer

 from scapy.all import sniff

import matplotlib.pyplot as plt


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

# Packet Counters

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


protocol_counts = {

    "TCP": 0,

    "UDP": 0,

    "ICMP": 0,

    "Other": 0

}



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

# Packet Handler

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


def process_packet(packet):


    if packet.haslayer("TCP"):

        protocol_counts["TCP"] += 1


    elif packet.haslayer("UDP"):

        protocol_counts["UDP"] += 1


    elif packet.haslayer("ICMP"):

        protocol_counts["ICMP"] += 1


    else:

        protocol_counts["Other"] += 1



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

# Capture Packets

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


def capture_packets(packet_limit=200):


    print("Capturing packets...")


    sniff(prn=process_packet, count=packet_limit)


    print("Capture complete.")



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

# Visualization

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


def visualize():


    labels = list(protocol_counts.keys())

    values = list(protocol_counts.values())


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


    plt.pie(

        values,

        labels=labels,

        autopct='%1.1f%%',

        startangle=140

    )


    plt.title("Network Protocol Distribution")

    plt.show()



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

# MAIN

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


if __name__ == "__main__":


    capture_packets(300)


    print("\nProtocol counts:")


    for proto, count in protocol_counts.items():

        print(f"{proto}: {count}")


    visualize()

Matrix Calculator with Step-by-Step Linear Algebra

import numpy as np

import sympy as sp


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

# Input Matrix

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


def input_matrix():

    rows = int(input("Enter number of rows: "))

    cols = int(input("Enter number of columns: "))


    matrix = []


    print("Enter matrix values row by row:")


    for i in range(rows):

        row = list(map(float, input().split()))

        matrix.append(row)


    return np.array(matrix)



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

# Determinant

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


def calculate_determinant(matrix):

    sym_matrix = sp.Matrix(matrix)


    print("\nMatrix:")

    sp.pprint(sym_matrix)


    det = sym_matrix.det()


    print("\nDeterminant calculation:")

    print(det)


    return det



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

# Matrix Inverse

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


def calculate_inverse(matrix):

    sym_matrix = sp.Matrix(matrix)


    print("\nMatrix:")

    sp.pprint(sym_matrix)


    try:

        inverse = sym_matrix.inv()


        print("\nInverse Matrix:")

        sp.pprint(inverse)


        return inverse


    except:

        print("Matrix is not invertible.")

        return None



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

# Eigenvalues

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


def calculate_eigenvalues(matrix):

    sym_matrix = sp.Matrix(matrix)


    print("\nMatrix:")

    sp.pprint(sym_matrix)


    eigenvals = sym_matrix.eigenvals()


    print("\nEigenvalues:")


    for val, mult in eigenvals.items():

        print(f"{val} (multiplicity {mult})")


    return eigenvals



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

# MAIN

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


if __name__ == "__main__":


    matrix = input_matrix()


    print("\nChoose operation:")

    print("1. Determinant")

    print("2. Inverse")

    print("3. Eigenvalues")


    choice = input("Enter choice: ")


    if choice == "1":

        calculate_determinant(matrix)


    elif choice == "2":

        calculate_inverse(matrix)


    elif choice == "3":

        calculate_eigenvalues(matrix)


    else:

        print("Invalid option")

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)