Blog

  • QR Code Generator Python Script

    This Python script uses the qrcode library to convert user-provided text or URLs into a QR code image, which is saved as a PNG file. It offers a simple way to quickly generate and share QR codes directly from your terminal.

    Click to view script…
    #!/usr/bin/env python3
    import qrcode
    
    def generate_qr_code(data, filename="qr_code.png"):
        """
        Generates a QR code from the provided data and saves it to a file.
    
        Parameters:
            data (str): The text or URL to encode.
            filename (str): The name of the file to save the QR code image.
        
        Returns:
            str: The filename where the QR code is saved.
        """
        # Create a QRCode object with desired settings.
        qr = qrcode.QRCode(
            version=1,  # 1 means 21x21 matrix; increase for more data.
            error_correction=qrcode.constants.ERROR_CORRECT_H,  # High error correction.
            box_size=10,  # Size of each box in pixels.
            border=4,  # Border size in boxes.
        )
        
        # Add data to the QR code.
        qr.add_data(data)
        qr.make(fit=True)
        
        # Create an image from the QR code instance.
        img = qr.make_image(fill_color="black", back_color="white")
        img.save(filename)
        return filename
    
    def main():
        print("=== QR Code Generator ===\n")
        data = input("Enter the text or URL you want to encode in the QR code: ").strip()
        if not data:
            print("No data provided. Exiting.")
            return
    
        filename = generate_qr_code(data)
        print(f"\nQR code generated and saved as '{filename}'.")
    
    if __name__ == "__main__":
        main()
  • True or False Trivia Challenge Python Script

    This interactive quiz game lets you explore fun categories by answering unique True/False questions. With each question, you’ll receive immediate feedback and an insightful explanation to expand your knowledge.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Animal Trivia",
                "questions": [
                    {
                        "question": "Elephants are the only animals that can't jump.",
                        "answer": True,
                        "description": "True! Due to their massive weight and unique limb structure, elephants are physically incapable of jumping."
                    },
                    {
                        "question": "Bats are blind.",
                        "answer": False,
                        "description": "False! While bats use echolocation, they also have functional eyes and can see."
                    },
                    {
                        "question": "A group of flamingos is called a 'flamboyance'.",
                        "answer": True,
                        "description": "True! The collective noun for flamingos is indeed 'flamboyance', which suits their vibrant appearance."
                    },
                    {
                        "question": "An octopus has three hearts.",
                        "answer": True,
                        "description": "True! Octopuses have two branchial hearts and one systemic heart."
                    },
                    {
                        "question": "Goldfish have a memory span of just three seconds.",
                        "answer": False,
                        "description": "False! Goldfish can actually remember things for months."
                    }
                ]
            },
            "2": {
                "name": "Space Facts",
                "questions": [
                    {
                        "question": "A day on Venus is longer than its year.",
                        "answer": True,
                        "description": "True! Venus rotates very slowly, making its day longer than the time it takes to orbit the Sun."
                    },
                    {
                        "question": "There is no sound in space.",
                        "answer": True,
                        "description": "True! Space is a vacuum, so sound cannot travel."
                    },
                    {
                        "question": "Mars has the tallest volcano in the solar system, Olympus Mons.",
                        "answer": True,
                        "description": "True! Olympus Mons on Mars stands about 22 kilometers high, making it the tallest volcano known."
                    },
                    {
                        "question": "Saturn is the only planet with rings.",
                        "answer": False,
                        "description": "False! While Saturn’s rings are the most prominent, Jupiter, Uranus, and Neptune also have ring systems."
                    },
                    {
                        "question": "The footprints on the Moon will disappear over time due to wind erosion.",
                        "answer": False,
                        "description": "False! The Moon has no atmosphere or wind, so the footprints will likely remain for millions of years."
                    }
                ]
            },
            "3": {
                "name": "History Myths",
                "questions": [
                    {
                        "question": "Napoleon Bonaparte was extremely short.",
                        "answer": False,
                        "description": "False! Napoleon was of average height for his era; the myth of his short stature comes from a misunderstanding of French measurements."
                    },
                    {
                        "question": "The Great Wall of China is visible from space.",
                        "answer": False,
                        "description": "False! The Great Wall is very narrow and follows the natural contours of the land, making it nearly impossible to see from space with the naked eye."
                    },
                    {
                        "question": "Vikings wore horned helmets.",
                        "answer": False,
                        "description": "False! There is no historical evidence that Vikings ever wore horned helmets; this image was popularized by 19th-century artists."
                    },
                    {
                        "question": "The French Revolution began in 1789.",
                        "answer": True,
                        "description": "True! The French Revolution, which reshaped France and influenced modern democracies, began in 1789."
                    },
                    {
                        "question": "Christopher Columbus made his first voyage to the Americas in 1492.",
                        "answer": True,
                        "description": "True! In 1492, Columbus set sail, marking the beginning of European exploration of the Americas."
                    }
                ]
            }
        }
    
        print("Welcome to the True/False Quiz Game!")
        
        while True:
            print("\nChoose a category for your quiz:")
            for key, cat in categories.items():
                print(f"{key}. {cat['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Thanks for playing! Goodbye!")
                break
            
            if choice not in categories:
                print("Invalid choice. Please try again.")
                continue
            
            selected_cat = categories[choice]
            print(f"\nYou selected: {selected_cat['name']}")
            # Create a local copy of the questions list so each question is shown only once.
            available_questions = selected_cat["questions"].copy()
            
            while available_questions:
                question = random.choice(available_questions)
                available_questions.remove(question)
                
                print("\n" + question["question"])
                user_answer = input("Type T for True or F for False: ").strip().lower()
                
                if user_answer not in ["t", "f"]:
                    print("Invalid input. Please type 'T' or 'F'.")
                    continue
                
                user_bool = True if user_answer == "t" else False
                
                if user_bool == question["answer"]:
                    print("Correct!")
                else:
                    print("Incorrect!")
                
                print("Explanation:", question["description"])
                
                # Check if there are more questions available.
                if available_questions:
                    another = input("\nWould you like another question from this category? (y/n): ").strip().lower()
                    if another != "y":
                        break
                else:
                    print("\nNo more questions left in this category.")
                    
    if __name__ == "__main__":
        main()
  • Historical News Fun Facts Python Script

    This Python script provides an interactive and engaging way to learn about major historical news events. Users can choose from a variety of categories and receive a random, interesting fact from each, making history both fun and informative.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Wars & Conflicts",
                "facts": [
                    "World War II (1939-1945) saw the largest mobilization of military forces in history.",
                    "The American Civil War (1861-1865) led to the abolition of slavery in the United States.",
                    "World War I (1914-1918) introduced modern warfare techniques like tanks and chemical warfare.",
                    "The Vietnam War sparked significant anti-war protests and shaped global politics for decades.",
                    "The Korean War (1950-1953) ended in an armistice, leaving the Korean Peninsula divided.",
                    "The Gulf War (1990-1991) was one of the first conflicts broadcast live on television.",
                    "The Napoleonic Wars reshaped Europe in the early 19th century.",
                    "The Crimean War (1853-1856) saw the first use of the telegraph for military communication.",
                    "The Thirty Years' War (1618-1648) was one of the longest and most destructive conflicts in Europe.",
                    "The Falklands War (1982) highlighted the lingering effects of colonial disputes."
                ]
            },
            "2": {
                "name": "Political Milestones",
                "facts": [
                    "The fall of the Berlin Wall in 1989 symbolized the end of the Cold War.",
                    "Nelson Mandela's release in 1990 marked a significant step toward ending apartheid in South Africa.",
                    "The Declaration of Independence in 1776 laid the foundation for the United States.",
                    "The French Revolution (1789-1799) radically transformed France’s political and social structure.",
                    "India gained independence from British colonial rule in 1947.",
                    "The establishment of the United Nations in 1945 aimed to promote peace and cooperation globally.",
                    "The suffragette movement secured voting rights for women in many countries during the early 20th century.",
                    "The end of the Cold War in 1991 reshaped global political alliances.",
                    "The formation of the European Union helped unify post-war Europe.",
                    "The Arab Spring in the early 2010s spurred political change across several Middle Eastern countries."
                ]
            },
            "3": {
                "name": "Tech & Science Breakthroughs",
                "facts": [
                    "The Apollo 11 moon landing in 1969 was watched live by millions around the globe.",
                    "The invention of the internet revolutionized communication and information sharing.",
                    "The Human Genome Project, completed in 2003, mapped the entire human genetic code.",
                    "The launch of the Hubble Space Telescope in 1990 expanded our view of the universe.",
                    "The discovery of penicillin in 1928 marked the beginning of modern antibiotics.",
                    "The advent of smartphones has transformed everyday communication and connectivity.",
                    "ENIAC, one of the first computers built in 1945, paved the way for the computer age.",
                    "Quantum computing promises to tackle problems beyond the capabilities of classical computers.",
                    "The discovery of the Higgs boson in 2012 confirmed the mechanism that gives particles mass.",
                    "CRISPR technology is revolutionizing genetics through precise gene editing."
                ]
            },
            "4": {
                "name": "Natural Disasters",
                "facts": [
                    "The 2004 Indian Ocean tsunami is one of the deadliest natural disasters in modern history.",
                    "The eruption of Mount Vesuvius in AD 79 famously buried the Roman cities of Pompeii and Herculaneum.",
                    "The 1906 San Francisco earthquake led to massive destruction and a major rebuild of the city.",
                    "Hurricane Katrina in 2005 devastated the Gulf Coast region of the United States.",
                    "The Great Galveston Hurricane of 1900 remains the deadliest natural disaster in U.S. history.",
                    "The 2011 Tōhoku earthquake and tsunami in Japan triggered a nuclear crisis at Fukushima.",
                    "The Dust Bowl of the 1930s severely impacted agriculture and displaced thousands in the American Midwest.",
                    "The 1980 eruption of Mount St. Helens was one of the most significant volcanic events in U.S. history.",
                    "The Lisbon earthquake of 1755 had far-reaching effects on European philosophy and society.",
                    "The Bhola cyclone of 1970 was one of the most catastrophic tropical cyclones ever recorded."
                ]
            },
            "5": {
                "name": "Cultural & Entertainment Events",
                "facts": [
                    "The Beatles’ appearance on The Ed Sullivan Show in 1964 kick-started Beatlemania in the U.S.",
                    "Woodstock in 1969 became an iconic symbol of the counterculture movement.",
                    "The launch of MTV in 1981 revolutionized the music industry and pop culture.",
                    "Blockbuster movies emerged in the 1970s, forever changing the film industry.",
                    "The first Academy Awards in 1929 established a global benchmark for cinematic achievement.",
                    "Reality TV's rise in the early 2000s reshaped modern television programming.",
                    "The global popularity of video games has transformed entertainment and technology industries.",
                    "Social media platforms in the 21st century have redefined celebrity culture and public interaction.",
                    "Streaming services have dramatically changed how audiences consume films and television shows.",
                    "Internet memes have become a defining aspect of digital culture in recent years."
                ]
            }
        }
        
        while True:
            print("\n=== Fun Fact Utility: Biggest News Events in History ===")
            print("Choose a category for a fun fact:")
            for key, value in categories.items():
                print(f"{key}. {value['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Goodbye!")
                break
            elif choice in categories:
                fact = random.choice(categories[choice]["facts"])
                print(f"\nFun Fact from {categories[choice]['name']}:")
                print(fact)
            else:
                print("Invalid choice. Please select a valid category.")
    
    if __name__ == "__main__":
        main()
  • URL Shortener Python Script

    This script is a straightforward and user-friendly URL shortener that leverages the TinyURL API to convert long URLs into compact, shareable links. It prompts the user for a URL, processes it through the API, and then displays both the original and shortened URLs for easy reference.

    This script requires the requests library to handle HTTP requests to the TinyURL API. Make sure to install it with pip install requests before running the script.

    Click to view script…
    #!/usr/bin/env python3
    import requests
    
    def shorten_url(url):
        """
        Shortens the given URL using the TinyURL API.
        
        Parameters:
            url (str): The original URL.
        
        Returns:
            str: The shortened URL or None if something went wrong.
        """
        api_url = 'https://tinyurl.com/api-create.php'
        params = {'url': url}
        try:
            response = requests.get(api_url, params=params)
            if response.status_code == 200:
                return response.text.strip()
            else:
                print(f"Error: Unable to shorten URL. Status code: {response.status_code}")
                return None
        except Exception as e:
            print("Error during request:", e)
            return None
    
    def main():
        print("=== Welcome to the Python URL Shortener ===\n")
        
        # Get URL from user
        original_url = input("Enter the URL you want to shorten: ").strip()
        if not original_url:
            print("No URL provided. Exiting.")
            return
    
        # Get the shortened URL
        shortened_url = shorten_url(original_url)
        if shortened_url:
            # Display the original and shortened URLs
            print("\nHere are your URLs:")
            print("-" * 40)
            print("Original URL:  ", original_url)
            print("Shortened URL: ", shortened_url)
            print("-" * 40)
        else:
            print("Failed to shorten the URL.")
    
    if __name__ == "__main__":
        main()

  • Interactive macOS Countdown Timer Bash Script

    This Bash script creates a countdown timer that either accepts the duration in seconds as a command-line argument or prompts the user for input. It displays the remaining time in the Terminal and sends a native macOS notification when the countdown completes.

    Click to view script…
    #!/bin/bash
    # Simple Countdown Timer for macOS with Interactive Input
    
    # Check if a time (in seconds) was provided as an argument
    if [ $# -eq 0 ]; then
        # Prompt the user for input if no argument is given
        read -p "Enter number of seconds for the countdown: " TIME_LEFT
    else
        TIME_LEFT=$1
    fi
    
    # Validate that the input is a positive integer
    if ! [[ $TIME_LEFT =~ ^[0-9]+$ ]] ; then
        echo "Error: Please enter a positive integer for seconds." >&2
        exit 1
    fi
    
    # Countdown loop
    while [ $TIME_LEFT -gt 0 ]; do
        echo -ne "Time left: ${TIME_LEFT} second(s) \r"
        sleep 1
        ((TIME_LEFT--))
    done
    
    # Move to a new line after the countdown
    echo -e "\nTime's up!"
    
    # Display a macOS notification using osascript
    osascript -e 'display notification "Countdown Complete!" with title "Timer"'
  • Automated Screen Capture AppleScript Tool

    This AppleScript lets you capture screenshots either on demand or at scheduled intervals, automatically saving each capture in a designated folder with a unique, timestamped filename. Notifications alert you whenever a screenshot is taken, ensuring you always know when your screen has been captured.

    Warning: This script requires specific macOS permissions to function correctly. In particular, macOS Catalina and later require that you enable Screen Recording permissions for the app running the script (e.g., Script Editor or Terminal), and you may also need to grant Automation or Full Disk Access in Security & Privacy settings. Without these permissions, the screenshot functionality and notifications might not work as expected.

    Click to view script…
    -- Automated Screen Capture Script
    
    -- Ensure the "Screenshots" folder exists on the Desktop
    do shell script "mkdir -p ~/Desktop/Screenshots"
    
    -- Ask the user to choose a capture mode
    display dialog "Choose Screenshot Mode:" buttons {"On Demand", "Scheduled"} default button "On Demand"
    set modeChoice to button returned of result
    
    if modeChoice is "On Demand" then
        my takeScreenshot()
    else if modeChoice is "Scheduled" then
        display dialog "Enter interval between screenshots (in seconds):" default answer "60"
        set intervalSeconds to (text returned of result) as integer
        
        display dialog "Enter number of screenshots to capture:" default answer "10"
        set numberShots to (text returned of result) as integer
        
        repeat with i from 1 to numberShots
            my takeScreenshot()
            delay intervalSeconds
        end repeat
    end if
    
    -- Handler to take a screenshot and save it with a timestamped filename
    on takeScreenshot()
        -- Create a timestamp
        set timeStamp to do shell script "date +%Y%m%d-%H%M%S"
        set fileName to "Screenshot-" & timeStamp & ".png"
        set filePath to "~/Desktop/Screenshots/" & fileName
        -- Capture the screenshot silently (-x suppresses the shutter sound)
        do shell script "screencapture -x " & filePath
        display notification "Captured: " & fileName with title "Screen Capture"
    end takeScreenshot
  • Flexible Volume Controller AppleScript

    This AppleScript lets you adjust your Mac’s system volume either by selecting from a list of predefined levels (Mute, 0, 25, 50, 75, or 100) or by entering a custom value between 0 and 100, with a notification confirming the change.

    Click to view script…
    -- Volume Controller Script
    
    -- First, choose the control method.
    display dialog "Choose Volume Control Method:" buttons {"Predefined Levels", "Custom Level"} default button "Predefined Levels"
    set methodChoice to button returned of result
    
    if methodChoice is "Predefined Levels" then
        -- Use a list to display multiple predefined options.
        set volumeOptions to {"Mute", "0", "25", "50", "75", "100"}
        set volChoiceList to choose from list volumeOptions with prompt "Select Volume Setting:" default items {"50"}
        
        if volChoiceList is false then
            display notification "No selection made." with title "Volume Controller"
            return
        end if
        
        set volChoice to item 1 of volChoiceList
        if volChoice is "Mute" then
            set volume with output muted
            display notification "Volume muted" with title "Volume Controller"
        else
            set volValue to volChoice as integer
            set volume output volume volValue
            display notification "Volume set to " & volValue & "%" with title "Volume Controller"
        end if
        
    else if methodChoice is "Custom Level" then
        display dialog "Enter desired volume level (0-100):" default answer "50"
        set volInput to text returned of result
        set volLevel to volInput as integer
        
        if volLevel < 0 then
            set volLevel to 0
        else if volLevel > 100 then
            set volLevel to 100
        end if
        
        set volume output volume volLevel
        display notification "Volume set to " & volLevel & "%" with title "Volume Controller"
    end if
  • Light and Dark Mode Toggler AppleScript

    This AppleScript toggles your macOS display between dark and light modes, letting you quickly adapt your favorite setting.

    Click to view script…
    tell application "System Events"
        tell appearance preferences
            set dark mode to not dark mode
        end tell
    end tell

  • USB Device Logger PowerShell Script

    A PowerShell script that logs detailed information about all connected USB devices, including their names, PNP device IDs, and descriptions, along with a timestamp. This tool is ideal for tracking USB connections over time for auditing or troubleshooting purposes.

    Click to view script…
    <#
    .SYNOPSIS
        Logs all USB devices connected to the system.
    
    .DESCRIPTION
        This script uses CIM/WMI to query for USB devices (by filtering for PNPDeviceIDs that start with "USB")
        and logs their details (Name, PNPDeviceID, Description) along with a timestamp. The log is appended to a file,
        which by default is stored in the same directory as the script (USBDeviceLog.txt).
    
    .NOTES
        Run this script with the necessary permissions. 
        Adjust the log file path if needed.
    #>
    
    # Define the log file location (you can change this to an absolute path if desired)
    $logFilePath = Join-Path -Path $PSScriptRoot -ChildPath "USBDeviceLog.txt"
    
    # Get the current timestamp
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    
    # Create the log entry header
    $logEntry = "USB Device Log - $timestamp`r`n" + ("=" * 50) + "`r`n"
    
    # Query for USB devices by filtering Win32_PnPEntity for entries with a PNPDeviceID starting with "USB"
    try {
        $usbDevices = Get-CimInstance -ClassName Win32_PnPEntity | Where-Object { $_.PNPDeviceID -like "USB*" }
    }
    catch {
        Write-Error "Error querying USB devices: $_"
        exit
    }
    
    if ($usbDevices) {
        foreach ($device in $usbDevices) {
            $logEntry += "Name         : " + $device.Name + "`r`n"
            $logEntry += "PNPDeviceID  : " + $device.PNPDeviceID + "`r`n"
            $logEntry += "Description  : " + $device.Description + "`r`n"
            $logEntry += ("-" * 40) + "`r`n"
        }
    }
    else {
        $logEntry += "No USB devices found." + "`r`n"
    }
    
    $logEntry += "`r`n"
    
    # Append the log entry to the log file
    try {
        Add-Content -Path $logFilePath -Value $logEntry
        Write-Host "USB devices logged successfully to $logFilePath" -ForegroundColor Green
    }
    catch {
        Write-Error "Failed to write to log file: $_"
    }
  • Drive Space Information PowerShell Script

    This PowerShell script retrieves and displays space information for all local fixed drives, including total size, free space, used space, and the percentage of free space.

    Click to view script…
    # Get-DriveSpaceInfo.ps1
    # This script retrieves space information for each local drive (DriveType=3) on the computer.
    # It displays the drive letter, total size, free space, used space, and percentage of free space.
    
    # Retrieve local disk drives (DriveType=3 indicates local fixed disks)
    $drives = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"
    
    if (!$drives) {
        Write-Host "No local drives found."
        exit
    }
    
    foreach ($drive in $drives) {
        $driveLetter = $drive.DeviceID
        $totalSize = $drive.Size
        $freeSpace = $drive.FreeSpace
    
        # Calculate used space and percentage of free space (if total size is not zero)
        if ($totalSize -gt 0) {
            $usedSpace = $totalSize - $freeSpace
            $percentFree = [Math]::Round(($freeSpace / $totalSize) * 100, 2)
            $totalSizeGB = [Math]::Round($totalSize / 1GB, 2)
            $freeSpaceGB = [Math]::Round($freeSpace / 1GB, 2)
            $usedSpaceGB = [Math]::Round($usedSpace / 1GB, 2)
        }
        else {
            $usedSpace = 0
            $percentFree = 0
            $totalSizeGB = 0
            $freeSpaceGB = 0
            $usedSpaceGB = 0
        }
    
        Write-Host "Drive: $driveLetter" -ForegroundColor Cyan
        Write-Host "  Total Size: $totalSizeGB GB"
        Write-Host "  Free Space: $freeSpaceGB GB ($percentFree`%)"
        Write-Host "  Used Space: $usedSpaceGB GB"
        Write-Host "-------------------------------------"
    }