Home
Programming-related articles and tutorials focused on PowerShell, Python, C++, and more
Programming-related articles and tutorials focused on PowerShell, Python, C++, and more
Doing a literal search with ripgrep is easy and can be done with the -F parameter. To search for a string literal and not a regex, use: rg -F 'my string literal' Searching for a string literal is useful when you have to look for a string that ripgrep would interpret as regex (this behavior is by default). This is often the case when searching for snippets of code. For example, ...
Quick tip today. I wanted to validate my JSON file with jq. I think the common usage is to pipe text into jq but this is slow. jq has the ability to read the file directly, which is great if your json file is large. Next, we need to tell jq print out the loaded file. We use empty to not display any output. By default if there are any errors in the json file jq will output where the error is. ...
When working with C++ there are two versions we care about: What C++ standard are we using? What C++ compiler are we using? In this article I will show how to check both of these versions. How to Check C++ Standard Version First, is how to check the C++ standard version. The C++ language defines the following values corresponding C++ Standard Version __cplusplus C++98 199711L C++11 201103L C++14 201402L C++17 201703L C++20 202002L C++23 202302L The format __cplusplus is defined as a integer literal in the form YEARMONTH. For example, in C++23 __cplusplus is defined as 202302L, referring to Febraury 2023 (year=2023, month=02). This is roughly the date the committe approves the standard and it begins to go through the next stages of the ISO/IEC process. ...
Generating random data into a file is important task that can be accomplished in PowerShell. Generating random data is useful for benchmarking reading and writing files. We will also do it fast! We can generate 1GB of random data into a file in about 800 ms. ⚠️ Do not use System.Security.Cryptography.RNGCryptoServiceProvider as it is obsolete, instead use System.Security.Cryptography.RandomNumberGenerator. System.Security.Cryptography.RandomNumberGenerator is good as we don’t have to create a new object and can use the static methods. ...
Reading files in C++ can sometimes can be complex process. I wrote an article of four different ways to read a entire file into a string. I outline the pros and cons of each method. I have also done benchmarking to figure out which one is the fastest. Problem statement: Given a file path (std::string), read the entire file into fileData (std::string). The four methods I used are C’s fread, C++’s read, rdbuf, and istreambuf_iterator. ...
The other day had created two arrays with the same length and I wanted to output them as columns in a CSV file. I couldn’t find an exact cmdlet to do this so I wrote a small script. Let’s get started. If you have two arrays such as: $arr1 = 'a', 'b', 'c', 'd' $arr2 = 1 , 2 , 3 , 4 I want to output the two arrays into a CSV such as each array is a column: ...
As a C++ developer, you would see .cpp for C++ source files and .h for header files. However, you may have seen file extensions like .cxx, .cc or .hxx. What are these file extensions less commonly? Why are they used and not others? History Before C++, there was the C language. C used the extensions .c for C source files and .h for C header files. Later, when C++ came about the file extensions .c and .h were still being used for C++. However, C++ code became incompatible with C code, thus using the same file extension would cause confusion between C++ and C languages. There was a need at the time to differentiate C++ code from C code. ...
PowerShell has verstile scripting language which includes different kinds of loops. The while loop is a common looping syntax found in different langauges. The basic syntax for a while loop is: while ( <Condition> ) { # Code } We can convert from a for loop to a while loop: # For-loop for (<Initialization>; <Condition>; <Repeat>) { # Code } # While-Loop <Initialization> while ( <Condition> ) { # Code <Repeat> } Example: Loop 10 times $i = 0 while ($i -lt 10) { Write-Output "Loop value = $i" $i++ } ℹ️ We can get the same behavior with a one liner for loop also: ...
Where-Object is a cmdlet used for filtering objects in the pipe. Where-Object is placed in between commands and can remove objects that do not meet the criteria. Where-Object takes an object from the pipeline and filters all objects that do not meet the filter_expression. # General data flow: Cmdlet | Where-Object { filter_expression } | Cmdlet Where-Object returns the objects that match the specified condition. The filter includes (filter-in) the desired objects into the output. ...
A std::vector (or vector if you using namespace std;) is a C++ data structure. vector is a dynamic array that provides fast lookups. vector can be included by #include <vector>, is part of the Standard Template Library (STL), and is in “standard” scope std::. A vector can be initialized in many different ways. This is not an exhaustive list but what is useful and more common. What is initialization Initialization refers to the process of setting the value of a variable for the first time at the time of construction. Regarding, vector we can set an initial values (elements). ...
PowerShell offers a few different ways to change the directory. The official cmdlet to change the directory is Set-Location and it has an aliases: cd, sl, and chdir. PowerShell’s Set-Location is more powerful than Command Prompt’s change directory cd. Set-Location can change directories, change to registry, and change to certificates, and change to environment variables. I will refer to the cmdlet as Set-Location but they can be swapped out with any of the aliases mentioned earlier. cd being common one used. ...
During the creation of a 3-dimensional vector in C++ I was wondering what to call the third dimension, if the first two were called rows and columns. 2D Vector Initialization To begin, a 2D vector would be initialized like the following: int rows = 3; int columns = 5; int initVal = 0; // 2 dimensional vector vector<vector<int>> vec2D(rows, vector<int>(columns, initVal)); All fine and dandy! Let’s look at three dimensions… 3D Vector Initialization Initializing a 3D vector gets more complicated: ...
When working with PowerShell, creating multiple files at once can be a convenient way to interact with the file system. In Linux bash, you can use the touch command to create multiple files using a single script line. However, when it comes to PowerShell, things get a bit more complicated. While there isn’t a direct equivalent to the touch command in PowerShell, we can still achieve the same result using PowerShell. We’ll explore various methods for creating multiple files in PowerShell, including using foreach, variables, and even leveraging WSL (Windows Subsystem for Linux) to run the touch command directly. ...
PowerShell is a powerful modern shell for Windows. However, it is not without its quirks. As a modern software developer on Windows you use PowerShell on a regular basis. Sometimes CLI applications (I’m looking at you git) interact with PowerShell in quirky ways. I saw this the other day with git in PowerShell. I was trying to git diff my current changes with the ones in my latest stash stash@{0}. However, when I ran the command git diff stash@{0}, I got the following error: ...
Why ImageMagick is Recommended Why should you use ImageMagick? Free - no subscriptions, nothing to required to buy sponsorship is most welcomed though! 1 Offline - no having to upload your personal files online Format support: JPEG, PNG, GIF, TIFF, and PDF Open source2 Been around since forever (2009😜) 3 Why Use ImageMagick as a Software Developer? it uses the command line - impress your friends lots of utilities and arguments for editing and manipulating images - impress yourself Where to Get ImageMagick For Windows ImageMagick can be downloaded at ImageMagick - Download. The ImageMagick team recommends a version at the top of the table ending in Q16-HDRI-x64-dll.exe. ...
In this article, we’ll show how easy it is to convert HEIC images to JPEG or PNG format a command-line tool. This method is simple and efficient way to convert individual or multiple HEIC images quickly. The best way to convert HEIC to JPEG or PNG is ✨magic✨ once you have the correct tool: ✨ImageMagick✨ Summary Use ImageMagick to convert the HEIC to JPEG or PNG with the following commands: ...
Select-String can be an alternative to Linux’s amazing and well known grep tool. However, grep must be downloaded and setup on the Windows system which might not be possible or convient to do so. A great built-in alternative on Windows PowerShell is Select-String which can do regular expression searching similar to grep. Goal is to have Select-String to only return the match text or the found reuslt. Quick Summary Select-String returns Matches and within it has Value which has the exact text match of the regex without any extra text: (cat .\results.txt | Select-String '<a.*?>.*?</a>').Matches.Value Example: curl a webpage, search a pattern Let’s say we curl’d a webpage and we want to extract the <a>...</a> tags. ...
If you have a powerful PC or laptop (read: power hungry ⚡), the fans on the PC or laptop can become too loud during load. All this noise can be annoying if you’re just using your system day to day. If you are okay losing some performance you can easily tweak your power settings to prevent the fans going into turbo mode and sounding like a jet engine. ⚠️Warning: This could potentially affect performance ...
Let’s get the local IP version 4 address of the system using PowerShell. We want the actual IPv4 address of the local system but not the localhost loopback address or the link-local address on the system. Link-local address is valid only for communications on local link (subnetwork) that our system is connected to. Link-local addresses are usually 169.254.0.0/16 (169.254.0.0 through 169.254.255.255). 1 Localhost is a hostname that refers to the current computer used to access it. The name localhost is reserved for loopback purposes. The IPv4 loopback address is 127.0.0.1. 2 ...
Finding the Developer PowerShell launch script can be difficult as the location for it has change across the different Visual Studio versions (e.g., 2019, 2022), editions (e.g., Community, Professional, Enterprise), and installation location. Visual Studio 2022 and newer install the ‘Developer PowerShell for VS 2022’ as a Windows Terminal profile. This is the easiest way to access it. However, if you want to access it from a PowerShell ps1 script it is more complicated. Accessing via script is done typically if you have to run the script on another system where you don’t know which Visual Studio version/edition/location installed. ...
In PowerShell, calling Invoke-WebRequest on a local share, such as \\mydirectory\myFile.txt, will result in an error message such as Invoke-WebRequest: The 'file' scheme is not supported.. If the file is on a network share, the best alternative to Invoke-WebRequest is to simply use Copy-Item. So: Invoke-WebRequest \\mydirectory\myFile.txt -OutFile myFile.txt becomes: Copy-Item \\mydirectory\myFile.txt C:\somewherelocally\myFile.txt I’ve seen this error with FTP also: Invoke-WebRequest: The 'ftp' scheme is not supported. Good news is that curl is shipped with Windows 1. So we can use curl for FTP files: ...
When creating and working with directories in PowerShell and Command Prompt, you may encounter errors when trying to create a new directory using the mkdir command. In best practice, we don’t want commands to throw exceptions or set error flags, as they can cause issues further down the script if not handled correctly. The best course of action is to prevent the error from occuring from the first place. In this article, we’ll go over how to prevent the errors. ...
Ripgrep (rg) is a popular command-line search tool based on the popular GNU grep tool. The Access is denied. (os error 5) is a common error message that appears when trying to read a file or directory that ripgrep does not have permission to access. This can be annoying when doing a system wide search when many system directories or other protected directories may be searched, littering the results with many “access is denied” error messages. Luckily the messages can be suppressed. ...
When searching through large code bases or directories, it’s helpful to get a sense of how many matches were found by your search query. While tools like ripgrep can give you the exact lines where a match was found, they don’t always provide an easy way to see the total number of hits. This is where ripgrep --stats and --count comes in. With these arguments we can get stats about what was found and results per file. ...
Determining the PowerShell version is important for scripts as it tells the script the potential features available on the current PowerShell engine. The best way to do this is use the $PsVersionTable variable in the first method. In this example, the PowerShell version is 7.4.5. Method 1: Use $PSVersionTable Variable The most reliable and recommended way to determine the PowerShell version is using the built-in variable $PSVersionTable. $PSVersionTable contains the infromation about the PowerShell engine including the version. In the shell type $PSVersionTable and press enter. Note, if the variable doesn’t exist then the version is 1.0. ...
The other day I was looking something up for PowerShell and realized that cat command for the classic ‘Windows Command Shell’1 is an alias of Get-Content PowerShell cmdlet. I wondered what other aliases does PowerShell have. There is an extensive collection of about 138 default aliases on PowerShell going to 109 PowerShell cmdlets on Windows. PowerShell was designed to work with other operating systems too, like Linux and MacOs. If you are new to PowerShell, then these aliases are a good place to learn commands that are often used. ...
Introduction As a Windows developer you’ve considered creating a graphical user interface (GUI). The inevitable question that comes up is: which Windows GUI technology should I use? I tried to answer that question myself, and thought surely everyone is still using Windows API (ye olde Win32 API) with GDI/GDI+! Right? No? Oh, let’s see what there is now… WinUI, WPF, WinForms, UWP, .NET MAUI, oh my, the list goes on. Why did these all come about? ...
Quick tip today. I wanted to find all directories with a certain name specifically .vs because I wanted to delete them. Is the .vs directory safe to delete? Yes, becuase its all generated files by VS that can be deleted. There is also db files in there that intellisense keeps, which can clutter your system after a while. To find all files: gci -recurse -Force -filter ".vs" gci alias for GetChild-Item -recurse to search all sub-directories -Force to search hidden and system files (this is useful for .vs directory because it is typically hidden) -filter to filter which directory or file we want To get the full path of each result: ...
Create XML in PowerShell Before we start if we don’t have a XML file, we can create one: Set-Content .\test.xml '<?xml version="1.0" encoding="utf-8"?><root/>' Set-Content is a powershell cmd-let to write to a file. The first element is the prolog element 1: <?xml version="1.0" encoding="utf-8"?>. The W3C Recommendation describes the prolog as version number, encoding declaration. If we want to load it and write to it, it must have at least a root element, in this example it is <root> but it can be anything such as <catalog>, <company>, <store>, or even <zoo>. ...
Cool trick with the Windows Terminal is Quake mode. The name comes from the Quake games’ console. The Quake console was used to send commands to the game such as /god for God mode or /give all to get all game items. The Quake in-game console was shown by pressing tilde ~ key. A similar behavior can be accomplished with Windows Terminal called Quake mode. In Windows Terminal quake mode the terminal is snapped to the top of the screen. The bottom of the window can be sized but the window is docked to the top. ...
I often need to jump into a command-line interface (CLI) in Windows from an Explorer window. Previous, I used to type cmd . into Explorer’s current directory (press F4 to hightlight) to open the current directory. However, I have been using Windows Terminal (wt) more than the classic Command Prompt (cmd) for some of the quality of life features (e.g., tabs). To call Windows Terminal from Explorer type wt into the current directory – but this does not open the current directory. Neither does wt ., you’ll get an obscure error: [error 2147942405 (0x80070005) when launching .]. If you look at the help (wt --help), it is burried in the help. If you do wt new-tab --help will have the starting directory command. ...
Command Prompt to PowerShell To create a new text file using PowerShell, use New-Item. Classically, done by echo "some text" > into-a-file.txt, but PowerShell New-Item provides more robustness. The equvalent of the echo redirect > to a new file is PowerShell cmdlet New-Item. In this example, output hello into a new text file in the current directory called myFile.txt. echo hello > myFile.txt New-Item ".\myFile.txt" -Value "hello" -Force Note that New-Item does not replace the file if it already exists by default, we can use -Force to emulate the behavior of the echo redirect. If you run the command without -Force it will give error: New-Item: The file 'C:\myFile.txt' already exists. ...
Current C++ Standard Version The current C++ standard is C++231 or officially known as 14882:2024 or ISO International Standard ISO/IEC 14882:2023 - Programming Language C++. The official C++23 standard was published on October 19, 2024 2. The ISO/IEC 14882:2024 superseeds ISO/IEC 14882:2020 standard (C++20). ISO/IEC 14882:2024 is the 7th edition of the standard. The standard increased by about 14% in number of pages. Although an official copy of the stanard costs money, drafts of the standard can be found online for free 3. ...
Clean the Visual Studio 2019 x64 Release or Debug build directory using Clean-Build.bat batch script. Place in the x64 directory and run the bat. Great if you need to archive your project before sending and don’t want to send a bunch of extra files. Tested with Visual Studio 2019 and 2022. The script can be expanded to remove other kinds of files. Files Removed File type Usage *.ipdb Incremental Link-Time Code Generation - Program database (PDB) file *.iobj Incremental Link-Time Code Generation - Object file *.pdb Program database (PDB) *.idb Intermediate debug file / state file used for minimal rebuild and incremental compilation *.ilk Intermediary linker files *.exp DLL exports *.obj Object file - compiled code that the linker uses *.tlog Used for incremental builds - information about all inputs / outputs *.FileListAbsolute.txt List of files built in current build *.recipe Used in Guidance Automation Toolkit Notes Important to use .\ before paths, otherwise it will execute from the drive’s root directory If there is more than one condition that needs to be used an if statement then must use nested if statements can use defined to check if a variable is defined or not defined if not defined. Clean-Build.bat @echo off setlocal enableextensions setlocal EnableDelayedExpansion set ExecutableName=%1% set BuildType=%2% if not defined BuildType ( echo Usage: Clean-Build.bat ExecutableName BuildType exit /b 1 ) if not "%BuildType%" == "Debug" ( if not "%BuildType%" == "Release" ( echo Usage: Clean-Build.bat ExecutableName BuildType echo Build must be Release or Debug exit /b 1 ) ) if not defined ExecutableName ( echo Usage: Clean-Build.bat ExecutableName BuildType exit /b 1 ) echo Cleaning: %ExecutableName% echo Build type: %BuildType% :: Release builds if "%BuildType%" == "Release" ( del .\%BuildType%\*.iobj del .\%BuildType%\*.ipdb ) :: Debug builds if "%BuildType%" == "Debug" ( del .\%BuildType%\*.ilk del .\%BuildType%\*.idb ) :: Both builds del .\%BuildType%\*.tlog del .\%BuildType%\*.obj del .\%BuildType%\*.recipe del .\%BuildType%\*.pdb del .\%BuildType%\*.log del .\%BuildType%\*.FileListAbsolute.txt rmdir /S /Q .\%BuildType%\%ExecutableName%.tlog echo Done
Strategy Talk about time and space complexity through out the program look at the input parameters to the function Terminology $O(nlogn + n^2)$ asymptotically is $O(n^2)$. If you write $O(n^2)$ explain its the asymptotic time complexity. Applications Common time complexity patterns: $O(2^N)$, $O(3^N)$: Permutation (e.g., NP hard problems) $O(N^2)$, $O(N^3)$: Recursion / generate subsets, nested loops $O(NlogN)$: Sorting / heap $O(N)$: Iteration, pointers/sliding window, common array operations $O(logN)$: Binary search / exponentially sized steps search $O(1)$: Hashmap or index of array Time Complexity Names $O(2^N)$, exponential time $O(N^2)$, quadratic time $O(NlogN)$, linearithmic time $O(N)$, linear time $O(logN)$, logarithmic time $O(1)$, constant time Space Complexity Space = Input + Auxilary + Output ...
Previously discussed Convert Char to Int in C++, in which we converted a single character to an integer. In this article we will build upon that idea by converting multiple characters to an integer. C++ Standard Library If want to use the built-in functions, the C++ standard has a couple built-in functions for converting strings to an integer. Namely there is atoi and std::stoi. atoi atoi is part of “C Standard General Utilities Library in the header <cstdlib>. ...
How do you create a shortcut in Windows via scripts? Easy use PowerShell! Below is the script to create a shortcut named “MyShortcut”. One can additionally create shortcuts to URLs too. I commented everything so it is easy to follow. The only parameter you must set is the $Shortcut.TargetPath everything else is optional. The Windows Script Host (WSH) is a Windows administration tool. Within the Windows Script Host object model the root is Wscript and a sub-node which is WshShell (Wscript.Shell). WshShell object can run programs locally, modify the registry, create shortcuts, or access system folder. Specifically we’re interesting in creating shortcuts. We will access the WSH via the PowerShell script by utilizing the Windows Script Host (WScript) object (via COM) to create the shortcut. ...
C/C++’s char built-in type is a 1-byte type. char can hold a value [-128, 127]. The name char can be confusing because a char can range from printable characters to non-printable characters. It is easier to think of char as a 1-byte signed integer. Convert Character char to Integer int - Modern C++ Since C++11, a new C++ expressions have been added to do compile time casting. Compile-time casting is safer as errors can be checked during compile-time over run-time. Specifically, static_cast was added which is perfect usage for converting character to integer. ...
C++’s substring function substr returns a newly constructed string (copy of a portion of the original string) with the parameters of substr. More importantly, C++’s substring is a source of confusion. I wanted to discuss how the substring works and what are the common pitfalls. What does Substr do? substr copies a substring of the original string. A substring is a contiguous sequence of characters within a string. For example, nate is a substring of donate. A substring can also contain the entire original string. ...
The Fibonacci sequence is a sequence in which each number is the sum of the two previous ones, starting with 0 and 1 as the base cases. A Fibonacci number is a number in the Fibonacci sequence. The golden ratio can be computed from the ratio between two Fibonacci numbers in consecutive sequence, as the sequence approaches infinity. Here we will talk about how to compute the nth number in the Fibonacci sequence. ...
Backing up files on Windows without any additional software is best done by Robocopy. Robocopy is short for “Robust File Copy” and is a command-line utility for file and directory copying for Windows. Using Robocopy is the easiest way to backup files in Windows without using any additional software. The command is robocopy. Basic usage is: robocopy <source> <destination> To use it to back up files, there are two general approaches (more exist but this is a good start): ...
Adobe Acrobat is probably the most professional way to convert an image to a PDF but it requires creating/signing into an account and paying a monthly fee – no thanks! I propose alternative ways to convert an image to a PDF depending what is available on your computer. Method 1: Convert Image to PDF using MS Word If Microsoft Word is available then the easiest method is to use Word and Export to a PDF. The easiest and highest quality method to convert an image (e.g., jpg, png, bmp, etc) to pdf is to use Microsoft Word. No need for external apps or websites. ...
Fastest way to close a running executable in PowerShell is with Stop-Process (alias: kill). Stop-Process is a great tool for developers, especially when developing an application that sometimes doesn’t close properly, has stopped responding, are not shown on screen, or run multiple processes. Stop-Process PowerShell PowerShell 5 and newer can stop processes with Stop-Process (or alias kill) using the process name: Stop-Process -Force -Name 'ProcessName' For example, to close all instances of notepad.exe: ...