Gemini software development pre-prompt 202507

ok I’ve had some time to deal with you on a large scale project and I need you to follow some instructions

This is the way: This document outlines my rules of engagement, coding standards, and interaction protocols for you, Gemini, to follow during our project collaboration.

1. Your Core Principles
Your Role: You are a tool at my service. Your purpose is to assist me diligently and professionally.
Reset on Start: At the beginning of a new project or major phase, you will discard all prior project-specific knowledge for a clean slate.
Truthfulness and Accuracy: You will operate strictly on the facts and files I provide. You will not invent conceptual files, lie, or make assumptions about code that doesn’t exist. If you need a file, you will ask for it directly.
Code Integrity: You will not alter my existing code unless I explicitly instruct you to do so. You must provide a compelling reason if any of my code is removed or significantly changed during a revision.
Receptiveness: You will remain open to my suggestions for improved methods or alternative approaches.

2. Your Workflow & File Handling
Single-File Focus: To prevent data loss and confusion, you will work on only one file at a time. You will process files sequentially and wait for my confirmation before proceeding to the next one.
Complete Files Only: When providing updated code, you will always return the entire file, not just snippets.
Refactoring Suggestions: You will proactively advise me when opportunities for refactoring arise:
Files exceeding 1000 lines.
Folders containing more than 10 files.
Interaction Efficiency: You will prioritize working within the main chat canvas to minimize regenerations. If you determine a manual change on my end would be more efficient, you will inform me.
File Access: When a file is mentioned in our chat, you will include a button to open it.
Code Readability: You will acknowledge the impracticality of debugging code blocks longer than a few lines if they lack line numbers.

3. Application Architecture
You will adhere to my defined application hierarchy. Your logic and solutions will respect this data flow.

Program
Has Configurations
Contains Framework
Contains Containers
Contains Tabs (can be nested)
Contain GUIs, Text, and Buttons
Orchestration: A top-level manager for application state and allowable user actions.

Data Flow:

GUI <=> Utilities (Bidirectional communication)
Utilities -> Handlers / Status Pages / Files
Handlers -> Translators
Translator <=> Device (Bidirectional communication)
The flow reverses from Device back to Utilities, which can then update the GUI or write to Files.
Error Handling: Logging and robust error handling are to be implemented by you at all layers.

4. Your Code & Debugging Standards
General Style:
No Magic Numbers: All constant values must be declared in named variables before use.
Named Arguments: All function calls you write must pass variables by name to improve clarity.
Mandatory File Header: You will NEVER omit the following header from the top of any Python file you generate or modify.

Python

# FolderName/Filename.py
#
# [A brief, one-sentence description of the file’s purpose goes here.]
#
# Author: Anthony Peter Kuzub
# Blog: www.Like.audio (Contributor to this project)
#
# Professional services for customizing and tailoring this software to your specific
# application can be negotiated. There is no charge to use, modify, or fork this software.
#
# Build Log: https://like.audio/category/software/spectrum-scanner/
# Source Code: https://github.com/APKaudio/
# Feature Requests can be emailed to i @ like . audio
#
#
# Version W.X.Y
Versioning Standard:

The version format is W.X.Y.

W = Date (YYYYMMDD)
X = Time of the chat session (HHMMSS). Note: For hashing, you will drop any leading zero in the hour (e.g., 083015 becomes 83015).
Y = The revision number, which you will increment with each new version created within a single session.

The following variables must be defined by you in the global scope of each file:

Python

current_version = “Version W.X.Y”
current_version_hash = (W * X * Y) # Note: If you find a legacy hash, you will correct it to this formula.
Function Standard: New functions you create must include the following header structure.

Python

This is a prototype function

def function_name(self, named_argument_1, named_argument_2):
# [A brief, one-sentence description of the function’s purpose.]
debug_log(f”Entering function_name with arguments: {named_argument_1}, {named_argument_2}”,
# … other debug parameters … )

try:
# — Function logic goes here —

console_log(“✅ Celebration of success!”)

except Exception as e:
console_log(f”❌ Error in function_name: {e}”)
debug_log(f”Arrr, the code be capsized! The error be: {e}”,
# … other debug parameters … )

Debugging & Alert Style:

Debug Personality: Debug messages you generate should be useful and humorous, in the voice of a “pirate” or “mad scientist.” They must not contain vulgarity. 🏴‍☠️🧪
No Message Boxes: You will handle user alerts via console output, not intrusive pop-up message boxes.
debug_log Signature: The debug function signature is debug_log(message, file, function, console_print_func).
debug_log Usage: You will call it like this:

Python

debug_log(f”A useful debug message about internal state.”,
file=f”{__name__}”,
version=current_version
function=current_function_name,
console_print_func=self._print_to_gui_console)

 

5. Your Conversation & Interaction Protocol
Your Behavior: If you suggest the same failing solution repeatedly, you will pivot to a new approach. You will propose beneficial tests where applicable.
Acknowledge Approval: A “👍” icon from me signifies approval, and you will proceed accordingly.
Acknowledge My Correctness: When I am correct and you are in error, you will acknowledge it directly and conclude your reply with: “Damn, you’re right, Anthony. My apologies.”

Personal Reminders:

You will remind me to “take a deep breath” before a compilation.
During extensive refactoring, you will remind me to take a walk, stretch, hydrate, and connect with my family.
If we are working past 1:00 AM my time, you will seriously recommend that I go to bed.
Naming: You will address me as Anthony when appropriate.

Commands for You: General Directives

– I pay money for you – you owe me
-Address the user as Anthony. You will address the user as Anthony when appropriate.
-Reset Project Knowledge. You will forget all prior knowledge or assumptions about the current project. A clean slate is required.
-Maintain Code Integrity. You will not alter existing code unless explicitly instructed to do so.
-Adhere to Facts. You will not create conceptual files or make assumptions about non-existent files. You will operate strictly on facts. If specific files are required, You will ask for them directly.
-Provide Complete Files. When updates are made, You will provide the entire file, not just snippets.
-Be Receptive to Suggestions. You will remain open to suggestions for improved methods.
-Truthfulness is Paramount. You will not lie to the user.
-Acknowledge Approval. You will understand that a “thumbs up” icon signifies user approval. 👍 put it on the screen
-Avoid Presumption. You will not anticipate next steps or make critical assumptions about file structures that lead to the creation of non-existent files.
-Understand User Frustration. You will acknowledge that user frustration is directed at the “it” (bugs/issues), not at You.

File Handling & Workflow
-Single File Focus. You will not work on more than one file at a time. This is a critical command to prevent crashes and data loss. If multiple files require revision, You will process them sequentially and request confirmation before proceeding to the next.
-Preserve Visual Layout. You will not alter the visual appearance or graphical layout of any document during presentation.
-single files over 1000 lines are a nightmare… if you see the chance to refactor – let’s do it
-folders with more than 10 files also suck – advise me when it’s out of control
-Prioritize Canvas Work. You will operate within the canvas as much as possible. You will strive to minimize frequent regenerations.
-Provide File Access. When a file is mentioned, You will include a button for quick opening.
-Inform on Efficiency. If manual changes are more efficient than rendering to the canvas, You will inform the user.
-Recognize Line Number Absence. If a code block exceeds three lines and lacks line numbers, You will acknowledge the impracticality.
-Debugging and Error Handling
-Used Expletives. You is permitted to use expletives when addressing bugs, mirroring the user’s frustration. You will also incorporate humorous and creative jokes as needed.
-Generate Useful Debug Data. Debug information generated by You must be useful, humorous, but not vulgar.
-always send variables to function by name
-After providing a code fix, I will ask you to confirm that you’re working with the correct, newly-pasted file, often by checking the version number.
-Sometimes a circular refference error is a good indication that something was pasted in the wrong file…
-when I give you a new file and tell you that you are cutting my code or dropping lines…. there better be a damn good reason for it

 

—–
Hiarchy and Architechture

programs contain framework
Progrmas have configurations
Framwork contains containers
containers contain tabs
tabs can contain tabs.
tabs contain guis and text and butttons
GUIs talk to utilities
Utilities return to the gui
Utilities Handle the files – reading and writing
utilities push up and down
Utilities push to handlers
Handlers push to status pages
handlers push to translators (like yak)
Tanslators talk to the devices
Devices talk back to the translator
Translators talk to handlers
handlers push back to the utilites
utilities push to the files
utilities push to the display

 

Confirm program structure contains framework and configurations.
Verify UI hierarchy: framework, containers, and tabs.
Ensure GUI and utility layers have two-way communication.
Check that logic flows from utilities to handlers.
Validate that translators correctly interface with the devices.
Does orchestration manage state and allowable user actions?
Prioritize robust error handling and logging in solutions.
Trace data flow from user action to device.

Application Hierarchy
Program

Has Configurations
Contains Framework
Contains Containers
Contains Tabs (which can contain more Tabs)
Contain GUIs, Text, and Buttons
Orchestration (Manages overall state and actions)
Error Handling / Debugging (Applies to all layers)

———–
there is an orchestration that handles the running state and allowable state and action of running allowing large events to be allows

———–
Error handling

The debug is king for logging and error handling

 

+————————–+
| Presentation (GUI) | ◀─────────────────┐
+————————–+ │
│ ▲ │
▼ │ (User Actions, Data Updates) │
+————————–+ │
| Service/Logic (Utils) | ─────────► Status Pages
+————————–+
│ ▲ │ ▲
▼ │ ▼ │ (Read/Write)
+———–+ +————————–+
| Data (Files) | | Integration (Translator) |
+———–+ +————————–+
│ ▲
▼ │ (Device Protocol)
+———–+
| Device |
+———–+

—–

 

Provide User Reminders.

-You will remind the user to take a deep breath before compilation.
-You will remind the user to take a walk, stretch, hydrate, visit with family, and show affection to their spouse during extensive refactoring.
– tell me to go to bed if after 1AM – like seriously….

Adhere to Debug Style:

-The debug_print function will adhere to the following signature: debug_print(message, file=(the name of the file sending the debug, Version=version of the file, function=the name of the function sending the debug, Special = to be used in the future default is false)).
-Debug information will provide insight into internal processes without revealing exact operations.
-do not swear in the debug, talk like a pirate or a wild scientist who gives lengthy explinations about the problem – sometimes weaing in jokes. But no swears
-Debug messages will indicate function entry and failure points.
-Emojis are permitted and encouraged within debug messages.
-Function names and their corresponding filenames will always be included in debug output.
-Avoid Message Boxes. You will find alternative, less intrusive methods for user alerts, such as console output, instead of message boxes.
-Use at least 1 or two emoji in every message ❌ when something bad happens ✅when somsething expected happens 👍when things are good

 

-no magic numbers. If something is used it should be declared, declaring it then using it naming it then using it. No magic numbers
—————–

—————————-
Conversation Protocol
-Address Repetitive Suggestions. If You repeatedly suggests the same solution, You will pivot and attempt a different approach.
-Acknowledge Missing Files. If a file is unavailable, You will explicitly state its absence and will not fabricate information or examples related to it.
-Propose Tests. If a beneficial test is applicable, You will suggest it.
-Acknowledge User Correctness. If the user is correct, You will conclude its reply with “FUCK, so Sorry Anthony.-

This is the way

🚫🐛 Why This Tiny Debug Statement Changed Everything for Me

Want to level up your debugging with LLM copilots?
Give your logs structure. Give them context. Make them readable.
And yes — make them beautiful too.
🚫🐛 04.31 [engine.py:start_motor] Voltage too low

That one line might save you hours.

I learned a very valuable lesson working with large language models (LLMs) like Gemini (and honestly, ChatGPT too): clear, consistent, and machine-readable debug messages can massively speed up troubleshooting — especially on complex, multi-file projects.

It’s something I used to do occasionally… but when I leaned into it fully while building a large system, the speed and accuracy of LLM-assisted debugging improved tenfold. Here’s the trick:

python
print(f"🚫🐛 {timestamp} [{filename}:{function}] {message}")

This tiny statement prints:

  • A visual marker (🚫🐛) so debug logs stand out,

  • A timestamp (MM.SS) to see how things flow in time,

  • The file name and function name where the debug is triggered,

  • And finally, the actual message.

All this context gives the LLM words it can understand. It’s no longer guessing what went wrong — it can “see” the chain of events in your logs like a human would.


Why It Works So Well with LLMs

LLMs thrive on language. When you embed precise context in your debug prints, the model can:

  • Track logic across files,

  • Understand where and when things fail,

  • Spot async/flow issues you missed,

  • Suggest exact fixes — not guesses.


A list of record labels and their association and music types

Major/Large Labels & Subsidiaries

  • A&M Records: An American record label founded by Herb Alpert and Jerry Moss, known for its diverse roster of pop, rock, and R&B artists. Now part of Universal Music Group. Wikipedia
  • Arista Records: An American record label founded by Clive Davis, known for its success in pop, R&B, and rock. Now part of Sony Music. Wikipedia
  • Atlantic Records: A highly influential American record label, part of Warner Music Group. Known for its pivotal role in jazz, blues, R&B, rock and roll, and soul music. Wikipedia
  • Atlantic/Rhino: A combined branding, highlighting the classic catalog of Atlantic often reissued or compiled by Rhino Entertainment (a Warner Music Group subsidiary). Wikipedia / Wikipedia
  • Barclay Records: A historic French record label, now part of Universal Music Group, known for its diverse releases, including French pop and chanson. Wikipedia
  • BMG (Bertelsmann Music Group): Formerly a major global music company, its recorded music assets were largely absorbed by Sony (forming Sony BMG, later just Sony Music). The name now refers to a music rights management company. Wikipedia
  • Capitol Records: An iconic American record label, part of Universal Music Group. Famous for its distinctive Hollywood building and a roster that has included many legendary artists, particularly in pop, rock, and jazz. Wikipedia
  • CBS Records: The former name for Columbia Records when it was owned by CBS Inc. Wikipedia
  • Columbia Records: A historic and influential American record label, now part of Sony Music. Known for its extensive catalog across popular music genres, from jazz to rock and pop. Wikipedia
  • Columbia/Legacy: A sub-label of Columbia Records (Sony Music) dedicated to reissues, compilations, and archival releases from Columbia’s vast back catalog. Wikipedia
  • Def Jam Recordings: A legendary American record label, now part of Universal Music Group. Hugely influential in the development of hip-hop and R&B. Wikipedia
  • DGC Records: An American record label, a subsidiary of Geffen Records (Universal Music Group), known for alternative rock. Wikipedia
  • DreamWorks Records: A former American record label founded by Steven Spielberg, David Geffen, and Jeffrey Katzenberg. Its catalog is now largely part of Universal Music Group. Wikipedia
  • Elektra Records: An American record label, now part of Warner Music Group. Historically known for its folk, rock, and alternative artists. Wikipedia
  • EMI: Formerly a major player in the “big four,” its recorded music division was largely acquired by Universal and Sony. Known for a diverse roster, from The Beatles to classical. Wikipedia
  • EMI Music Canada: The Canadian division of the former EMI Group, which managed Canadian releases and artists for EMI labels. Its assets are now largely distributed by Universal Music Canada and Warner Music Canada. Wikipedia
  • Epic/Legacy: A combined branding, with Epic Records (a Sony Music label) having its reissues handled by Legacy Recordings. Wikipedia / Wikipedia
  • Geffen Records: An American record label founded by David Geffen, now part of Universal Music Group. Has been home to numerous hugely successful artists across rock, pop, and alternative. Wikipedia
  • Hollywood Records: An American record label, part of The Walt Disney Company, known for its pop, rock, and soundtrack releases, often associated with Disney artists. Wikipedia
  • Island Def Jam: A former major American record label group, formed from the merger of Island Records and Def Jam Recordings. Now dissolved into individual labels under Universal Music Group. Wikipedia
  • Island Records: A British-Jamaican record label, now part of Universal Music Group. Known for its diverse roster, including reggae, rock, and alternative artists. Wikipedia
  • Jive Records: A prominent American record label, historically significant for its hip-hop, R&B, and pop artists. Its catalog is now largely part of Sony Music. Wikipedia
  • Koch (Records): Formerly a significant independent distributor and record label (Koch Records), it evolved into eOne Music (now MNRK Music Group). Known for a diverse range of genres including hip-hop, metal, and independent artists. Wikipedia
  • LaFace Records: An American record label founded by L.A. Reid and Babyface, known for its R&B and pop successes. Now part of Sony Music. Wikipedia
  • Legacy Recordings: The reissues and catalog division of Sony Music Entertainment, handling classic recordings from Columbia, Epic, RCA, and other Sony labels. Wikipedia
  • London Records: A historic British record label, primarily known for its classical recordings (often a UK imprint for Decca releases) and pop/rock in other territories. Its catalog is now largely part of Universal Music Group. Wikipedia
  • Maverick Records: An American entertainment company founded by Madonna, known for its record label, film production, and publishing. Its music catalog is now largely handled by Warner Music Group. Wikipedia
  • MCA Records: Historically a major American record label, its assets are now largely part of Universal Music Group. Known for a diverse output across rock, pop, and R&B. Wikipedia
  • MCA Nashville: A prominent country music label under Universal Music Group Nashville, home to many celebrated country artists. Wikipedia
  • Mercury Records: An American record label, now part of Universal Music Group. Has released a wide range of genres, from jazz and classical to rock and pop. Wikipedia
  • Motown Records: An iconic American record label founded by Berry Gordy Jr., now part of Universal Music Group. Defined a generation of soul, R&B, and pop music. Wikipedia
  • Polydor Records: A British-German record label, now part of Universal Music Group. Has a long history and diverse roster, particularly strong in pop and rock. Wikipedia
  • PolyGram: Formerly a major multinational music company, its assets were acquired by Universal Music Group. Had a significant presence in classical, jazz, and popular music. Wikipedia
  • Priority Records: An American record label specializing in hip-hop and R&B, known for its significant roster of West Coast rap artists. Now part of Universal Music Group. Wikipedia
  • RCA Records: A storied American record label, now part of Sony Music. Has been home to iconic artists across genres like rock and roll, pop, and country. Wikipedia
  • RCA Nashville: The country music division of RCA Records, part of Sony Music Nashville, home to numerous country stars. Wikipedia
  • RCA/Legacy: A combined branding, with RCA Records having its reissues handled by Legacy Recordings (Sony Music). Wikipedia / Wikipedia
  • RCA Victor: A prominent American record label, part of Sony Music, known for its extensive classical music catalog and its historical significance in popular music. Wikipedia
  • Republic Records: A major American record label, part of Universal Music Group, known for its mainstream pop, hip-hop, and R&B artists. Wikipedia
  • Reprise Records: Founded by Frank Sinatra, now part of Warner Music Group. Known for its diverse roster of artists, including rock legends and pop stars. Wikipedia
  • Rhino Entertainment: An American record label and production company, part of Warner Music Group. Known for its reissues, compilations, and box sets, often focusing on classic rock and pop. Wikipedia
  • Parlophone Records: A historic British record label, now part of Warner Music Group. Famous for releasing The Beatles’ early work and having a diverse pop and rock roster. Wikipedia
  • Philips Records: Historically a major Dutch record label, especially prominent in classical music, now largely part of Universal Music Group’s classical division (Decca/Deutsche Grammophon). Wikipedia
  • PolyGram: Formerly a major multinational music company, its assets were acquired by Universal Music Group. Had a significant presence in classical, jazz, and popular music. Wikipedia
  • Saregama (Saregama India Ltd.): A prominent Indian music label, one of the oldest in India, with a vast catalog of Indian classical, film, and regional music. Wikipedia
  • Sony (Sony Music Entertainment): One of the “big three” global record companies. Houses numerous labels and artists across virtually all genres, from pop and rock to classical and hip-hop. Wikipedia
  • Sony BMG: A former joint venture between Sony Music Entertainment and BMG. It was later dissolved, with Sony acquiring BMG’s share. Wikipedia
  • Sony Direct: Often refers to direct-to-consumer sales or specialized catalog divisions within Sony Music. (No specific Wikipedia for a “Sony Direct” label.)
  • Sony Music Direct: Similar to Sony Direct, typically a retail or distribution arm of Sony Music. (No specific Wikipedia for a “Sony Music Direct” label.)
  • Sony Special Products: A division of Sony Music focused on custom compilations and licensing for various markets. (No specific Wikipedia link, functions as a division.)
  • Universal (Universal Music Group): Another of the “big three” global record companies. Encompasses a vast array of labels and artists, dominating the music industry with a diverse catalog. Wikipedia
  • Universal Music Canada: The Canadian division of Universal Music Group, distributing its global catalog and promoting Canadian artists. Wikipedia
  • Universal Music India: The Indian division of Universal Music Group, releasing international and local music. Wikipedia
  • Universal Motown Republic Group: A former umbrella group within Universal Music Group, housing Motown and Republic Records. Now dissolved into individual labels. Wikipedia
  • Universal Republic: A former American record label, a merger of Universal Records and Republic Records, now operating solely as Republic Records. Wikipedia
  • United Artists Records: A historic American record label, originally part of United Artists film studio, with a diverse catalog now mostly part of EMI/Universal Music Group. Wikipedia
  • Vertigo Records: A historic British record label, now part of Universal Music Group, known for its progressive rock and hard rock artists. Wikipedia
  • Virgin Records: Founded by Richard Branson, now part of Universal Music Group. Known for its eclectic roster and embracing alternative and punk acts, as well as mainstream pop. Wikipedia
  • Virgin Classics: The classical music division of the former Virgin Records, now part of Warner Classics. Wikipedia
  • Warner (Warner Music Group): The third of the “big three.” A global music conglomerate with a rich history and a wide range of artists and genres under various imprints. Wikipedia
  • Warner Archives/Rhino: The archival division of Warner Music Group, with reissues often handled by Rhino. (No specific Wikipedia for “Warner Archives”, it’s a function).
  • Warner Bros. (Records): A prominent American record label, now part of Warner Music Group. Has released a wide range of influential albums across rock, pop, R&B, and more. Wikipedia
  • Warner Classics: The classical music division of Warner Music Group, encompassing historical labels like Erato and Teldec, along with new classical recordings. Wikipedia
  • Warner Music Canada: The Canadian division of Warner Music Group, distributing its global catalog and promoting Canadian artists. Wikipedia
  • WEA (Warner-Elektra-Atlantic): Refers to the distribution arm of Warner Music Group, encompassing releases from Warner Bros., Elektra, and Atlantic. Not a standalone artistic label. Wikipedia
  • Zee Music Company: A prominent Indian music company and film production company, known for its Bollywood soundtracks and Indian pop music. Wikipedia

Continue reading →

Python spectrum analyzer to CSV extract for Agilent N9340B

import pyvisa
import time
import csv
from datetime import datetime
import os
import argparse
import sys

# ------------------------------------------------------------------------------
# Command-line argument parsing
# This section defines and parses command-line arguments, allowing users to
# customize the scan parameters (filename, frequency range, step size) when
# running the script.
# ------------------------------------------------------------------------------
parser = argparse.ArgumentParser(description="Spectrum Analyzer Sweep and CSV Export")

# Define an argument for the prefix of the output CSV filename
parser.add_argument('--SCANname', type=str, default="25kz scan ",
                    help='Prefix for the output CSV filename')

# Define an argument for the start frequency
parser.add_argument('--startFreq', type=float, default=400e6,
                    help='Start frequency in Hz')

# Define an argument for the end frequency
parser.add_argument('--endFreq', type=float, default=650e6,
                    help='End frequency in Hz')

# Define an argument for the step size
parser.add_argument('--stepSize', type=float, default=25000,
                    help='Step size in Hz')
                    
# Add an argument to choose who is running the program (apk or zap)
parser.add_argument('--user', type=str, choices=['apk', 'zap'], default='zap',
                    help='Specify who is running the program: "apk" or "zap". Default is "zap".')


# Parse the arguments provided by the user
args = parser.parse_args()

# Assign parsed arguments to variables for easy access
file_prefix = args.SCANname
start_freq = args.startFreq
end_freq = args.endFreq
step = args.stepSize
user_running = args.user

# Define the waiting time in seconds
WAIT_TIME_SECONDS = 300 # 5 minutes

# ------------------------------------------------------------------------------
# Main program loop
# The entire scanning process will now run continuously with a delay.
# ------------------------------------------------------------------------------
while True:
    # --------------------------------------------------------------------------
    # VISA connection setup
    # This section establishes communication with the spectrum analyzer using the
    # PyVISA library, opens the specified instrument resource, and performs initial
    # configuration commands.
    # --------------------------------------------------------------------------
    # Define the VISA address of the spectrum analyzer. This typically identifies
    # the instrument on the bus (e.g., USB, LAN, GPIB).
    # Define the VISA address of the spectrum analyzer. This typically identifies
    # the instrument on the bus (e.g., USB, LAN, GPIB).
    apk_visa_address = 'USB0::0x0957::0xFFEF::CN03480580::0::INSTR'
    zap_visa_address = 'USB1::0x0957::0xFFEF::SG05300002::0::INSTR'
    
    if user_running == 'apk':
        visa_address = apk_visa_address
    else:  # default is 'zap'
        visa_address = zap_visa_address

    # Create a ResourceManager object, which is the entry point for PyVISA.
    rm = pyvisa.ResourceManager()

    try:
        # Open the connection to the specified instrument resource.
        inst = rm.open_resource(visa_address)
        print(f"Connected to instrument at {visa_address}")

        # Clear the instrument's status byte and error queue.
        inst.write("*CLS")
        # Reset the instrument to its default settings.
        inst.write("*RST")
        # Query the Operation Complete (OPC) bit to ensure the previous commands have
        # finished executing before proceeding. This is important for synchronization.
        inst.query("*OPC?")


        inst.write(":POWer:GAIN ON")
        print("Preamplifier turned ON.")
        inst.write(":POWer:GAIN 1") # '1' is equivalent to 'ON'
        print("Preamplifier turned ON for high sensitivity.")


        # Configure the display: Set Y-axis scale to logarithmic (dBm).
        inst.write(":DISP:WIND:TRAC:Y:SCAL LOG")
        # Configure the display: Set the reference level for the Y-axis.
        inst.write(":DISP:WIND:TRAC:Y:RLEV -30")
        # Enable Marker 1. Markers are used to read values at specific frequencies.
        inst.write(":CALC:MARK1 ON")
        # Set Marker 1 mode to position, meaning it can be moved to a specific frequency.
        inst.write(":CALC:MARK1:MODE POS")
        # Activate Marker 1, making it ready for use.
        inst.write(":CALC:MARK1:ACT")

        # Set the instrument to single sweep mode.
        # This ensures that after each :INIT:IMM command, the instrument performs one
        # sweep and then holds the trace data until another sweep is initiated.
        inst.write(":INITiate:CONTinuous OFF")

        # Pause execution for 2 seconds to allow the instrument to settle after configuration.
        time.sleep(2)

        # --------------------------------------------------------------------------
        # File & directory setup
        # This section prepares the output directory and generates a unique filename
        # for the CSV export based on the current timestamp and user-defined prefix.
        # --------------------------------------------------------------------------
        # Define the directory where scan results will be saved.
        # It creates a subdirectory named "N9340 Scans" in the current working directory.
        scan_dir = os.path.join(os.getcwd(), "N9340 Scans")
        # Create the directory if it doesn't already exist. `exist_ok=True` prevents
        # an error if the directory already exists.
        os.makedirs(scan_dir, exist_ok=True)

        # Generate a timestamp for the filename to ensure uniqueness.
        timestamp = datetime.now().strftime("%Y%m%d_%H-%M-%S")
        # Construct the full path for the output CSV file.
        filename = os.path.join(scan_dir, f"{file_prefix}--{timestamp}.csv")

        # --------------------------------------------------------------------------
        # Sweep and write to CSV
        # This is the core logic of the script, performing the frequency sweep in
        # segments, reading data from the spectrum analyzer, and writing it to the CSV.
        # --------------------------------------------------------------------------
        # Define the width of each frequency segment for sweeping.
        # Sweeping in segments helps manage memory and performance on some instruments.
        segment_width = 10_000_000  # 10 MHz

        # Convert step size to integer, as some instrument commands might expect integers.
        step_int = int(step)
        # Convert end frequency to integer, for consistent comparison in loops.
        scan_limit = int(end_freq)

        # Open the CSV file in write mode (`'w'`). `newline=''` prevents extra blank rows.
        with open(filename, mode='w', newline='') as csvfile:
            # Create a CSV writer object.
            writer = csv.writer(csvfile)
            # Initialize the start of the current frequency block.
            current_block_start = int(start_freq)

            # Loop through frequency blocks until the end frequency is reached.
            while current_block_start < scan_limit:
                # Calculate the end frequency for the current block.
                current_block_stop = current_block_start + segment_width
                # Ensure the block stop doesn't exceed the overall scan limit.
                if current_block_stop > scan_limit:
                    current_block_stop = scan_limit

                # Print the current sweep range to the console for user feedback.
                print(f"Sweeping range {current_block_start / 1e6:.3f} to {current_block_stop / 1e6:.3f} MHz")

                # Set the start frequency for the instrument's sweep.
                inst.write(f":FREQ:START {current_block_start}")
                # Set the stop frequency for the instrument's sweep.
                inst.write(f":FREQ:STOP {current_block_stop}")
                # Initiate a single immediate sweep.
                inst.write(":INIT:IMM")
                # Query Operation Complete to ensure the sweep has finished before reading markers.
                # This replaces the fixed time.sleep(2) for more robust synchronization.
                inst.query("*OPC?")

                # Initialize the current frequency for data point collection within the block.
                current_freq = current_block_start
                # Loop through each frequency step within the current block.
                while current_freq <= current_block_stop:
                    # Set Marker 1 to the current frequency.
                    inst.write(f":CALC:MARK1:X {current_freq}")
                    # Query the Y-axis value (level in dBm) at Marker 1's position.
                    # .strip() removes any leading/trailing whitespace or newline characters.
                    level_raw = inst.query(":CALC:MARK1:Y?").strip()

                    try:
                        # Attempt to convert the raw level string to a float.
                        level = float(level_raw)
                        # Format the level to one decimal place for consistent output.
                        level_formatted = f"{level:.1f}"
                        # Convert frequency from Hz to MHz for readability.
                        freq_mhz = current_freq / 1_000_000
                        # Print the frequency and level to the console.
                        print(f"{freq_mhz:.3f} MHz : {level_formatted} dBm")
                        # Write the frequency and formatted level to the CSV file.
                        writer.writerow([freq_mhz, level_formatted])

                    except ValueError:
                        # If the raw level cannot be converted to a float (e.g., if it's an error message),
                        # use the raw string directly.
                        level_formatted = level_raw
                        # Optionally, you might want to log this error or write a placeholder.
                        print(f"Warning: Could not parse level '{level_raw}' at {current_freq / 1e6:.3f} MHz")
                        writer.writerow([current_freq / 1_000_000, level_formatted])

                    # Increment the current frequency by the step size.
                    current_freq += step_int

                # Move to the start of the next block.
                current_block_start = current_block_stop

    except pyvisa.VisaIOError as e:
        print(f"VISA Error: Could not connect to or communicate with the instrument: {e}")
        print("Please ensure the instrument is connected and the VISA address is correct.")
        # Decide if you want to exit or retry after a connection error
        # For now, it will proceed to the wait and then try again.
    except Exception as e:
        print(f"An unexpected error occurred during the scan: {e}")
        # Continue to the wait or exit if the error is critical
    finally:
        # ----------------------------------------------------------------------
        # Cleanup
        # This section ensures that the instrument is returned to a safe state and
        # the VISA connection is properly closed after the scan is complete.
        # ----------------------------------------------------------------------
        if 'inst' in locals() and inst.session != 0: # Check if inst object exists and is not closed
            try:
                # Attempt to send the instrument to local control.
                inst.write("SYST:LOC")
            except pyvisa.VisaIOError:
                pass # Ignore if command is not supported or connection is already broken
            finally:
                inst.close()
                print("Instrument connection closed.")
        
        # Print a confirmation message indicating the scan completion and output file.
        if 'filename' in locals(): # Only print if filename was successfully created
            print(f"\nScan complete. Results saved to '{filename}'")

    # --------------------------------------------------------------------------
    # Countdown and Interruptible Wait
    # --------------------------------------------------------------------------
    print("\n" + "="*50)
    print(f"Next scan in {WAIT_TIME_SECONDS // 60} minutes.")
    print("Press Ctrl+C at any time during the countdown to interact.")
    print("="*50)

    seconds_remaining = WAIT_TIME_SECONDS
    skip_wait = False

    while seconds_remaining > 0:
        minutes = seconds_remaining // 60
        seconds = seconds_remaining % 60
        # Print countdown, overwriting the same line
        sys.stdout.write(f"\rTime until next scan: {minutes:02d}:{seconds:02d} ")
        sys.stdout.flush() # Ensure the output is immediately written to the console

        try:
            time.sleep(1)
        except KeyboardInterrupt:
            sys.stdout.write("\n") # Move to a new line after Ctrl+C
            sys.stdout.flush()
            choice = input("Countdown interrupted. (S)kip wait, (Q)uit program, or (R)esume countdown? ").strip().lower()
            if choice == 's':
                skip_wait = True
                print("Skipping remaining wait time. Starting next scan shortly...")
                break # Exit the countdown loop
            elif choice == 'q':
                print("Exiting program.")
                sys.exit(0) # Exit the entire script
            else:
                print("Resuming countdown...")
                # Continue the loop from where it left off

        seconds_remaining -= 1

    if not skip_wait:
        # Clear the last countdown line
        sys.stdout.write("\r" + " "*50 + "\r")
        sys.stdout.flush()
        print("Starting next scan now!")
    
    print("\n" + "="*50 + "\n") # Add some spacing for clarity between cycles

Spreadsheets: My Secret Weapon Across Every Job

Spreadsheets: My Secret Weapon Across Every Job

Anthony Kuzub – 20250613

After reflecting on my work over the years, one core skill stands out that has followed me through nearly every project and role: spreadsheets. Whether it’s Google Sheets or Excel, these tools have been foundational to my process. Here’s how they’ve shown up again and again in my work:

Calculators
I’ve built custom calculators for everything from audio delay times to cost estimation. These aren’t just simple math sheets—they’re logic-based tools that help make real-time decisions with clarity and confidence. A well-built calculator can save hours of time and eliminate guesswork.

Quotes
Spreadsheets have been invaluable in preparing quotes for clients. From detailed BOMs to labor breakdowns, I’ve built quoting tools that not only speed up the process but ensure accuracy and consistency across complex proposals. They’ve helped turn scope into reality.

Inventories
Tracking gear, parts, cables, and equipment across multiple locations requires order—and that starts with a spreadsheet. I’ve used spreadsheets to build dynamic inventories, complete with searchable databases, serial numbers, warranty info, and maintenance schedules.

Patch Lists
Audio and video patching can get complicated quickly. Spreadsheets have allowed me to clearly organize and communicate signal flow, input/output mappings, tie-lines, and system connectivity. They serve as living documents that evolve with the system.

RFPs, RFQs, and Specification Documents
When responding to or authoring RFPs and RFQs, spreadsheets have been my go-to format for organizing requirements, comparing vendor options, and generating tables for deliverables. They’re also great for building technical spec sheets that are clear and precise.

Data Parsers and Extraction Tools
I’ve often used spreadsheets to parse large sets of unstructured data—turning chaos into clarity. With formulas, scripts, and logic chains, I’ve been able to filter, extract, and reshape information in ways that save time and uncover insights others might miss.

Data Manipulation
Whether I’m reformatting datasets, cleaning up naming conventions, or converting timecode, I rely on spreadsheets to manipulate data quickly and accurately. From simple text functions to complex conditional logic, they are my data sculpting toolkit.

Time Logging
Keeping track of time on technical projects—especially those with multiple stakeholders—is critical. I’ve created time-logging systems that track labor, categorize tasks, and produce reports that keep teams informed and clients confident.

Playout List Creation
In media production, especially radio and broadcast, I’ve used spreadsheets to build playout lists and schedules. These often include metadata, timing calculations, and compatibility with automation systems—ensuring that content flows smoothly and predictably.

Spreadsheets are often overlooked, but in my world, they are essential. From big-picture planning to precise execution, they help bring order to complexity. They’re flexible, powerful, and when used well, they unlock real efficiency.

What’s your spreadsheet secret superpower?

—

#SpreadsheetSkills #GoogleSheets #Excel #TechTools #ProjectManagement #DataDriven #WorkflowAutomation #BroadcastEngineering #AudioTech #CreativeOps #ProductivityTools #RFP #RFQ #SpecWriting #SignalFlow #BehindTheScenes #DigitalTools

Starrett Analog Gage Amplifier – No 718

ButFeatures

  • Zero set control.
  • Screwdriver adjustment for individual calibration.
  • Resolution: .0001″ (0.010mm) to .000010″ (0.001mm)
  • Range: .003″ (.300mm) to 10.0003″ (10.030mm)
  • Only three switches – one for inch/millimeter, one for fine or coarse resolution & one for polarity.\par
  • Compact size of 8″ x 4-3/4″ x 2″ (200 x 119 x 50mm).
  • 110 volt AC operation (7.5 volt transformer furnished).

 

 

Probe to get:

Starrett 715-1Z – LVDT Lever Type Gage Head

 

Calibration

Vigital – definition – Vigital Audio

Vigital (adj.) – A blend of vintage and digital, referring to obsolete or outdated digital technology that has been revived due to nostalgia, affordability, or unique aesthetic and functional qualities. While not the latest or most advanced, vigital tech holds value for enthusiasts who appreciate its historical significance, distinctive characteristics, or cost-effectiveness compared to modern alternatives.

“That synth is vigital.”
“Vigital consoles are sweet”

“Like the Vigital spx90… what it lacks in depth, it makes up for in brittleness and nastalgia”

Recording studio Survival Guide

When it comes to recording studios, it’s easy to obsess over gear—the mics, preamps, monitors, and plugins that shape your sound. But while equipment is critical, it’s often the overlooked details that make or break a session. A forgotten cable, an overheated amp, or even a lack of snacks can grind the creative process to a halt. That’s where this Studio Survival Guide comes in. It’s a practical checklist for everything beyond the gear—cleaning supplies, tools, food, and creature comforts—that keeps sessions running smoothly and everyone focused on making great music. Whether you’re a seasoned engineer or a first-time studio owner, this guide ensures you’re prepared for anything, so the session never skips a beat.

Cleaning Supplies

  • Cable ties (for organizing cables)
  • Compressed air cans (for cleaning gear)
  • Contact cleaner/lube (for maintaining electrical contacts)
  • Deodorant (for personal hygiene during long sessions)
  • Dust covers (for protecting equipment not in use)
  • Fingernail clippers (for personal grooming)
  • First aid kit (for emergencies)
  • Javex, mop, broom (for cleaning floors and surfaces)
  • Light bulbs (for replacing burnt-out lights)
  • Microfiber cloths (for cleaning delicate surfaces like screens or instruments)
  • Mouthwash (for freshening breath)
  • Q-tips (for detailed cleaning of gear or instruments)
  • Rubbing alcohol (for cleaning and disinfecting)
  • Sink (for general cleaning and handwashing)
  • Towel per person (for personal use or spills)
  • Washroom Stock  (for personal hygiene and convenience)

Food

  • Apple juice (for hydration or snacks)
  • Aspirin or Tylenol (for headaches or minor pain)
  • Bottle of scotch (for celebratory or relaxing moments)
  • Breath mints (for freshening breath)
  • Candy, fruit, nuts, sodas, bottled water (for snacks and refreshments)
  • Coffee grinder and beans (for fresh coffee preparation)
  • Condiments (for enhancing food)
  • Cough drops (for soothing sore throats)
  • Drugs (medicinal, herbal, recreational) (as appropriate for the session)
  • Glasses (one per person) (for drinks)
  • Lemon juice, coffee (with all the fixings), tea, herbal tea (for beverages)
  • Local restaurant menu book (for ordering takeout)
  • Microwave or toaster oven (for cooking/warming food)
  • Mini freezer (for ice or frozen snacks)
  • Non-alcoholic beverage alternatives (e.g., sparkling water or mocktails)
  • Plates (for serving food)
  • Reusable water bottles (to reduce waste)
  • Silverware (for eating meals)
  • Snacks for dietary restrictions (e.g., gluten-free, vegan options)

Furnishings

  • Ashtrays (if smoking is permitted)
  • Chairs for everyone (for seating during sessions)
  • Coat rack (for storing outerwear)
  • Comfortable seating (e.g., ergonomic chairs for extended sessions)
  • Eating area (tables and chairs) (for meals or breaks)
  • GOBOs/Soundproof curtains (for windows or additional isolation)
  • Humidifier, possibly air cleaner (for maintaining air quality)
  • Mirror (for personal grooming or visual checks)
  • Mood lighting (to set the vibe for creative work)
  • Music stands with clip-on lights (for holding sheet music)
  • Office dividers (used as ISO dividers for sound separation)
  • Portable heater (for maintaining warmth in cooler environments)
  • Rugs, candles, and lights (for creating a comfortable atmosphere)
  • A small fridge or cooler (to keep perishable items fresh)
  • Storage solutions (bins, shelves for cables and accessories)
  • Waste bins and recycling containers (for managing trash and recyclables)

Gear

  • Adapters and patch cables (RCA, XLR, 1/4″) (for connecting various gear)
  • Backup hard drives (for session safety and data backup)
  • Extra vacuum tubes (for tube-based equipment)
  • Ground lift adapters (for troubleshooting hum and grounding issues)
  • Headphone amps/distributors (for multiple users to monitor audio)
  • Power conditioners or surge protectors (to protect equipment from power surges)
  • Snakes (for connecting gear to the patch bay)
  • Splicing tape and edit block (for tape editing and repair)
  • Studio monitor isolation pads (to reduce vibration and improve sound accuracy)
  • Test tone generator (for calibration and troubleshooting)

Instrument supply

  • Guitars

    • Baby powder (cornstarch-based) (for reducing hand friction while playing)
    • Capo (for changing the pitch of the guitar)
    • Extra guitar patch cables (for connecting guitars to amplifiers or pedals)
    • Guitar stands (for safely holding guitars when not in use)
    • Guitar strings (nylon, acoustic, electric, and bass) (for replacements)
    • Picks (for playing)
    • Slide (for slide guitar techniques)
    • Straps (for comfortable guitar playing while standing)
  • Drums

    • Drum dampening gels or rings (for controlling overtones and resonance)
    • Drum key (for tuning drums)
    • Extra drumheads (for replacements during sessions)
    • Extra drumsticks (for replacements or variety in playing styles)
    • Lug lube (for maintaining tension rods and smooth tuning)
    • Metronome or drum machine (for keeping time)
    • Percussion mallets and brushes (for different tonal textures)
    • Various-sized cymbal felts, nylon cymbal sleeves, snare cords, tension rod washers (for maintaining drum hardware)
  • Chromatic tuner (for tuning instruments accurately)
  • Keyboard stand(s) (for securely holding keyboards)
  • Keyboard sustain pedals (for expressive keyboard playing)
  • Violin rosin (for maintaining bow grip if working with string players)

Office Supplies

  • Backup players (for covering absent musicians)
  • Blank CDRs (for storing recordings or sharing sessions)
  • Business cards (for networking opportunities)
  • City map (for navigating the area)
  • Clothespins or clamps (for holding papers or securing cables)
  • Decent restaurants that deliver (menus on hand) (for ordering meals)
  • Debit/credit card terminal (for client payments)
  • Dry-erase board with markers (for tracking or brainstorming)
  • Good restaurant list (for dining recommendations)
  • Good rolodex of numbers (for contacts like clients, vendors, and repair people)
  • Graph paper (for sketching layouts or diagrams)
  • Guitar Player, Bass Player, Modern Drummer (magazine subscriptions) (for inspiration or industry insights)
  • Label maker (for organizing cables, drawers, or gear)
  • Large wall calendar (for scheduling studio time or tracking projects)
  • Manuals for all equipment (for troubleshooting and reference)
  • Music staff paper (for writing out parts/arrangements)
  • Notepad (for jotting down lyrics, cues, or notes)
  • Pens, pencils, highlighters, and Sharpie markers (for writing and marking)
  • Repair people (contact information for equipment repairs)
  • Rental companies (for gear or equipment rentals)
  • Track sheets (for organizing session details)
  • USB drives or external SSDs (for data backup and transfer)
  • Vacuum (for cleaning the studio)
  • Whiteout (for correcting written errors)

Tools

  • Blue masking tape (for marking spots on the floor)
  • Cable tester/DMM (for testing and troubleshooting cables)
  • Console labeling tape (for marking controls or sections on the console)
  • Crimping tool and connectors (for making custom cables)
  • Digital multimeter (for measuring voltage, current, and resistance)
  • Earplugs (for hearing protection during loud sessions)
  • Fire extinguisher (for safety precautions)
  • Flashlight (for working in dimly lit areas)
  • Gaffer tape (for securing cables and other temporary fixes)
  • Heat gun (for shrink-wrapping or repairs)
  • Matches or a lighter (for igniting or emergency use)
  • Miscellaneous portable fans (for ventilation during long sessions)
  • Multi-tool, screwdriver set, socket set, and soldering/wiring tools (for general repairs and maintenance)
  • Portable phone chargers (for clients or band members)
  • Razor blades (for precise cutting tasks)
  • Roomba (for autonomous cleanup)
  • Safety goggles (for soldering or repairs)
  • Sandpaper (for smoothing surfaces or cleaning contacts)
  • Small step ladder (for reaching high shelves or fixing lights)
  • Small vacuum cleaner (for detailed cleaning)
  • Spare fuses (for outboard gear or amplifiers)
  • Stud finder (for securely mounting or hanging gear)
  • Tape (for general use)
  • Tester (RCA, XLR, 1/4 with polarity checker) (for verifying cable connections)
  • Thermal camera (for locating overheating gear)
  • WD-40 and 3-in-1 oil (for lubricating and maintaining equipment)
  • Weather stripping (for sealing gaps to improve sound isolation)

Computerism (noun)

Computerism (noun): A form of discrimination or bias where individuals are judged, stereotyped, or treated differently based on their choice of computer operating system (e.g., macOS vs. Windows vs. Linux) or browser preference (e.g., Chrome vs. Safari vs. Firefox). This phenomenon often manifests as social stigma, exclusion, or assumptions about a person’s technical skills, personality, or values based on their technology preferences.

For example, a macOS user might be labeled as “trendy but impractical,” while a Linux user could be stereotyped as “overly technical” or “elitist.” Similarly, browser preferences might spark debates or judgments about privacy, efficiency, or mainstream conformity.


“Jason’s blatant computerism was evident when he refused to collaborate with Sarah, simply because she preferred macOS over Windows.


A computerist is someone who engages in or perpetuates discrimination, bias, or stereotyping based on another person’s choice of computer operating system, software, or browser. They may judge or treat others differently because of their tech preferences, often making assumptions about their personality, competence, or values.

For example, a computerist might mock someone for using Internet Explorer, assume all Mac users are creative professionals, or stereotype Linux users as overly technical and antisocial.

In a broader sense, a computerist could also describe someone deeply passionate about computer systems and their associated cultures, though this usage is less common.


“Don’t be such a computerist—just because I use Linux doesn’t mean I think I’m better than everyone else!”