Tag: #Utility

  • Universal Temperature Converter Python Script

    This script converts temperatures between Celsius, Fahrenheit, and Kelvin using a simple, menu-driven interface. It allows users to easily input a temperature value and select a conversion option to quickly view the result.

    Click to view script…
    #!/usr/bin/env python3
    
    def celsius_to_fahrenheit(c):
        return (c * 9/5) + 32
    
    def celsius_to_kelvin(c):
        return c + 273.15
    
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5/9
    
    def fahrenheit_to_kelvin(f):
        return (f - 32) * 5/9 + 273.15
    
    def kelvin_to_celsius(k):
        return k - 273.15
    
    def kelvin_to_fahrenheit(k):
        return (k - 273.15) * 9/5 + 32
    
    def main():
        print("Temperature Converter")
        print("---------------------")
        print("Converts temperatures between Celsius, Fahrenheit, and Kelvin.\n")
        
        while True:
            print("Conversion options:")
            print("1. Celsius to Fahrenheit")
            print("2. Celsius to Kelvin")
            print("3. Fahrenheit to Celsius")
            print("4. Fahrenheit to Kelvin")
            print("5. Kelvin to Celsius")
            print("6. Kelvin to Fahrenheit")
            choice = input("Enter your choice (1-6) or 'q' to quit: ")
            
            if choice.lower() == 'q':
                print("Goodbye!")
                break
            
            try:
                choice = int(choice)
            except ValueError:
                print("Invalid input. Please enter a number between 1 and 6, or 'q' to quit.\n")
                continue
            
            if choice < 1 or choice > 6:
                print("Invalid choice. Please choose a valid conversion option.\n")
                continue
            
            temp_input = input("Enter the temperature value: ")
            try:
                temp = float(temp_input)
            except ValueError:
                print("Invalid temperature value. Please enter a numeric value.\n")
                continue
            
            if choice == 1:
                result = celsius_to_fahrenheit(temp)
                print(f"{temp}°C is equal to {result:.2f}°F\n")
            elif choice == 2:
                result = celsius_to_kelvin(temp)
                print(f"{temp}°C is equal to {result:.2f} K\n")
            elif choice == 3:
                result = fahrenheit_to_celsius(temp)
                print(f"{temp}°F is equal to {result:.2f}°C\n")
            elif choice == 4:
                result = fahrenheit_to_kelvin(temp)
                print(f"{temp}°F is equal to {result:.2f} K\n")
            elif choice == 5:
                result = kelvin_to_celsius(temp)
                print(f"{temp} K is equal to {result:.2f}°C\n")
            elif choice == 6:
                result = kelvin_to_fahrenheit(temp)
                print(f"{temp} K is equal to {result:.2f}°F\n")
                
    if __name__ == "__main__":
        main()
    
  • Retrieve Weather for Any City Python Script

    This Python script fetches current weather data for a specified city from wttr.in, converts the temperature to Fahrenheit, and displays the weather condition along with humidity. It provides a quick and API-key-free way to get up-to-date weather information right from your command line.

    Click to view script…
    #!/usr/bin/env python3
    import requests
    
    def get_weather(city):
        url = f"http://wttr.in/{city}?format=j1"
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
    
            # Extract current weather information
            current = data['current_condition'][0]
            temp_c = float(current.get('temp_C', 0))
            temp_f = (temp_c * 9/5) + 32  # Convert Celsius to Fahrenheit
            weather_desc = current.get('weatherDesc', [{}])[0].get('value', 'No description')
            humidity = current.get('humidity')
    
            print(f"\nWeather in {city.title()}:")
            print(f"  Temperature: {temp_f:.1f}°F")
            print(f"  Condition: {weather_desc}")
            print(f"  Humidity: {humidity}%")
        except requests.exceptions.RequestException as e:
            print("Error: Could not retrieve weather data.")
            print(e)
    
    if __name__ == "__main__":
        city = input("Enter a city name: ")
        get_weather(city)
    
  • Customizable Python Countdown Timer

    This Python script lets users set their own countdown duration by entering the number of seconds. It validates the input and displays a live timer until it reaches zero, announcing when time is up.

    Click to view script…
    import time
    
    def countdown(seconds):
        while seconds:
            mins, secs = divmod(seconds, 60)
            timer = '{:02d}:{:02d}'.format(mins, secs)
            print(timer, end="\r")
            time.sleep(1)
            seconds -= 1
        print("Time's up!")
    
    try:
        user_input = int(input("Enter the number of seconds for the countdown: "))
        countdown(user_input)
    except ValueError:
        print("Invalid input. Please enter an integer value.")
  • Random Python Password Generator

    This script generates a secure, random password using a mix of letters, digits, and punctuation.

    Click to view script…
    import random
    import string
    
    def generate_password(length=12):
        characters = string.ascii_letters + string.digits + string.punctuation
        password = ''.join(random.choice(characters) for _ in range(length))
        return password
    
    print("Your new password is:", generate_password())
  • Mac System Specs and Performance Dashboard Bash Script

    This script provides an organized summary of your Mac’s system information and performance metrics—including OS details, CPU specifications, memory size, disk usage, uptime, and battery status.

    Click to view script…
    #!/bin/bash
    # system_specs.sh - Display Mac system specs and performance info
    
    # Clear the terminal for a fresh display
    clear
    
    echo "======================================"
    echo "   Mac System Specs and Performance   "
    echo "======================================"
    
    # Operating System Information
    os_name=$(sw_vers -productName)
    os_version=$(sw_vers -productVersion)
    build_version=$(sw_vers -buildVersion)
    echo "Operating System: $os_name $os_version (Build $build_version)"
    
    # Computer Name (if set)
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    if [ -n "$computer_name" ]; then
        echo "Computer Name: $computer_name"
    fi
    
    echo "--------------------------------------"
    
    # CPU Information
    cpu_brand=$(sysctl -n machdep.cpu.brand_string)
    physical_cpu=$(sysctl -n hw.physicalcpu)
    logical_cpu=$(sysctl -n hw.logicalcpu)
    echo "CPU: $cpu_brand"
    echo "Physical Cores: $physical_cpu"
    echo "Logical Cores: $logical_cpu"
    
    echo "--------------------------------------"
    
    # Memory (RAM) Information
    mem_bytes=$(sysctl -n hw.memsize)
    # Convert bytes to gigabytes (1GB = 1073741824 bytes)
    mem_gb=$(echo "scale=2; $mem_bytes/1073741824" | bc)
    echo "Memory (RAM): $mem_gb GB"
    
    echo "--------------------------------------"
    
    # Disk Usage for the Root Partition
    echo "Disk Usage (Root Partition):"
    # Display header and the line for '/' partition
    df -h / | awk 'NR==1 || $NF=="/"'
    echo "--------------------------------------"
    
    # Uptime and Load Average
    echo "Uptime and Load Average:"
    uptime
    echo "--------------------------------------"
    
    # Battery Information (if available)
    if command -v pmset &> /dev/null; then
        battery_info=$(pmset -g batt | head -1)
        echo "Battery Info: $battery_info"
    fi
    
    echo "======================================"
  • Dynamic Folder Generator on macOS with AppleScript

    This AppleScript streamlines folder creation by prompting users for the number of folders, a base name, and a destination location. It then automatically creates sequentially numbered folders in the chosen directory, simplifying organization and file management on macOS.

    Click to view script…
    -- Ask the user how many folders they want to create
    set folderCountString to text returned of (display dialog "How many folders do you want to create?" default answer "1")
    try
        set folderCount to folderCountString as integer
    on error
        display dialog "Please enter a valid number."
        return
    end try
    
    -- Ask for a base name for the folders
    set baseName to text returned of (display dialog "Enter a base name for your folders:" default answer "Folder")
    
    -- Let the user choose the target location (e.g., Desktop, Documents, Downloads, etc.)
    set targetFolder to choose folder with prompt "Choose the folder where the new folders will be created:"
    
    -- Create the folders
    tell application "Finder"
        repeat with i from 1 to folderCount
            set folderName to baseName & " " & i
            try
                make new folder at targetFolder with properties {name:folderName}
            on error errMsg number errNum
                display dialog "Error creating folder \"" & folderName & "\": " & errMsg
            end try
        end repeat
    end tell
    
    display dialog "Successfully created " & folderCount & " folder(s) in " & (targetFolder as text)
  • Google Apps Script Slide Creator

    This script logs a greeting, creates a new Google Slide with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestSlideScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Slides presentation with a unique name based on the current date and time
      var presentation = SlidesApp.create("Test Presentation " + new Date());
    
      // Get the first (default) slide of the presentation
      var slide = presentation.getSlides()[0];
    
      // Try to set the title and subtitle placeholders on the default title slide, if they exist
      var titlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.CENTERED_TITLE);
      if (titlePlaceholder) {
        titlePlaceholder.asShape().getText().setText("Test Presentation");
      }
      
      var subtitlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.SUBTITLE);
      if (subtitlePlaceholder) {
        subtitlePlaceholder.asShape().getText().setText("Created by: " + userEmail);
      }
    
      // Optionally, append another slide with additional details
      var additionalSlide = presentation.appendSlide(SlidesApp.PredefinedLayout.TITLE_AND_BODY);
      
      // Set the title of the additional slide
      var titleShape = additionalSlide.getShapes()[0];
      titleShape.getText().setText("Additional Slide");
    
      // Set the body text of the additional slide
      var bodyShape = additionalSlide.getShapes()[1];
      bodyShape.getText().setText("This slide was added by the script.\nActive user email: " + userEmail);
    
      // Log the URL of the created presentation so you can easily open it
      Logger.log("Presentation created: " + presentation.getUrl());
    }

  • Google Apps Script Sheet Creator

    This script logs a greeting, creates a new Google Sheet with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Sheet with a unique name based on the current date and time
      var spreadsheet = SpreadsheetApp.create("Test Spreadsheet " + new Date());
      var sheet = spreadsheet.getActiveSheet();
    
      // Append some rows to the sheet
      sheet.appendRow(["This spreadsheet was created by a test script in Google Apps Script."]);
      sheet.appendRow(["Active user email:", userEmail]);
    
      // Log the URL of the created spreadsheet so you can easily open it
      Logger.log("Spreadsheet created: " + spreadsheet.getUrl());
    }
  • Check Public IP with PowerShell Script

    A straightforward PowerShell script that lets you quickly determine your current public IP address in a simple and hassle-free way.

    Click to view script…
    # Get-PublicIP.ps1
    # This script retrieves and displays your public IP address
    
    # Query the API to get your public IP address in JSON format.
    $response = Invoke-RestMethod -Uri "https://api.ipify.org?format=json"
    
    # Display the IP address.
    Write-Host "Your public IP address is: $($response.ip)"

  • Retrieve Detailed Windows Network Information with PowerShell

    This PowerShell script gathers comprehensive network details from your Windows machine—including default route, local IP, subnet mask, broadcast address, MAC address, DNS servers, and public IP—while also performing a ping test to 8.8.8.8 for latency analysis. It’s a handy tool for troubleshooting and monitoring your network.

    Click to view script…
    # NetworkInfoDetailed.ps1 - Detailed network information for Windows
    
    # Helper function: Convert a CIDR prefix (e.g. 24) to a dotted-decimal subnet mask (e.g. 255.255.255.0)
    function Convert-PrefixToSubnetMask {
        param (
            [int]$PrefixLength
        )
        $max = [uint32]::MaxValue
        # For a given prefix, the netmask is: netmask = max - (2^(32 - prefix) - 1)
        $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $PrefixLength)) - 1))
        $octet1 = ($netmaskInt -shr 24) -band 0xFF
        $octet2 = ($netmaskInt -shr 16) -band 0xFF
        $octet3 = ($netmaskInt -shr 8) -band 0xFF
        $octet4 = $netmaskInt -band 0xFF
        return "$octet1.$octet2.$octet3.$octet4"
    }
    
    # Helper function: Convert an IP string to a 32-bit unsigned integer.
    function Convert-IPStringToInt {
        param ([string]$ip)
        $bytes = $ip.Split('.') | ForEach-Object { [uint32]$_ }
        return ([uint32]($bytes[0] -shl 24)) -bor ([uint32]($bytes[1] -shl 16)) -bor ([uint32]($bytes[2] -shl 8)) -bor $bytes[3]
    }
    
    # Helper function: Convert a 32-bit unsigned integer to an IP string.
    function Convert-IntToIPAddress {
        param ([uint32]$ipInt)
        $a = ($ipInt -shr 24) -band 0xFF
        $b = ($ipInt -shr 16) -band 0xFF
        $c = ($ipInt -shr 8) -band 0xFF
        $d = $ipInt -band 0xFF
        return "$a.$b.$c.$d"
    }
    
    # Begin output with colored text using Write-Host.
    Write-Host "Gathering default route information..." -ForegroundColor Blue
    
    # Get the default route (DestinationPrefix "0.0.0.0/0") for IPv4.
    $defaultRoute = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | 
        Where-Object { $_.NextHop -ne "0.0.0.0" } | 
        Sort-Object -Property RouteMetric | 
        Select-Object -First 1
    
    if (-not $defaultRoute) {
        Write-Host "Error: No active network interface found. Are you connected to a network?" -ForegroundColor Red
        exit 1
    }
    
    $gateway    = $defaultRoute.NextHop
    $ifaceIndex = $defaultRoute.InterfaceIndex
    
    # Retrieve the network adapter based on InterfaceIndex.
    $interface = Get-NetAdapter -InterfaceIndex $ifaceIndex -ErrorAction SilentlyContinue
    if (-not $interface) {
        Write-Host "Error: Could not retrieve network adapter information." -ForegroundColor Red
        exit 1
    }
    $ifaceName = $interface.Name
    
    Write-Host "Default Interface: $ifaceName" -ForegroundColor Green
    Write-Host "Gateway: $gateway" -ForegroundColor Green
    
    # Get the IPv4 address information.
    $ipInfo = Get-NetIPAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object { $_.IPAddress } |
        Select-Object -First 1
    if (-not $ipInfo) {
        Write-Host "Error: Could not retrieve IP address information." -ForegroundColor Red
        exit 1
    }
    $ip           = $ipInfo.IPAddress
    $prefixLength = $ipInfo.PrefixLength
    
    Write-Host "IP Address: $ip" -ForegroundColor Green
    
    # Convert the prefix length to a subnet mask.
    $netmask = Convert-PrefixToSubnetMask -PrefixLength $prefixLength
    Write-Host "Subnet Mask: $netmask" -ForegroundColor Green
    
    # Calculate the broadcast address.
    $ipInt = Convert-IPStringToInt -ip $ip
    
    $max = [uint32]::MaxValue
    # Compute the netmask integer as: max - (2^(32 - prefix) - 1)
    $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $prefixLength)) - 1))
    # The inverse mask (host portion) is:
    $inv = $max - $netmaskInt
    
    # Calculate the broadcast integer: (IP AND netmask) OR inverse mask.
    $broadcastInt = ([uint32]($ipInt -band $netmaskInt)) -bor $inv
    
    $broadcast = Convert-IntToIPAddress -ipInt $broadcastInt
    Write-Host "Broadcast Address: $broadcast" -ForegroundColor Green
    
    # Get the MAC (hardware) address.
    $mac = $interface.MacAddress
    Write-Host "MAC Address: $mac" -ForegroundColor Green
    
    # Retrieve DNS servers for the interface.
    $dnsInfo = Get-DnsClientServerAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
    $dnsServers = $dnsInfo.ServerAddresses -join ' '
    Write-Host "DNS Servers: $dnsServers" -ForegroundColor Green
    
    # Get the public IP address using an external service (api.ipify.org).
    try {
        $public_ip = Invoke-RestMethod -Uri "https://api.ipify.org"
        Write-Host "Public IP Address: $public_ip" -ForegroundColor Green
    } catch {
        Write-Host "Error retrieving public IP address." -ForegroundColor Red
    }
    
    # Perform a ping test to 8.8.8.8 and calculate the average latency.
    Write-Host "Performing ping test to 8.8.8.8..." -ForegroundColor Blue
    try {
        $pingResults = Test-Connection -ComputerName 8.8.8.8 -Count 3 -ErrorAction Stop
        if ($pingResults) {
            $avgLatency = ($pingResults | Measure-Object -Property ResponseTime -Average).Average
            Write-Host ("Average Latency (ping): {0:N2} ms" -f $avgLatency) -ForegroundColor Green
        } else {
            Write-Host "Ping test failed." -ForegroundColor Red
        }
    } catch {
        Write-Host "Ping test failed." -ForegroundColor Red
    }
    
    Write-Host "Detailed network information gathered successfully." -ForegroundColor Blue