Connect to localhost from Docker container
For Win and Mac:
localhost
and127.0.0.1
– These resolve to the container.host.docker.internal
– This resolves to the outside host.
RabbitMQ CLI tools
Error Message:
CLI tool fails to authenticate with the server (e.g. due to CLI tool's Erlang cookie not matching that of the server)
Solution from here
Ensure cookies are synchronized across 1, 2 and Optionally 3 below
-
%HOMEDRIVE%%HOMEPATH%\.erlang.cookie
(usuallyC:\Users\%USERNAME%\.erlang.cookie
for user%USERNAME%
) if both theHOMEDRIVE
andHOMEPATH
environment variables are set -
%USERPROFILE%\.erlang.cookie
(usuallyC:\Users\%USERNAME%\.erlang.cookie
) ifHOMEDRIVE
andHOMEPATH
are not both set -
For the RabbitMQ Windows service -
%USERPROFILE%\.erlang.cookie
(usuallyC:\WINDOWS\system32\config\systemprofile
)
Trimming video using FFMpeg
See here
Freeing up disk space - Linux
Reference: article
sudo apt-get autoremove
- Remove
apt
cache:sudo apt-get clean
sudo journalctl --vacuum-time=3d
- Remove old revisions of snaps:
#!/bin/bash
# Removes old revisions of snaps
# CLOSE ALL SNAPS BEFORE RUNNING THIS
set -eu
snap list --all | awk '/disabled/{print $1, $3}' |
while read snapname revision; do
snap remove "$snapname" --revision="$revision"
done
- Clean the thumbnail cache:
rm -rf ~/.cache/thumbnails/*
Can use ncdu
to check disk space from command line as well.
ImageMagick script for converting .heic to .jpg
import os
import subprocess
lst = os.listdir(".")
for entry in lst:
if entry.lower().endswith(".heic"):
fname = os.path.basename(entry).split(".")[0] + ".jpg"
print(f"Converting {entry} to {fname}")
ran_proc = subprocess.run(["magick",entry,"-quality","100%",fname])
if ran_proc.stdout:
print(f"Stdout is {ran_proc.stdout}")
if ran_proc.stderr:
print(f"Stderr is {ran_proc.stderr}")
pip
installing packages globally
When pip
inside virtualenv is installing packages globally check the following:
Try checking your bin/pip and bin/activate scripts. In bin/pip, look at the shebang. Is it correct? If not, correct it. Then on line ~42 in your bin/activate, check to see if your virtualenv path is right. It'll look something like this
VIRTUAL_ENV="/Users/me/path/to/virtual/environment"
If that fails, run the virtual environments pip with its full path.
How to change user
su - john # if john is the user
Python Requests library using proxy
Set environment variables http_proxy
and https_proxy
. These can be used by pip
as well
Using Azure AD access token for non Microsoft Graph API
See here. They key is that the scopes
array should have a single element with: "<YourClientId>/.default
.
When following the example here, make sure to replace
the scopes with "<YourClientId>/.default
.
Replace text using Powershell
(Get-Content .\file.txt) -replace "!", "," | Set-Content -Path .\replaced.txt
Using PugiXML with Qt
- Make sure to include pugi's cpp and headers in the .pro file
Neovim restore Windows Terminal cursor on exit
vim.cmd [[
autocmd VimLeave * set guicursor=a:ver20a:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor,sm:block-blinkwait175-blinkoff150-blinkon175
]]
Frappe Gantt chart
See here
Using PyPDF2 to decrypt a PDF
See here
Might need to install pyCryptodome
first pip install pycryptodome
# Decrypt password-protected PDF in Python.
# cleaned-up version of http://stackoverflow.com/a/26537710/329263
#
# Requirements:
# pip install PyPDF2
#
# Usage: decrypt_pdf('encrypted.pdf', 'decrypted.pdf', 'secret_password')
import sys
from PyPDF2 import PdfFileReader, PdfFileWriter
def decrypt_pdf(input_path, output_path, password):
with open(input_path, 'rb') as input_file, \
open(output_path, 'wb') as output_file:
reader = PdfFileReader(input_file)
reader.decrypt(password)
writer = PdfFileWriter()
for i in range(reader.getNumPages()):
writer.addPage(reader.getPage(i))
writer.write(output_file)
print(f"Done. wrote to {output_file}")
if __name__ == '__main__':
input_file = sys.argv[1]
output_file = sys.argv[2]
password = sys.argv[3]
# example usage:
decrypt_pdf(input_file,output_file,password)
Postgres UPSERT operation
Source: here
Excerpt:
CREATE TABLE inventory(
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL
);
INSERT INTO inventory(id, name, price, quantity)
VALUES
(1, 'A', 15.99, 100),
(2, 'B', 25.49, 50),
(3, 'C', 19.95, 75)
RETURNING *;
Here, EXCLUDED
means "use the new value"
INSERT INTO inventory (id, name, price, quantity)
VALUES (1, 'A', 16.99, 120)
ON CONFLICT(id)
DO UPDATE SET
price = EXCLUDED.price,
quantity = EXCLUDED.quantity;
Git rebase into forked repo
Excerpted from here
- Add the remote (original repo that you forked) and call it “upstream”
git remote add upstream https://github.com/original-repo/goes-here.git
- Fetch all branches of remote upstream
git fetch upstream
- Rewrite your master with upstream’s master using git rebase.
git rebase upstream/master
- Push your updates to master. You may need to force the push with “--force”.
git push origin master --force
Error parsing ws-trust response
If this happens, use AcquireTokenInteractive
.
Cadence report
command line tool
To get at the Quick Reports
from the command line, use the report
command line tool like so:
report -v elp <path to .brd file> <output.txt>
To see a list of all the command line parameters type
report -help
User has not been granted requested logon
If seeing this error, follow the steps here
Windows disk cleanup script
Remove-Item -Path "$env:tmp\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:userprofile\appdata\local\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:appdata\Code\Service Worker\CacheStorage\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:appdata\Teams\Service Worker\CacheStorage\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:userprofile\appdata\local\Microsoft\Edge\User Data\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:userprofile\appdata\local\Microsoft\vscode-cpptools\" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:userprofile\Downloads\" -Recurse -Force -ErrorAction SilentlyContinue
Distutils and Python 3.12
Install setuptools
using pip
instead as python 3.12 removed distutils
.
Zip and unzip on Linux
zip -r <backup.zip> <directory_name>
Example:
zip -r backup.zip my_folder/
Notice that the /
is very important! To unzip:
unzip [file_name.zip]
Vim find all in file and show in quickfix window
:vimgrep /pattern/ %
and then
:copen
or
:cwindow
.vimrc for gvim (Windows)
source $VIMRUNTIME/vimrc_example.vim
source $VIMRUNTIME/mswin.vim
imap jk <Esc>
au VimEnter * imap jk <Esc>
"set guifont=Consolas:h11
set guifont=Cascadia\ Code:h12
set number
"set guifont=Cascadia Code:h11
colorscheme onedark
set encoding=utf-8
"colorscheme summerfruit
set nobackup "no backup files
set nowritebackup "only in case you don't want a backup file while editing
set noswapfile "no swap files
set noundofile
set autoindent
set expandtab
set tabstop=4
set shiftwidth=4
set autoread
set autochdir
autocmd BufNewFile,BufRead *.csv set filetype=csv_semicolon
autocmd BufNewFile,BufRead *.dat set filetype=csv_pipe
" let g:plug_shallow = 0
call plug#begin('~/.vim/plugged')
" Plug 'mechatroner/rainbow_csv'
Plug 'prabirshrestha/vim-lsp'
Plug 'mattn/vim-lsp-settings'
Plug 'prabirshrestha/asyncomplete.vim'
Plug 'PProvost/vim-ps1'
Plug 'prabirshrestha/asyncomplete-lsp.vim'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'shime/vim-livedown'
call plug#end()
" Live down section reference
" launch the Livedown server and preview your markdown file
" :LivedownPreview
" stop the Livedown server
" :LivedownKill
" launch/kill the Livedown server
" :LivedownToggle
nmap mt :LivedownToggle<CR>
" End Live down section!
" < Other Plugins, if they exist >
" Plug 'fatih/vim-go'
"Plug 'neoclide/coc.nvim', {'do': 'yarn install --frozen-lockfile'}
"Plug 'dense-analysis/ale'
" call plug#end()
" Use the internal diff if available.
" Otherwise use the special 'diffexpr' for Windows.
if &diffopt !~# 'internal'
set diffexpr=MyDiff()
endif
function MyDiff()
let opt = '-a --binary '
if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
let arg1 = v:fname_in
if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
let arg1 = substitute(arg1, '!', '\!', 'g')
let arg2 = v:fname_new
if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
let arg2 = substitute(arg2, '!', '\!', 'g')
let arg3 = v:fname_out
if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
let arg3 = substitute(arg3, '!', '\!', 'g')
if $VIMRUNTIME =~ ' '
if &sh =~ '\<cmd'
if empty(&shellxquote)
let l:shxq_sav = ''
set shellxquote&
endif
let cmd = '"' . $VIMRUNTIME . '\diff"'
else
let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
endif
else
let cmd = $VIMRUNTIME . '\diff'
endif
let cmd = substitute(cmd, '!', '\!', 'g')
silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3
if exists('l:shxq_sav')
let &shellxquote=l:shxq_sav
endif
endfunction
git
compare file in different branches
See here
The syntax is as follows
git difftool [| diff] branch1..branch2 -- <path/to/file/file_to_compare>
Example:
git difftool branch1..branch2 -- ./src/myfile.py
Clearing MEF Component cache
Download the "Clear MEF Component cache" extension as shown here if constantly seeing "Could not load file or assembly" when saving files in Visual Studio 2022.
Evite CSV import
The CSV has to be in the following format (pasted from reference link below):
- Column A: First Name (and/or last name, plus any additional guest names if adding families under one contact).
- Column B: Email address only (can be left blank if adding guests by phone instead).
- Column C: Phone numbers only (can be left blank if adding guests by email instead).
- No headers.
- No special characters or symbols.
- No additional columns filled in.
Sample:
Luke Skywalker,,111-111-1111
Han Solo,,999-999-9999
Chewbacca,,333-333-3333
Obi-Wan Kenobi,,222-222-2222
Recovering flash drive after using Balena Etcher
Summary:
list disk
select disk N # make sure you select the right one from the listing
clean # cleans the disk
"Add a partition back to it and format it, so that it acts like a normal storage device. Do the following"
create partition primary
select partition 1
format quick
Typst snippets for VSCode
{
// Place your snippets for typst here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// "Print to console": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"AddFigure": {
"prefix": "addfig",
"body" : [
"#figure(image(\"$1\",width:70%),caption:[$2])"
],
"description": "Add figure to typst document"
},
"AddTable": {
"prefix": "addtable",
"body": [
"#table(columns: (auto,auto)",
"table.header([*$1*],[*$2*])",
"[$3], [$4])"
],
"description": "Add table to typst document"
}
}
GNOME Tweaks app
Gnome tweaks is a handy app to quickly set appearance and other settings in Ubuntu (works as of Noble)
To install: sudo apt install gnome-tweaks
To run: Type in gnome-tweaks
in terminal
Powershell Notes
Get names of all directories in current script root:
$dirs = Get-ChildItem $PSScriptRoot |
Where-Object {$_.PSIsContainer} | # analog of `.Where` Linq function in C#
Foreach-Object {$_.Name} # analog of `.Select` Linq function in C#
Reference: here
Visual Studio Code vim bindings quickstart Notes
{
"editor.fontSize": 16,
"vim.insertModeKeyBindings": [
{
"before": ["j", "k"],
"after": ["<esc>"]
},
],
"vim.useSystemClipboard": true,
"vim.useCtrlKeys": false,
}
Powershell remote execution with parameters
Invoke-Command -ComputerName "computer-name" -FilePath "path\to\local\script.ps1" -ArgumentList "Argument1","Argument2"
Sample script.ps1
param (
[Parameter(Position=0)][string]$param1,
[Parameter(Position=1)][string]$param2
)
Write-Output "Param1: $param1, Param2: $param2"
FFMpeg stitch videos together
To concatenate videos without re-encoding:
/Applications/ffmpeg -f concat -safe 0 -i ./all.txt -c copy entire.mp4
Contents of all.txt:
file './C0043.MP4'
file './C0044.MP4'
Command to create compressed MP4:
ffmpeg -i entire.mp4 -vcodec libx265 -crf 28 output.mp4
ImageMagick Notes
- To make a .ico file from a PNG:
convert -background transparent "icons8-bot-48.png" -define icon:auto-resize=16,24,32,48,64,72,96,128,256 "bot.ico"
- To remove background:
Using extern C
in C++
In C++, when using C libraries (with source code) do the following in the header file that is being #include
d
#ifdef __cplusplus
extern "C"
{
#endif
//content of header file
#ifdef __cplusplus
}
#endif
Git Credential Manager
To use Git Credential Manager, make sure the following is set in the global .gitconfig
:
[credential "https://github.com"]
helper = manager
Inf2Cat
tool
This tool is used to create a .cat
file for PnP drivers that need a detached signature.
Workflow:
- Use
Inf2Cat
to create a.cat
file - Sign the driver
.sys
file usingsigntool
- The
.cat
file must be referred to by the.inf
file - Keep the
.cat
,.sys
, and the.inf
files in the same directory - Use
pnputil
and the.inf
file to install the driver
"C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\Inf2Cat.exe"
Version 1.0.0.0
Runs driver signability tests and creates the catalog(s).
INF2CAT /driver:path /os:operatingSystem1[,os2]...
[/nocat] [/verbose]
[/drm[:file1[,file2]...]]
[/pe[:file1[,file2]...]]
[/pageHashes[:file1][,file2]...]]
/driver (/drv) Indicates the path to the driver package follows.
path Specifies the path to the driver package.
/os Indicates the operating system(s) targeted by the driver
package follows. The targeted operating system(s) is a
comma separated list of the following values:
operatingSystem1 2000
XP_X86 Server2003_X86
XP_X64 Server2003_X64
Server2003_IA64
Vista_X86 Server2008_X86
Vista_X64 Server2008_X64
Server2008_IA64
7_X86
7_X64 Server2008R2_X64
Server2008R2_IA64
8_X86
8_X64 Server8_X64
8_ARM
6_3_X86
6_3_X64 Server6_3_X64
6_3_ARM
10_X86
10_X64 Server10_X64
Server10_ARM64
10_AU_X86
10_AU_X64 Server2016_X64
10_RS2_X86
10_RS2_X64
10_RS3_X86
10_RS3_X64
10_RS3_ARM64
10_RS4_X86
10_RS4_X64
10_RS4_ARM64
10_RS5_X86
10_RS5_X64 ServerRS5_X64
10_RS5_ARM64 ServerRS5_ARM64
10_19H1_X86
10_19H1_X64
10_19H1_ARM64
10_VB_X86
10_VB_X64
10_VB_ARM64
ServerFE_X64
ServerFE_ARM64
10_CO_X64
10_CO_ARM64
10_NI_X64
10_NI_ARM64
10_GE_X64
10_GE_ARM64
Server2025_X64
Server2025_ARM64