Code Snippets

A library of technical solutions, from GUI automation to database optimization.

Python: Data Storage Calculator (GUI)

Download .ZIP

A Tkinter-based desktop application that parses text for storage values (TB, GB, MB) and calculates the total with real-time unit conversion.

import tkinter as tk
from tkinter import messagebox
import re

# Constants for binary conversion
CONVERSION_FACTOR = 1024.0

def calculate_and_display():
    input_text = text_input.get("1.0", tk.END)
    pattern = re.compile(r'(\d+\.?\d*)\s*(TB|GB|MB)', re.IGNORECASE)
    matches = pattern.findall(input_text)
    total_gb = 0.0

    if not matches:
        messagebox.showerror("Error", "No valid values found.")
        return

    for value_str, unit in matches:
        value = float(value_str)
        unit_upper = unit.upper()
        if unit_upper == 'TB': total_gb += value * CONVERSION_FACTOR
        elif unit_upper == 'GB': total_gb += value
        elif unit_upper == 'MB': total_gb += value / CONVERSION_FACTOR

    update_result_labels(total_gb)

def update_result_labels(total_gb):
    total_mb = total_gb * CONVERSION_FACTOR
    total_tb = total_gb / CONVERSION_FACTOR
    selected_unit = display_unit_var.get()

    if selected_unit == "MB": result = f"{total_mb:.2f} MB"
    elif selected_unit == "TB": result = f"{total_tb:.4f} TB"
    else: result = f"{total_gb:.2f} GB"

    result_label.config(text=f"Total Storage: {result}")

# --- GUI Setup ---
root = tk.Tk()
root.title("Data Storage Calculator")
root.geometry("500x450")

text_input = tk.Text(root, height=10, width=60)
text_input.pack(padx=10, pady=5)

calculate_button = tk.Button(root, text="Calculate", command=calculate_and_display, bg="green", fg="white")
calculate_button.pack(pady=5)

display_unit_var = tk.StringVar(value="GB")
# ... (Radio buttons and labels)

root.mainloop()

SQL: Advanced Insert Logic

Download .ZIP

A clever workaround for the "cannot select from target table" limitation in SQL. This uses an aliased subquery to allow inserting from a SELECT on the same table.

INSERT INTO user_in_group (user_id, group_id, role_id, notification_enabled, creation_time, is_deleted)
SELECT DISTINCT user_id, 4307, 3, 1, now(), 0 
FROM user_in_group 
WHERE user_id NOT IN (
    SELECT user_id FROM (
        SELECT * FROM user_in_group
    ) a WHERE group_id = 4307
);

Bash: Keyword Log Searcher

Download .ZIP

A practical shell script for DevOps and troubleshooting. It converts user input into a regex-friendly pattern to search multiple logs simultaneously.

#!/bin/bash

# A little script to search entries in a log file based on keywords search.

read -p "Enter the full path to the log file: " log_file_path

if [ ! -f "$log_file_path" ]; then
    echo "Error: File not found."
    exit 1
fi

read -p "Enter keywords (separated by a space): " search_keywords

grep_pattern=$(echo "$search_keywords" | sed 's/ /|/g')

grep -E --color=always -i "$grep_pattern" "$log_file_path"