Gray_code_element

Monday, February 10, 2025

Extracting a series of zip files into folders with the names of each file

Batch File to Extract ZIP Files into Folders

Batch File to Extract ZIP Files into Folders

If you have multiple ZIP files in a folder and want to extract each one into its own folder with the same name as the ZIP file, you can use a batch script.

Method 1: Using Windows tar (Windows 10+)

Create a batch file and paste the following code:


    @echo off
    setlocal enabledelayedexpansion
    for %%F in (*.zip) do (
        set "foldername=%%~nF"
        mkdir "!foldername!"
        tar -xf "%%F" -C "!foldername!"
    )
    echo Extraction complete!
    pause
    

Steps:

  • Save the file as extract_all.bat in the folder containing your ZIP files.
  • Double-click the batch file to extract each ZIP file into a folder named after the ZIP filename.

Method 2: Using 7-Zip (More Reliable)

Prerequisite: Install 7-Zip and ensure it’s added to the system path or use the full path to 7z.exe.


    @echo off
    setlocal enabledelayedexpansion
    for %%F in (*.zip) do (
        set "foldername=%%~nF"
        mkdir "!foldername!"
        "C:\Program Files\7-Zip\7z.exe" x "%%F" -o"!foldername!" -y
    )
    echo Extraction complete!
    pause
    

Steps:

  • Save as extract_all.bat in the folder containing the ZIP files.
  • Run the batch file.

How It Works

  • for %%F in (*.zip) do → Loops through all .zip files in the folder.
  • set "foldername=%%~nF" → Extracts the filename (without extension).
  • mkdir "!foldername!" → Creates a folder with the same name.
  • tar -xf or 7z.exe x → Extracts the ZIP file into the created folder.

Would you like any modifications, such as handling subdirectories or logging extraction results? Let me know in the comments!

Tuesday, February 4, 2025

Top Level Statements in C#

C# Top-Level Statements vs. Main Method

C# Top-Level Statements vs. Main Method

In C# 9 and later, you can use top-level statements, which eliminate the need for explicitly defining a Main method. Your code uses this feature, so the Main method is not required.

Why is Main Not Required?

  • Starting from C# 9, you can write top-level statements directly in a .cs file, and the compiler will implicitly generate a Main method.
  • This feature is designed to make simple programs (like console applications) more concise.

How It Works:

  • The compiler automatically wraps the code inside a generated Main method.
  • Your program starts executing from the first statement.
  • Any await statements require an async context, which is automatically handled.

If Using Older C# Versions:

If you're using C# 8 or earlier, or if you prefer the traditional structure, you would need to explicitly define Main like this:


using System;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Starting MQTT Client...");

        var mqttFactory = new MqttFactory();
        var mqttClient = mqttFactory.CreateMqttClient();

        var mqttClientOptions = new MqttClientOptionsBuilder()
            .WithTcpServer("broker.mqtt-dashboard.com", 1883)
            .WithCleanSession()
            .Build();

        double Temperature = -5;
        double WindSpeed = 10;
        var Rand = new Random();

        mqttClient.ConnectedAsync += async e =>
        {
            Console.WriteLine("Successfully connected to the MQTT broker.");

            while (true)
            {
                double currentTemperature = Math.Round((Temperature + Rand.NextDouble()), 3);
                double currentWindSpeed = Math.Round((WindSpeed + Rand.NextDouble()), 3);

                var message = new MqttApplicationMessageBuilder()
                    .WithTopic("LRLBTopic")
                    .WithPayload(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new
                    {
                        Temperature = currentTemperature,
                        WindSpeed = currentWindSpeed,
                    })))
                    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                    .Build();

                await mqttClient.PublishAsync(message);
                Console.WriteLine("Message published to topic: LRLBTopic");
                Thread.Sleep(2000);
            }
        };

        mqttClient.DisconnectedAsync += e =>
        {
            Console.WriteLine("Disconnected from the MQTT broker.");
            return Task.CompletedTask;
        };

        try
        {
            await mqttClient.ConnectAsync(mqttClientOptions);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error connecting to the MQTT broker: {ex.Message}");
            return;
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

        await mqttClient.DisconnectAsync();
    }
}
    

Summary:

  • C# 9+: Main is optional (uses top-level statements).
  • C# 8 or earlier: Main is required.
  • For explicit structure: You can still define Main if you prefer.

Your code will work fine as long as you are using C# 9 or later in your project. 🚀

Visual Studio Remove Blank spaces

  1. In window, press Ctrl+H (quick replace)
  2. Click "Use regular expressions"
  3. In Find, specify: ^\$\n
  4. leave Replace as blank
  5. Click "Replace All"  All blank lines will be deleted.
Understanding the Regular Expression: ^\s*$\n

This regular expression is used to identify and remove blank lines from text.

  • ^: Matches the beginning of a line. Since we're using the `re.MULTILINE` flag in Python, each line in the text is treated as a separate unit.
  • \s*: Matches zero or more whitespace characters (spaces, tabs, newlines).
  • $: Matches the end of a line.
  • \n: Matches a newline character.

In essence, this regular expression matches a line that:

  1. Starts with the beginning of the line.
  2. Contains zero or more whitespace characters.
  3. Ends with the end of the line.
  4. Is followed by a newline character.

Therefore, it effectively targets and matches blank lines that might contain spaces or tabs.

Thanks to Gemini for the explaination.


Saturday, August 10, 2024

Python with OpenAI on Windows Computer

Install python. https://platform.openai.com/docs/quickstart

 at command prompt:

C:\Users\Jhufnagel>python -m venv openai-env    (this creates a virtual environment so the libraries do not interfere with other libraries)

(openai-env) C:\Users\Jhufnagel>python -m pip install --upgrade openai (Note, the openai platform states that I can just use 'pip install --upgrade openai', but that gives an access error). I found the work around at https://stackoverflow.com/questions/31172719/pip-install-access-denied-on-windows



Sunday, November 5, 2023

Solidworks macros eith ChatGPT

 Record a simple using thr Solidworks macro recorder, upload it to ChatGPT, and explain to ChatGPT how you want it changed: https://youtu.be/QJfYaIGAmdY?si=j2N52jE9NZl67tWA

A  similar second example where we start with giving ChatGPT some basic code ideas and even telling the references to use:https://youtu.be/ksOW4Sap6So?si=5bhrn3TmI8qSuJHb

Tuesday, September 19, 2023

Musical theory behind Bach Prelude in CMaj

 Theory explained https://andrewhennington.wordpress.com/2015/10/22/j-s-bach-prelude-no-1-in-c-major-bwv-846/

Tonic cord - the root cord

Supersonic: the second note in a normal 8 note (heptatonic: 7 pitches) scale

Phrase- usually 4 bars long, ending in some form of a cadence. The first phrase ends in a imperfect authentic cadence 

Authentic cadence goes from the dominant to the tonic. Perfect cadence has tonic the highest tone in the final cord. Imperfect does 

Thursday, August 24, 2023

y bar

y + hold Alt, type 0773