Skip to content

Instantly share code, notes, and snippets.

@tshego3
Last active March 11, 2025 09:08
Show Gist options
  • Save tshego3/7d918ed092732c842802a302df4de443 to your computer and use it in GitHub Desktop.
Save tshego3/7d918ed092732c842802a302df4de443 to your computer and use it in GitHub Desktop.
Personal Development Nexuses

Primary Nexuses

Standard Nexuses

Standard Nexuses:
EnergyInsight - TMM@Pay13:
DEV Nexuses
Alternative Nexuses
Other

Project Nexuses

Project Nexuses:

Microsoft Edge Start Modes

Microsoft Edge Start Modes:

Media Nexuses

Media Nexuses:

PowerShell

PowerShell Convert file to Base64 string format
  • File Command:
[convert]::ToBase64String((Get-Content -path "your_file_path" -Encoding byte))
# Read the binary content of the PDF file
$fileBytes = [System.IO.File]::ReadAllBytes("C:\Users\User\Downloads\Sample.pdf")

# Convert the binary content to Base64
$base64String = [Convert]::ToBase64String($fileBytes)

# Output the Base64 string
Write-Output $base64String
  • Text Command:
[convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("Hello world"))
  • Base64 to File Command:
# Base64 encoded string representing the PDF content
$base64String = "JVBERi0xLjUKJb/7 ..."

# Try to convert Base64 string to byte array
try {
    $pdfBytes = [System.Convert]::FromBase64String($base64String)
}
catch {
    Write-Output "Error: Unable to decode Base64 string. Details: $_"
    Exit
}

# Specify the output file path
$outputFilePath = "C:\path\to\output.pdf"

# Try to write the byte array to a PDF file
try {
    [System.IO.File]::WriteAllBytes($outputFilePath, $pdfBytes)
    Write-Output "PDF file successfully created at $outputFilePath"
}
catch {
    Write-Output "Error: Unable to write PDF file. Details: $_"
}
PowerShell Loop through each JSON object
# URL of the JSON endpoint
$url1 = "{endpoint}"
$url2Prep = "{endpoint}/{Operation}"

# Bearer token provided in a variable (replace with actual token)
$token = "tyJ0eX..."

# Headers including the Authorization token
$headers = @{
    "Authorization" = "Bearer $token"
}

# Send request to the API endpoint and retrieve JSON response
try {
    $response = Invoke-RestMethod -Uri $url1 -Headers $headers -Method Get -ContentType "application/json"
    
    # Check if the response contains the "Services" array
    if ($response.Operations -is [array]) {
        foreach ($operation in $response.Operations) {
            Write-Output "METHODNAME: " $operation.Name

            $url2 = $url2Prep.Replace("{Operation}", $operation.Name)
            $url2Result = Invoke-RestMethod -Uri $url2 -Headers $headers -Method Get -ContentType "application/json"

            if ($url2Result.Parameters -is [array]) {
                Write-Output "PARAMETERNAMES:"

                foreach ($parameter in $url2Result.Parameters) {
                    Write-Output $parameter.Name
                }
            }
        }
    } else {
        Write-Output "Error: No 'Services' array found in the response."
    }
}
catch {
    Write-Output "Error retrieving data from API: $_"
}
PowerShell to update the web.config file
# Load the Web.config file
[xml]$webConfig = Get-Content 'C:\inetpub\wwwroot\WebApp\Web.config'

# Find the appSettings key to update
$appSetting = $webConfig.configuration.appSettings.add | Where-Object { $_.key -eq 'ida:RedirectUri' }

# Update the value
$appSetting.value = 'https://www.endpoint.com/'

# Save the changes back to the Web.config file
$webConfig.Save('C:\inetpub\wwwroot\WebApp\Web.config')
PowerShell to update the appsettings.json file
# Read the JSON file
$json = Get-Content -Path "C:\inetpub\wwwroot\WebApp\appsettings.json" -Raw | ConvertFrom-Json;

# Update the value
$jsonValue = "https://www.endpoint.com/";
$json.RedirectUri = $jsonValue;
$json.Active = $true; # Note: $true is the correct boolean value in PowerShell

# Save the updated JSON back to the file
$json | ConvertTo-Json -Depth 32 | Set-Content -Path "C:\inetpub\wwwroot\WebApp\appsettings.json";
PowerShell Service enable/disable procedure
# Get service status:
Get-Service -ComputerName serverone.local.co.za -Name ServiceName

# Restart service:
Get-Service -ComputerName serverone.local.co.za -Name ServiceName | Restart-Service -Force

# Stop service:
Get-Service -ComputerName serverone.local.co.za -Name ServiceName | Stop-Service -Force

# Start service:
Get-Service -ComputerName serverone.local.co.za -Name ServiceName | Start-Service
PowerShell Various Commands
  • Converting text to base64 in PowerShell:
# $text = "<text>";
# $bytes = [System.Text.Encoding]::UTF8.GetBytes($text);
# $base64 = [Convert]::ToBase64String($bytes);
# Write-Output $base64;
	
$text = "<text>"; $base64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($text)); Write-Output $base64;
  • Get all file names in a folder, excluding their extensions, and output them as a comma-separated list
$folderPath = "C:\Your\Folder\Path";
$fileNames = Get-ChildItem -Path $folderPath -File | Select-Object -ExpandProperty BaseName;
$commaList = $fileNames -join ",";
Write-Output $commaList;
Various Command Documentation
  • Converting text to base64 in CMD:
@echo off
setlocal enabledelayedexpansion

set "text=<text>"
echo !text! | openssl base64
  • CMD: Convert MP4 to AVI
ffmpeg -i input.mp4 output.avi
  • CMD: Convert all WAV files in a folder to MP3 format using FFmpeg
for i in *.wav; do ffmpeg -i "$i" -f mp3 "${i%.*}.mp3"; done
  • CMD: Convert MP4 to GIF
ffmpeg -i input.mp4 -vf "fps=10,scale=1920:-1:flags=lanczos,palettegen" palette.png
ffmpeg -i input.mp4 -i palette.png -filter_complex "fps=10,scale=1920:-1:flags=lanczos[x];[x][1:v]paletteuse" output.gif
  • Open Windows System Environment Variables
Windows + R > SystemPropertiesAdvanced > Environment Variables
  • Stopping AzAgent:
End task: Agent.Listener.exe / AzAgent.Listener.exe
End task: AgentService.exe / AzAgentService.exe
  • Visual Studio Code Find & Regex Examples
public class $1\n{
public class (\w+)\(
Multiline Find: Shift+Enter in the Search Panel
Multiline Find: Use (.*\n)+ to match one or more lines with or without content, .e.g, <html>(.*\n)+</html> for an entire document. 
  • Replace all newlines with spaces:

    1. Open the Find and Replace Dialog:
      • Press Ctrl + H to open the Find and Replace dialog.
    2. Set Up the Find and Replace:
      • In the "Find what" box, enter \n to match newlines.
      • In the "Replace with" box, enter a space to replace newlines with a space.
    3. Enable Regular Expressions:
      • Click on the "Use Regular Expressions" option (usually a button with a star or asterisk symbol .*).
    4. Perform the Replacement:
      • Click "Replace All" to replace all newlines with spaces. Here's a visual representation of what you need to do:
    • Find what: \n OR ^(?:[\t]*(?:\r?\n|\r))+
    • Replace with: (a single space)
    • Use Regular Expressions: Enabled
  • Remove comments from your code in Visual Studio, you can use the following steps:

    1. Open your code file** in Visual Studio.
    2. Select the lines** of code that contain the comments you want to remove.
    3. Use the "Find and Replace" feature**:
      • Press Ctrl + H to open the Find and Replace window.
      • In the "Find what" box, enter the comment syntax for your programming language (e.g., // for single-line comments in C#, /* ... */ for block comments).
      • Leave the "Replace with" box empty.
      • Click on "Replace All" to remove all instances of the comment syntax.

    Alternatively, you can use regular expressions in the Find and Replace window to target comments more precisely. For example, to remove single-line comments in C#, you can use the following regular expression in the "Find what" box: //.*$.

  • To install a package, use the npm install command followed by the package name. This command installs the package and adds it to the node_modules directory.

npm install <package-name>

  • For example, to install the Express package, you would run:

npm install express

  • To install a package globally, use the -g flag:

npm install -g <package-name>

npm install -g @angular/cli

npm install -g azure-functions-core-tools

  • To remove a package, use the npm uninstall command followed by the package name:

npm uninstall <package-name>

  • For example, to uninstall the Express package, you would run:

npm uninstall express

  • To uninstall a global package, use the -g flag:

npm uninstall -g <package-name>

  • To update a package, use the npm update command followed by the package name:

npm update <package-name>

  • For example, to update the Express package, you would run:

npm update express

  • To update all global packages, use the -g flag:

npm update -g

  • To list all installed packages, use the npm list command:

npm list

  • To list all globally installed packages, use the -g flag:

npm list -g

  • To check for outdated packages, use the npm outdated command:

npm outdated

  • To check for outdated global packages, use the -g flag:

npm outdated -g

  • To run a script defined in the package.json file, use the npm run command followed by the script name:

npm run <script-name>

  • For example, to run a script named start, you would run:

npm run start

  • To publish a package to the npm registry, use the npm publish command:

npm publish

  • Additional Commands:

npm init: Create a package.json file.

npm test: Run tests defined in the package.json file.

npm version: Bump the version of a package.

npm help: Get help on npm commands.

Scheduling a batch file to run with Windows Task Scheduler is a great way to automate tasks on your PC

Here's a step-by-step guide to help you set it up:

  1. Create Your Batch File: Make sure you have your batch file (.bat) ready and stored in a safe location on your PC. The location is important because if the file is moved or deleted, the task will not run.

  2. Open Task Scheduler:

    • Press Win + R to open the Run dialog box.
    • Type taskschd.msc and press Enter. This will open the Task Scheduler.
  3. Create a New Task:

    • In the Task Scheduler window, click on Action in the menu bar and select Create Basic Task.
    • Give your task a name and description that will help you recognize it later. Click Next.
  4. Set the Trigger:

    • Choose when you want the task to start. You have several options such as Daily, Weekly, Monthly, One time, When the computer starts, When I log on, or When a specific event is logged. Select the option that best suits your needs and click Next.
  5. Set the Action:

    • Choose Start a program and click Next.
    • Click Browse and navigate to the location of your batch file. Select the batch file and click Open.
  6. Finish the Task:

    • Review the summary of your task and click Finish to create the task.
  7. Run with Admin Rights (Optional):

    • If your batch file requires administrative privileges, find the task in the Task Scheduler, right-click on it, and select Properties.
    • Go to the General tab and check the box that says Run with highest privileges. Click OK.

That's it! Your batch file should now run according to the schedule you set.

Azure Application Insights

Azure Application Insights Information

To show the average response time in milliseconds (ms) or in 1-minute intervals, you can adjust the KQL query accordingly. Here are the two options:

1. Average Response Time in Milliseconds (ms):

requests
| where timestamp >= ago(3d)
| summarize avgDurationMs = avg(duration) by bin(timestamp, 1d)
| project Day = format_datetime(bin(timestamp, 1d), 'yyyy-MM-dd'), avgDurationMs

2. Average Response Time in 1-Minute Intervals:

requests
| where timestamp >= ago(3d)
| summarize avgDuration = avg(duration) by bin(timestamp, 1m)
| project Minute = format_datetime(bin(timestamp, 1m), 'yyyy-MM-dd HH:mm'), avgDuration

3. Maximum Response Time in Milliseconds (ms):

requests
| where timestamp >= ago(3d)
| summarize maxDurationMs = max(duration) by bin(timestamp, 1d)
| project Day = format_datetime(bin(timestamp, 1d), 'yyyy-MM-dd'), maxDurationMs

You can run these KQL queries in the Azure Portal using the Log Analytics feature within your Application Insights resource. Here are the steps:

  1. Open Azure Portal: Navigate to the Azure portal.
  2. Select Application Insights: Go to your Application Insights resource.
  3. Open Logs (Analytics): In the left-hand menu, select "Logs" under the "Monitoring" section.
  4. Enter Your Query: Copy and paste the KQL query into the query editor.
  5. Run the Query: Click the "Run" button to execute the query and view the results.

This will allow you to analyze the average response time for requests over the last 3 days.

To check the average response time for requests in the last 3 days using Azure Application Insights, you can follow these steps:

  1. Open Azure Portal: Navigate to the Azure portal and select your Application Insights resource.
  2. Go to Metrics: In the Application Insights resource, go to the "Metrics" section.
  3. Configure Metrics:
    • Select "Log-based metrics" as the metric namespace.
    • Choose "Receiving response time" as the metric.
    • Select "Average" as the aggregation type.
    • Set the time range to the last 3 days.
  4. Apply Filters: If needed, apply any additional filters to narrow down the data to specific requests or operations.
  5. View Results: The chart will display the average response time for the selected period.

Build and Test PHP 7 CRUD REST API with MySQL:

Microsoft Visual Studio Installer Projects:

Nexuses:

Nexuse

Spoof Location on Microsoft Edge:

Custom IIS Domain Name Config:

  • C:\Windows\System32\drivers\etc\hosts
  • localhost name resolution is handled within DNS itself.
  • 27.0.0.1       www.localhost.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment