This commit is contained in:
Artur Gurgul 2025-08-03 16:27:25 +02:00
commit acc61e858b
18 changed files with 5068 additions and 0 deletions

62
utils/git-squash.md Normal file
View file

@ -0,0 +1,62 @@
---
layout: default
title: Git - notes
categories: software
---
Squash the last three commits
```bash
git rebase -i HEAD~3
```
You will see something like this
```plain
pick f392171 Added new feature X
pick ba9dd9a Added new elements to page design
pick df71a27 Updated CSS for new elements
```
- `pick` `p` the commit will be taken
- `squash` `s`, the commit will be blended with the above.
Edit to something like this
```plain
pick f392171 New message for this three commit!
squash ba9dd9a
squash df71a27
```
Now you can accept the change by continuing the rebase:
```bash
git rebase --continue
```
After that you need to force override the history using this command:
```bash
git push origin master --force
```
## Squash merge
```bash
git checkout master
git merge --squash bugfix
git commit
```
### Checkout bare repository
```
git clone --bare https://github.com/nextcloud/server.git /var/www/nextcloud.git --recursive
cd nextcloud.git; git worktree add /var/www/nextcloud
cd /var/www/nextcloud; checkout -f v27.1.4
git --work-tree=/var/www/nextcloud --git dir=/home/artur/pub/drive/repos/nextcloud.git checkout -f v27.1.4 --recursive
```

591
utils/recepies.yml Normal file
View file

@ -0,0 +1,591 @@
layout: default
title: Recipes
type: recipes
recipes:
Read a DNS records:
^: dns networking
$: dig artgur.net +nostats +nocomments +nocmd
I/O Stats:
$: iostat
Checking type of executable files:
$: otool -hv test.so
Gzip of image:
^: compression, zip
$: dd if=/dev/sdb | gzip > ~/backup.img.gz
Progress with `dd`:
$:
- sudo dd if=2024-11-19-raspios-bookworm-armhf.img of=/dev/disk27 status=progress
- sudo dd if=/dev/sdb | pv -s 5.29G | dd of=DriveCopy1.dd bs=4096
- sudo pv ubuntu-24.04.1-desktop-amd64.iso | sudo dd of=/dev/disk27
Get directory size:
$: du -sh MacOSBackup
Print all sizes in directory:
$:
- du -sh *
- du -shc *
Compare two files:
$:
- vim -d file1 file2
- mcdiff file1 file2
Disk manager:
$: cfdisk /dev/sda
List of disks:
$: parted -l
Informations about disk:
$: fdisk -l /dev/sda
Power off the disk:
$: udisksctl power-off -b /dev/sdX
Generate random password:
$:
- pwgen -s -1 32
- openssl rand -hex 12
List block devices:
$: lsblk
Linux headers:
-
$: uname -r
-
$: apt search linux-headers-$(uname -r)
Show all disks with json format:
$: lsblk -J
List disk with uuid's:
$: lsbkl -f
vfat file system:
- : Create a file systyem
$: mkfs.vfat -F 32 /dev/sdb4
- : Mount the file system
$: mount -i -t vfat -oumask=0000,iocharset=utf8 /dev/sdb4 /root
See what processes are using the drive:
$: lsof /where/drive/is/mounted
See what process opens the port:
$:
- lsof -p 6919
- lsof -i :6919
See the stats of IO:
$:
- apt install sysstat iotop
- iostat -dh 2
- iotop -o
- sar -p -d -b 1
- vmstat -d 1
- vmstat -p /dev/sda2 1
Rsync:
$: rsync -ah --progress /Volumes/Data /Volumes/Data\ 1/Junk/1TB\ Drive
reloading local DNS:
$: sudo /etc/init.d/dns-clean start
Print all processes in json format:
$: |
ps aux | awk -v OFS=, '{print $1, $2}' | jq -R 'split(",") | {user: .[0], pid: .[1]}'
Split files:
$: split -b 70M deno
Search and execute command from the history:
$: eval `history | fzf | cut -s -d " " -f4-`
file: .zshrc
content: |
export HISTSIZE=100000000
alias hexec='eval `history | fzf | cut -s -d " " -f4-`'
Editing command with editor:
file: ~/.zshrc
content: bindkey '^e' edit-command-line
Copy public ssh key:
- cat ~/.ssh/id_rsa.pub | pbcopy
change password that was saved in a variable:
$: echo "$archpass" | passwd "$archuser" --stdin
Git diff between branches:
$: git diff release-1.2.0..release-1.2.1
MacOS info aliases in `.zhrc`:
file: .zhrc
content: |
alias cpu='sysctl -n machdep.cpu.brand_string'
alias cpu-temp='sudo powermetrics --samplers smc | grep -i "CPU die temperature"'
alias gpu-temp='sudo powermetrics --samplers smc | grep -i "GPU die temperature"'
alias lsusb='sudo ioreg -p IOUSB'
alias allusb='ioreg -p IOUSB -w0 -l'
Power metrics:
$: sudo powermetrics --samplers all
Install pods from non standard localisations:
$: |
pod 'WASHD', :git => 'https://github.com/vatlib/EasyUITextFields.git'
pod 'WASHD', :path => '/Users/artur/projs/easyuitextfields'
SQLite select and search results with FZF:
$: echo "select * from bookmarks" | sqlite3 bookmarks.db | fzf
Open file with FZF:
$: nvim -o `fzf`
Set default shell. ZSH in this case:
$: sudo chsh --shell /usr/bin/zsh user
Show Git object:
$: pigz -d < .git/objects/02/f2cc93fee0b3cb7c9b75f49e4ded3f9b1480eb
list of wireless cards:
$: lspci -knn | grep Net -A2
Scan networks:
$: iwlist scan
Shutdown:
$: shutdown -h now
Connect to the network:
$: nmcli dev wifi connect TP-Link_5828 password my-secret-pass
You can forward port `80` to `8090`:
$: iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8090
Allow accepting connections on `8090`:
$: iptables -I INPUT -m tcp -p tcp --dport 8090 -j ACCEPT
Search files that contains particular string:
$: grep -rnw "." -e "Search key"
Remove garbage files:
$: find ./ -name ".DS_Store" -depth -exec rm {} \;
Find files, directories and symbolic links using regex:
$: find ./ -iname `fo*` and `F??` -type f,d,l
Make text from pipe uppercased:
$:
- cat file.txt | tr [:lower:] [:upper:]
- cat file.txt | tr [a-z] [A-Z]
- tr [a-z] [A-Z] < linux.txt > output.txt
Installing packages in python for an user:
$: pip3 install --user meson
Calling module through interpreter:
$: python3 -m pip install six
Remove spaces:
$: cat file.txt | tr -d ' '
Remove duplicate characters:
input-file: domains.txt
content: |
www.google.....com
www.linkedin.com
www.linuxsay.com
$: cat domains.txt | tr -s '.'
output: |
www.google.com
www.linkedin.com
Extract digit:
$:
- echo "My UID is $UID" | tr -cd "[:digit:]\n"
- echo "My UID is $UID" | tr -d "a-zA-Z"
Translate single character:
$: echo "My UID is $UID" | tr " " "\n"
Get path by number:
$: echo $PATH | cut -d ":" -f 1
list search path line by line:
$: echo $PATH | tr ":" "\n"
Screen capture:
$:
- ffmpeg -f x11grab -video_size 1280x800 -framerate 25 -i $DISPLAY -c:v ffvhuff screen.mkv
- ffmpeg -video_size 1280x800 -framerate 25 -f x11grab -i :0.0 -f pulse -ac 2. \
-i default -vcodec vp8 -acodec libvorbis myvideo_$(date +%d_%B_%Y_%H:%M).webm
Take a screenshot:
$:
- xwd -root -out screenshot.xwd
- maim -s -u | xclip -selection clipboard -t image/png -i
- imlib2_grab screenshot.png
Install Python package for the user:
$: python3 -m pip install --user pyelftools
Erase free space:
$: sudo diskutil secureErase freespace 1 /Volumes/Data\ Drive
Format disk:
$: sudo diskutil eraseDisk ExFAT data /dev/disk26
Search for commit:
$: alias gf='git log --all --oneline | fzf'
Converts all files in current directory revursevely:
install: brew install imagemagick
tags: convert image-magic
$: alias rmalfa='find . -name “*.png” -exec convert “{}” -alpha off “{}” \;'
Weather alias:
$: alias weather='curl wttr.in'
Starting an electron app on wayland:
- : Start chromium using wayland
$: chromium --enable-features=UseOzonePlatform --ozone-platform=wayland
- : The same for electron-based apps
$: |
`app-executable` --enable-features=UseOzonePlatform \
--ozone-platform=wayland
Save website As PDF:
file: .zshrc
content: |
function aspdf {
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --print-to-pdf="./$1.pdf" $2
}
$: aspdf "filename" "https://domain.com/example.pdf"
Export Markdown as PDF:
$:
- pandoc README.md -o README.pdf
- pandoc --from=gfm --to=pdf -o README.pdf README.md
Gem path:
content: |
export GEM_HOME=$HOME/.gem
path=("$GEM_HOME/bin" $path)
QEMU - port forwarding:
$: |
qemu-system-i386 -net nic,model=rtl8139 \
-net user,hostfwd=tcp::3389-:3389,hostfwd=tcp::443-:443,hostfwd=tcp::992-:992
SQL using regex:
description: Add a check constraint to the `id` column to enforce alphanumeric strings of exactly 5 characters long
$: ALTER TABLE short_urls ADD CONSTRAINT id CHECK (id ~ '^[a-zA-Z0-9]{5}$');
Console font size:
description: Edit file &rarr; `/etc/default/console-setup`
$: dpkg-reconfigure -plow console-setup
Redirect errors to null device:
$: find / 2>/dev/null
Installing nonfree firmware from repository:
description: |
I.e: Firmware for nonfree driver for Intel's WIFI cards.
https://packages.debian.org/sid/firmware-iwlwifi
$: apt-get update && apt-get install firmware-linux-nonfree
Installing nonfree firmware from manufacturer:
- : Search for binary. An example
link: https://www.intel.com/content/www/us/en/support/articles/000005511/wireless.html
- : Extract and copy like
$: cp iwlwifi-cc-a0-46.ucode /lib/firmware
Linux - RAM disk:
description: This might be useful for spead up programs that heavily use disk
$: mount -t TYPE -o size=SIZE FSTYPE MOUNTPOINT
info: |
* `TYPE` &rarr; either `tmpfs` or `ramfs`.
* `SIZE` &rarr; ie. `512m`
* `FSTYPE` &rarr; File system type, either `tmpfs`, `ramfs`, `ext4`, etc.
file: /etc/fstab
content: tmpfs /mnt/ramdisk tmpfs nodev,nosuid,noexec,nodiratime,size=1024M 0 0
fstab:
: Use 'blkid' to print the universally unique identifiers, and can be used in fstab file like
file: /etc/fstab
content: |
# <file system> <mount point> <type> <options> <dump> <pass>
UUID=1a38b8ca-e1f5-45e6-bbe8-3abd2775b3a6 / ext4 errors=remount-ro 0 1
/swapfile none swap sw 0 0
/dev/disk/by-uuid/4D3C-4E36 /mnt/4D3C-4E36 auto nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=e21eebe4-471a-4375-8c4c-618b3733a940 /home ext4 nodev,nosuid 0 2
Linux - Mount disk from `qcow2` image:
- : Step 1 - Enable NBD on the Host
$: modprobe nbd max_part=8
- : Step 2 - Connect the QCOW2 as network block device
$: qemu-nbd --connect=/dev/nbd0 /var/lib/vz/images/100/vm-100-disk-1.qcow2
- : Step 3 - Find The Virtual Machine Partitions
$: fdisk /dev/nbd0 -l
- : Step 4 - Mount the partition from the VM
$: mount /dev/nbd0p1 /mnt/somepoint/
- : Step 5 - After you done, unmount and disconnect
$:
- umount /mnt/somepoint/
- qemu-nbd --disconnect /dev/nbd0
- rmmod nbd
Ubuntu - Power management - make Ubuntu do nothing when laptop lid is closed:
- : Open the `/etc/systemd/logind.conf` file in a text editor as root, for example
$: sudo -H gedit /etc/systemd/logind.conf
- : If `HandleLidSwitch` is not set to ignore then change it
$: HandleLidSwitch=ignore
note: |
Other settings that the action can be ignored: `HandleLidSwitchExternalPower`, `HandleLidSwitchDocked`, `IdleAction`.
- : Restart the systemd daemon (be aware that this command will log you out)
$:
- sudo systemctl restart systemd-logind
- sudo service systemd-logind restart
Chroot environment of Debian sid:
- : Install Bootstrap
$: sudo apt install debootstrap
- : Create a directory that you want to use for the base system (_chroot-debian_ in this case)
$: mkdir chroot-debian
- : Create a base system
$: sudo debootstrap sid chroot-debian http://deb.debian.org/debian
note: Valid names `sid`, `stable` or any debian code name
- : Mount filesystems
$:
- sudo mount -o bind /dev chroot-debian/dev
- sudo mount -t sysfs none chroot-debian/sys
- sudo mount -o bind /proc chroot-debian/proc
- : Optionally, copy DNS resolver configuration.
$: sudo cp /etc/resolv.conf /path/to/chroot-env/etc/resolv.conf
- : Start chrooting
$: sudo chroot chroot-debian /bin/bash
- : Once done, exit the session and unmount
$: sudo umount chroot-debian/dev chroot-debian/proc
Pass variables to chrooted environment:
$: chroot ./ env -i PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Allowing user to run a command as root:
$: sudo visudo
content: artur ALL=(ALL) chroot /path/to/chroot-env
Nginx - serving files setup DAV:
- : Full version with 3rd party extensions
$: apt install nginx-full nginx-extras
-
content: |
location / {
index nonextistent;
autoindex on;
autoindex_format json;
}
location /restricted {
fancyindex on;
fancyindex_exact_size off;
auth_basic "Restricted";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
location /dropbox {
index nonextistent;
autoindex on;
autoindex_format json;
dav_methods PUT DELETE MKCOL COPY MOVE;
dav_ext_methods PROPFIND OPTIONS LOCK UNLOCK;
dav_access user:rw group:r all:r;
# client_max_body_size 0;
create_full_put_path on;
client_body_temp_path /tmp/;
limit_except GET PROPFIND OPTIONS HEAD {
auth_basic "Restricted";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
# auth_pam "Restricted";
# auth_pam_service_name "common-auth";
}
- : Create password
$:
- echo -n 'sammy:' >> /etc/nginx/.htpasswd
- openssl passwd -apr1 >> /etc/nginx/.htpasswd
- : Another method to set the password
$:
- htpasswd -c /etc/nginx/.htpasswd sammy
- htpasswd /etc/nginx/.htpasswd another_user
note: UI Client `Cyberduck`
Backing up the entire OS:
$: sudo rsync -aAXHv / --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /mnt
Python:
$: apt install python3-full
Check battery:
- $:
- upower -i /org/freedesktop/UPower/devices/battery_BAT0
- upower -i `upower -e | grep 'BAT'`
- upower -i $(upower -e | grep BAT) | grep --color=never -E "state|to\ full|to\ empty|percentage"
- : Battery capacity
$: cat /sys/class/power_supply/BAT0/capacity
- : ACPI
$:
- apt install acpi
- acpi -V
- acpi -t
- : Watch the status for example
$: watch --interval=5 acpi -V
How to scan open ports:
$:
- nmap -sT -p- 10.10.8.8
- nmap -p 80 127.0.0.1
Remove non ASCII characters form the file:
$: sed 's/[^[:print:]\t]//g' script.sh > cleaned_script.sh
Network Manager:
- : Check Status
$:
- pacman -S networkmanager
- systemctl status NetworkManager
- $:
- nmcli dev status
- nmcli radio wifi
- $: nmcli radio wifi on
- $: nmcli dev wifi list
- $: nmcli dev wifi connect network-ssid
- $: nmcli dev wifi connect network-ssid password "network-password"
- : With password promot
$: nmcli dev wifi connect network-ssid password "network-password"
- $: nmcli con show
- $:
- nmcli con down ssid/uuid
- nmcli con up ssid/uuid
- $: ip link set eno1 up
DHCP Client:
$: pacman -S dhclient dhcpcd
Turn dchp on for the interface:
$: dhclient eth0 -v
Create file:
content: |
cat > filename <<- "EOF"
file contents
more contents
EOF
Get data about file include number of links:
$: stat f1
File decryption:
$: openssl aes256 -md sha256 -d -in file.enc.zip -out file.zip -pass pass:"<password>"
Base64:
$:
- openssl base64 -in qrcode.png -out qrcode.png.base64
- openssl base64 -in qrcode.png
Extract tar.xz:
$: tar -xJf file.tar.xz -C destination
Execute command:
- : Execute `ls` for each each object in current directory that starts from `D` or `M`
$: ls {D*,M*}
- : Utworzenie dwóch katalogów `test_a`, `test_b`
$: mkdir test_{a,b}
Copy content of directory and merge it. Dereference links:
$: cp -LTr /form/ .
JSON Linux apis:
$:
- tree -J
- ls -l | jq -R -s -c 'split("\n")[:-1]'
List dependencies:
$:
- pacman -Sy lld
- llvm-nm
Find location of executable:
$: type -a python
Execute Command when file is changed:
-
$: brew install fswatch
-
$: fswatch -o . --exclude "\.build.*$" | xargs -n1 -I{} your-command
Add capabilities:
description: allow all to open 443 port
$: sudo setcap 'cap_net_bind_service=+ep' ./service
Test speed of the drive:
$: sudo hdparam -t --direct /dev/mmcblk0

941
utils/recepiesmd.md Normal file
View file

@ -0,0 +1,941 @@
---
layout: default
title: Recipes MD
---
#### Read a DNS records
dig artgur.net +nostats +nocomments +nocmd
#### I/O Stats
iostat
#### Checking type of executable files
otool -hv test.so
#### #Receipe Gzip of image
```shell
dd if=/dev/sdb | gzip > ~/backup.img.gz
```
#### Progress with `dd`
```
sudo dd if=2024-11-19-raspios-bookworm-armhf.img of=/dev/disk27 status=progress
sudo dd if=/dev/sdb | pv -s 5.29G | dd of=DriveCopy1.dd bs=4096
sudo pv ubuntu-24.04.1-desktop-amd64.iso | sudo dd of=/dev/disk27
```
#### Get directory size
du -sh MacOSBackup
##### Print all sizes in directory
```bash
du -sh *
```
```bash
du -shc *
```
#### Compare two files
```bash
vim -d file1 file2
mcdiff file1 file2
```
### Disk manager
```bash
cfdisk /dev/sda
```
#### List disks
```
parted -l
```
#### informations about disk
```bash
fdisk -l /dev/sda
```
#### Power off the disk
```
udisksctl power-off -b /dev/sdX
```
#### Generate random password
```bash
pwgen -s -1 32
```
or
```
openssl rand -hex 12
```
#### List block devices
lsblk
#### Linux headers
```
uname -r
apt search linux-headers-$(uname -r)
```
Show all disks with json format
```shell
lsblk -J
```
List disk with uuid's
```shell
lsbkl -f
```
#### MKFS
```bash
mkfs.vfat -F 32 /dev/sdb4
```
```bash
mount -i -t vfat -oumask=0000,iocharset=utf8 /dev/sdb4 /root
```
#### See what processes are using the drive
```
lsof /where/drive/is/mounted
```
### See what process opens the port
```bash
lsof -p 6919
lsof -i :6919
```
#### See the stats of IO
```
apt install sysstat iotop
```
```
iostat -dh 2
iotop -o
sar -p -d -b 1
vmstat -d 1
vmstat -p /dev/sda2 1
```
### Rsync
```
rsync -ah --progress /Volumes/Data /Volumes/Data\ 1/Junk/1TB\ Drive
```
#### reloading local DNS
```shell
sudo /etc/init.d/dns-clean start
```
#### Print all processes in json format
``` shell
ps aux |
awk -v OFS=, '{print $1, $2}' |
jq -R 'split(",") | {user: .[0], pid: .[1]}'
```
### Split files
```
split -b 70M deno
```
#### Search and execute command from the history
```bash
eval `history | fzf | cut -s -d " " -f4-`
```
Adding this to `.zshrc`
```
export HISTSIZE=100000000
alias hexec='eval `history | fzf | cut -s -d " " -f4-`'
```
#### Editing command with editor
`~/.zshrc`
```
bindkey '^e' edit-command-line
```
#### Copy public ssh key
```bash
cat ~/.ssh/id_rsa.pub | pbcopy
```
#### change password that was saved in a variable
```bash
cho "$archpass" | passwd "$archuser" --stdin
```
#### Git diff between branches
git diff release-1.2.0..release-1.2.1
#### MacOS info aliases in`.zhrc`
```
alias cpu='sysctl -n machdep.cpu.brand_string'
alias cpu-temp='sudo powermetrics --samplers smc | grep -i "CPU die temperature"'
alias gpu-temp='sudo powermetrics --samplers smc | grep -i "GPU die temperature"'
alias lsusb='sudo ioreg -p IOUSB'
alias allusb='ioreg -p IOUSB -w0 -l'
```
**Power metrics**
```bash
sudo powermetrics --samplers all
```
#### Install pods from non standard localisations
```ruby
pod 'WASHD', :git => 'https://github.com/vatlib/EasyUITextFields.git'
pod 'WASHD', :path => '/Users/artur/projs/easyuitextfields'
```
#### SQLite select and search results with FZF
```bash
echo "select * from bookmarks" | sqlite3 bookmarks.db | fzf
```
#### Open file with FZF
```bash
nvim -o `fzf`
```
#### Set default shell. ZSH in this case
sudo chsh --shell /usr/bin/zsh user
#### Show Git object
```sh
pigz -d < .git/objects/02/f2cc93fee0b3cb7c9b75f49e4ded3f9b1480eb
```
#### list of wireless cards
lspci -knn | grep Net -A2
#### Scan networks
iwlist scan
#### Shutdown
shutdown -h now
#### Connect to the network
nmcli dev wifi connect TP-Link_5828 password my-secret-pass
#### You can forward port `80` to `8090`
```shell
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8090
```
#### Allow accepting connections on `8090`
```shell
iptables -I INPUT -m tcp -p tcp --dport 8090 -j ACCEPT
```
#### Search files that contains particular string
``` shell
grep -rnw "." -e "Search key"
```
#### Remove garbage files
find ./ -name ".DS_Store" -depth -exec rm {} \;
#### Find files, directories and symbolic links using regex
find ./ -iname `fo*` and `F??` -type f,d,l
#### Make text from pipe uppercased
```bash
cat file.txt | tr [:lower:] [:upper:]
cat file.txt | tr [a-z] [A-Z]
tr [a-z] [A-Z] < linux.txt > output.txt
```
#### Installing packages for python
**_just for user_**
```bash
pip3 install --user meson
```
**_calling module through interpreter_**
```bash
python3 -m pip install six
```
#### Remove spaces
```bash
cat file.txt | tr -d ' '
```
#### Remove duplicate characters
```bash
$ cat domains.txt
www.google.....com
www.linkedin.com
www.linuxsay.com
```
```bash
$ cat domains.txt | tr -s '.'
www.google.com
www.linkedin.com
```
#### Extract digit
``` bash
echo "My UID is $UID" | tr -cd "[:digit:]\n"
echo "My UID is $UID" | tr -d "a-zA-Z"
```
#### Translate single character
```bash
echo "My UID is $UID" | tr " " "\n"
```
#### Get path by number
```bash
echo $PATH | cut -d ":" -f 1
```
#### list search path line by line
```bash
echo $PATH | tr ":" "\n"
```
#### Screen capture
```
ffmpeg -f x11grab -video_size 1280x800 -framerate 25 -i $DISPLAY -c:v ffvhuff screen.mkv
ffmpeg -video_size 1280x800 -framerate 25 -f x11grab -i :0.0 -f pulse -ac 2. \
-i default -vcodec vp8 -acodec libvorbis myvideo_$(date +%d_%B_%Y_%H:%M).webm
```
#### Take a screenshot
```bash
xwd -root -out screenshot.xwd
maim -s -u | xclip -selection clipboard -t image/png -i
imlib2_grab screenshot.png
```
#### Install Python package for the user
python3 -m pip install --user pyelftools
#### Erase free space
sudo diskutil secureErase freespace 1 /Volumes/Data\ Drive
#### Format disk
sudo diskutil eraseDisk ExFAT data /dev/disk26
#### Search for commit
```bash
alias gf='git log --all --oneline | fzf'
```
#### Remove alpha channel from all files
```bash
# ➜ brew install imagemagick
```
**Converts all files in current directory revursevely**
```bash
alias rmalfa='find . -name “*.png” -exec convert “{}” -alpha off “{}” \;'
```
#### Weather alias
```sh
alias weather='curl wttr.in'
```
#### Starting an electron app on wayland
Start chromium using wayland
```bash
chromium --enable-features=UseOzonePlatform --ozone-platform=wayland
```
Its the same for electron-based apps:
```bash
`app-executable` --enable-features=UseOzonePlatform \
--ozone-platform=wayland
```
#### Save website As PDF
```bash
function aspdf {
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --print-to-pdf="./$1.pdf" $2
}
```
Usage
```bash
aspdf "filename" "https://superuser.com/questions/592974/how-to-print-to-save-as-pdf-from-a-command-line-with-chrome-or-chromium"
```
### Export Markdown as PDF
```bash
pandoc README.md -o README.pdf
```
```bash
pandoc --from=gfm --to=pdf -o README.pdf README.md
```
#### Gem path
```hash
export GEM_HOME=$HOME/.gem
path=("$GEM_HOME/bin" $path)
```
#### QEMU - port forwarding
```bash
qemu-system-i386 -net nic,model=rtl8139 \
-net user,hostfwd=tcp::3389-:3389,hostfwd=tcp::443-:443,hostfwd=tcp::992-:992
```
#### SQL using regex
Add a check constraint to the `id` column to enforce alphanumeric strings of exactly 5 characters long
```sql
ALTER TABLE short_urls ADD CONSTRAINT id CHECK (id ~ '^[a-zA-Z0-9]{5}$');
```
#### Console font size
Edit file &rarr; `/etc/default/console-setup`
```bash
dpkg-reconfigure -plow console-setup
```
#### Redirect errors to null device
find / 2>/dev/null
#### Installing nonfree firmware from repository
I.e: Firmware for nonfree driver for Intel's WIFI cards.
```
https://packages.debian.org/sid/firmware-iwlwifi
```
```bash
apt-get update && apt-get install firmware-linux-nonfree
```
#### Installing nonfree firmware from manufacturer
Search for binary. An example:
[https://www.intel.com/content/www/us/en/support/articles/000005511/wireless.html](https://www.intel.com/content/www/us/en/support/articles/000005511/wireless.html)
Extract and copy like
```bash
cp iwlwifi-cc-a0-46.ucode /lib/firmware
```
### Linux - RAM disk
This might be useful for spead up programs that heavily use disk.
```
mount -t TYPE -o size=SIZE FSTYPE MOUNTPOINT
```
* `TYPE` &rarr; either `tmpfs` or `ramfs`.
* `SIZE` &rarr; ie. `512m`
* `FSTYPE` &rarr; File system type, either `tmpfs`, `ramfs`, `ext4`, etc.
To make this setting persistent you might want to add to `/etc/fstab` fallowing line
```plain
tmpfs /mnt/ramdisk tmpfs nodev,nosuid,noexec,nodiratime,size=1024M 0 0
```
#### fstab
Use 'blkid' to print the universally unique identifiers, and can be used in fstab file like
```
# <file system> <mount point> <type> <options> <dump> <pass>
UUID=1a38b8ca-e1f5-45e6-bbe8-3abd2775b3a6 / ext4 errors=remount-ro 0 1
/swapfile none swap sw 0 0
/dev/disk/by-uuid/4D3C-4E36 /mnt/4D3C-4E36 auto nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=e21eebe4-471a-4375-8c4c-618b3733a940 /home ext4 nodev,nosuid 0 2
```
### Linux - Mount disk from `qcow2` image
Step 1 - Enable NBD on the Host
```bash
modprobe nbd max_part=8
```
Step 2 - Connect the QCOW2 as network block device
```bash
qemu-nbd --connect=/dev/nbd0 /var/lib/vz/images/100/vm-100-disk-1.qcow2
```
Step 3 - Find The Virtual Machine Partitions
```bash
fdisk /dev/nbd0 -l
```
Step 4 - Mount the partition from the VM
```bash
mount /dev/nbd0p1 /mnt/somepoint/
```
Step 5 - After you done, unmount and disconnect
```bash
umount /mnt/somepoint/
qemu-nbd --disconnect /dev/nbd0
rmmod nbd
```
### Ubuntu - Power management
To make Ubuntu do nothing when laptop lid is closed:
From For 13.10 onwards:
Open the `/etc/systemd/logind.conf` file in a text editor as root, for example:
```bash
sudo -H gedit /etc/systemd/logind.conf
```
If `HandleLidSwitch` is not set to ignore then change it:
```bash
HandleLidSwitch=ignore
```
Other settings that the action can be ignored: `HandleLidSwitchExternalPower`, `HandleLidSwitchDocked`, `IdleAction`.
Restart the systemd daemon (be aware that this command will log you out):
```bash
sudo systemctl restart systemd-logind
```
or, from 15.04 onwards:
```bash
sudo service systemd-logind restart
```
### Chroot environment of Debian sid
Install Bootstrap
```bash
sudo apt install debootstrap
```
Create a directory that you want to use for the base system (_chroot-debian_ in this case)
```bash
mkdir chroot-debian
```
Create a base system
```bash
sudo debootstrap sid chroot-debian http://deb.debian.org/debian
```
Valid names `sid`, `stable` or any debian code name
Mount  filesystems
```bash
sudo mount -o bind /dev chroot-debian/dev
sudo mount -t sysfs none chroot-debian/sys
sudo mount -o bind /proc chroot-debian/proc
```
Optionally, copy DNS resolver configuration.
```
sudo cp /etc/resolv.conf /path/to/chroot-env/etc/resolv.conf
```
Start chrooting
```bash
sudo chroot chroot-debian /bin/bash
```
Once done, exit the session and unmount
```bash
sudo umount chroot-debian/dev chroot-debian/proc
```
#### Pass variables to chrooted environment
```bash
chroot ./ env -i PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
```
# Allowing user to run a command as root
```shell
sudo visudo
```
```
artur ALL=(ALL) chroot /path/to/chroot-env
```
#### Nginx - serving files setup DAV
Full version with 3rd party extensions
```
apt install nginx-full nginx-extras
```
```
location / {
index nonextistent;
autoindex on;
autoindex_format json;
}
location /restricted {
fancyindex on;
fancyindex_exact_size off;
auth_basic "Restricted";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
location /dropbox {
index nonextistent;
autoindex on;
autoindex_format json;
dav_methods PUT DELETE MKCOL COPY MOVE;
dav_ext_methods PROPFIND OPTIONS LOCK UNLOCK;
dav_access user:rw group:r all:r;
# client_max_body_size 0;
create_full_put_path on;
client_body_temp_path /tmp/;
limit_except GET PROPFIND OPTIONS HEAD {
auth_basic "Restricted";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
        # auth_pam "Restricted";
        # auth_pam_service_name "common-auth";
}
```
Create password
``` bash
echo -n 'sammy:' >> /etc/nginx/.htpasswd
openssl passwd -apr1 >> /etc/nginx/.htpasswd
```
Another method to set the password
```bash
htpasswd -c /etc/nginx/.htpasswd sammy
htpasswd /etc/nginx/.htpasswd another_user
```
**UI Client `Cyberduck`**
#### Backing up the entire OS
```
sudo rsync -aAXHv / --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /mnt
```
Python
```
install python3-full
```
### Check battery
```bash
upower -i /org/freedesktop/UPower/devices/battery_BAT0
upower -i `upower -e | grep 'BAT'`
upower -i $(upower -e | grep BAT) | grep --color=never -E "state|to\ full|to\ empty|percentage"
```
Battery capacity
```bash
cat /sys/class/power_supply/BAT0/capacity
```
`apt install acpi`
acpi -V
acpi -t
Watch the status for example:
```
watch --interval=5 acpi -V
```
### How to scan open ports
```
nmap -sT -p- 10.10.8.8
nmap -p 80 127.0.0.1
```
### Remove non ASCII characters form the file
```bash
sed 's/[^[:print:]\t]//g' script.sh > cleaned_script.sh
```
## Network Manager
Check Status
```
pacman -S networkmanager
systemctl status NetworkManager
```
```bash
nmcli dev status
nmcli radio wifi
```
```bash
nmcli radio wifi on
```
```bash
nmcli dev wifi list
```
```bash
nmcli dev wifi connect network-ssid
```
```bash
nmcli dev wifi connect network-ssid password "network-password"
# with password promot
nmcli dev wifi connect network-ssid password "network-password"
```
```
nmcli con show
```
```
nmcli con down ssid/uuid
nmcli con up ssid/uuid
```
```
ip link set eno1 up
```
### DHCP Client
```
pacman -S dhclient dhcpcd
```
Turn dchp on for the interface
```
dhclient eth0 -v
```
### Create file
```bash
cat > filename <<- "EOF"
file contents
more contents
EOF
```
### Get data about file include number of links
```bash
stat f1
```
### File decryption
```bash
openssl aes256 -md sha256 -d -in file.enc.zip -out file.zip -pass pass:"<password>"
```
### Base64
```bash
openssl base64 -in qrcode.png -out qrcode.png.base64
openssl base64 -in qrcode.png
```
### tar.xz
```
tar -xJf file.tar.xz -C destination
```
## Execute command
Execute `ls` for each each object in current directory that starts from `D` or `M`
```
ls {D*,M*}
```
Utworzenie dwóch katalogów `test_a`, `test_b`
```
mkdir test_{a,b}
```
### copy content of directory and merge it. Dereference links
```
cp -LTr /form/ .
```
## JSON Linux apis
```
tree -J
ls -l | jq -R -s -c 'split("\n")[:-1]'
```
### List dependencies
```bash
pacman -Sy lld
llvm-nm
```
### Find location of executable
```
type -a python
```
### Reload each file save
```bash
brew install fswatch
fswatch -o . --exclude "\.build.*$" | xargs -n1 -I{} your-command
```
## Add capabilities
allow all to open 443 port
```bash
sudo setcap 'cap_net_bind_service=+ep' ./service
```
# Test speed of the drive
```
sudo hdparam -t --direct /dev/mmcblk0
```

12
utils/regex.md Normal file
View file

@ -0,0 +1,12 @@
---
layout: default
title: Regex - notes
---
How to match “any character” in the regular expression
- `.` &rarr; any char except newline
- `\.` &rarr; the actual dot character
- `.?` = `.{0,1}` &rarr; match any char except newline zero or one times
- `.*` = `.{0,}` &rarr; match any char except newline zero or more times
- `.+` = `.{1,}` &rarr; match any char except newline one or more times

372
utils/vim.md Normal file
View file

@ -0,0 +1,372 @@
---
layout: default
title: Vim notes
categories: software
---
#### Symbols and meanings
- `%` &rarr; current file. An example: `:so %` &rarr; Source the current file
- `$` &rarr; end of line
- `.` &rarr; Current line An example: `:.!sh` &rarr; Pipe current line to `sh` and replace it with the output
Entering `!!` in normal mode is translated to `:.!` I. e. Typing `!!date` in normal mode replaces current line with the date.
#### Tips
- `:e[dit]` &rarr; Edit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim. `:e!` Force reload file
- `:help index` &rarr; Get all default mappings
#### Navigation
- `h` `j` `k` `l` &rarr; left, down, up, right
- `*` &rarr; Next whole word under cursor (previous `#`)
- `e` &rarr; Forward to the end of word. `E` can contain punctuation
- `w` &rarr; Move forward to the beginning of a word. `W` Same as `w`, but special characters are treated as part of a word.
- `b` &rarr; Works as `w`, but backwards
- `{`,`}` &rarr; Jump by paragraphs
- `(`,`)` &rarr; Jump by sentences
- `G` &rarr; Jump to the end of the file
- `1G` &rarr; Jump to the beginning of the file (same as `gg`)
- `50G` &rarr; Jump to line 50
- `0` &rarr; Beginning of line
- `_` or `^` &rarr; first non-blank character of the line
- `g_` &rarr; last non-blank character of the line
- `fX` &rarr; next character `X`. `FX` previous. `;` repeat , `,` repeat in reverse
- `tX` &rarr; tili next `X` (similar to above, but the cursor is before `X`)
- `H` &rarr; Jump to the top of the screen
- `M` &rarr; Jump to the middle of the screen
- `L` &rarr; Jump to the bottom of the screen
#### Scrolling
* `10 <PageUp>` or `10<CTRL-B>` &rarr; Move 10 pages up
* `5 <PageDown>` or `5<CTRL-F>` &rarr; Move 5 pages down.
- `zz` &rarr; scroll the line with the cursor to the center of the screen
- `zt` &rarr; to the top
- `zb` &rarr; to the bottom
### Terminal buffers
- `:te[rm[inal]] command`
- `:b#` switch buffer
- `:ls` list buffers
- `:buff 1` or `:b1` switch to buffer 1
### List of the commands
Common meaning of letters in the commands
- `w` &rarr; word
- `i` &rarr; inner
| Command | |
| ---: | :--- |
| `dd` | Delete one line |
| `d` | Delete selection |
| `x` | Delete character under cursor |
| `d+` | Delete 2 lines |
| `:%d` or :`1,$d` | Delete the whole of the file |
| `dw`, `diw` | Delete what that the cursor is over |
| `di(` | Delete inner brackets. `da(` &rarr; including brackets |
| `:r[ead] !date` | Execute commend and put content into editor |
| `.` | Repeat the last operation |
| `gU` | Uppercase the selection, `gu` &rarr; lower |
| `%` | Jump to matching bracket `{ }` `[ ]` `( )` |
| `:%!column -t` | Put text in columns |
| `:%!sort` | Sort the whole file |
| `:'<,'>!grep text` | Keep lines that contains `text` |
| `:'<,'>!sort` | Sort selected lines |
| `:eariler 1m` | State from the 1 min before |
| `ga` | Display hex, ascii value of character under cursor |
| `g8 ` | Display hex value of utf-8 character under cursor |
| `ciw` | Change inner word |
| `yiw` | Yank inner word |
| `viwp` | Select word and then replace it with previously yanked text |
| `rX` | replace every character in selection or under cursor with `X` |
| `guiw` | Lower case word |
| `guu` | Lowercase line |
| `gUU` | Uppercase line |
| `=` | Indent the selection |
| `=%` | Indent the current braces |
| `G=gg` | indent entire document |
| `ZZ` | Write current file, if modified, and exit (same as `:wq`) |
| `ZQ` | Quit current file and exit (same as `:q!`) |
| `:so %` | Source current file |
| `@:` | Execute last command again |
#### Status line
```vim
:set statusline=%<%f%h%m%r%=%b\ 0x%B\ \ %l,%c%V\ %P
```
#### Visual Mode
- `V` &rarr; Selection by lines
- `v` &rarr; Selection follows the cursor
- `Ctrl+v` &rarr; Block selection
- When selected block you can applay changes to each line by typing `I` editing and finally pressing `Esc`
#### Enter Insert Mode
- `I` &rarr; At the first non white character of the line
- `i` &rarr; On the left of the cursor
- `A` &rarr; At the very end of the line
- `a` &rarr; On the right of the cursor
- `c` &rarr; Delete selection and enter insert mode
- `o` &rarr; Create new line below and enter insert mode
- `O` &rarr; Create new line above and enter insert mode
#### Split the editor
- `:sp <filename>` &rarr; Vertically
- `:vs <filename>` &rarr; Horizontally
- `:set splitbelow`, `:set splitright`
#### Markers
- `:marks` &rarr; list of marks
- `ma` &rarr; set current position for mark `a`
- `` `a`` &rarr; jump to the cursor position of mark `a`
- `'a` &rarr; jump to the beginning of a line of a mark `a`
- ``y`a`` &rarr; yank text to position of mark `a`
* ``` `` ``` &rarr; Return to the cursor position before the latest jump
* `` `.`` &rarr; Jump to the last changed line.
### Recording macros
1. `qa` &rarr; Start recording macro under letter `a`
2. `q` &rarr; Stop recording
3. `@a` &rarr; Play the macro saved under letter a
4. `@@` &rarr; Play the last macro
#### Searching
- `:%s/Plug.*$//` &rarr; Search and delete all lines that starts from Plug
- `:%s/foo/bar/gc` &rarr; Replace all occurrence of foo by bar with confirmation
- `'<,'>:s/find/replacewith/` Replace selection
- `/pattern` &rarr; search for pattern then enter and `n` next `N` previous match
- `?pattern` &rarr; search backward for pattern
### Registers
- `:reg` &rarr; print all registers
- `"ap` &rarr; paste the register `a` , if the macro is recorded then it will paste it
- `"xy` &rarr; yank into register `x`
- `:let @a = "kkll"` &rarr; set a macro from the command mode
- `:let @A='i'` &rarr; append to register `a`
- `:%normal @a` &rarr; execute the macro on all lines of the current file
- `:'<,'>normal @a` &rarr; execute the macro on a visually selected lines
- `:10,20 normal @a` &rarr; execute the macro for lines from 10 to 20
- `:g/pattern/ normal @a` &rarr; Search for pattern and execute macro for it
#### Functions - An example
Function definition
```vim
function! CalculateAge()
normal 03wdei^R=2012-^R"^M^[0j
endfunction
```
Key banding to function
```vim
nnoremap <leader>a :call CalculateAge()<CR>
```
Preloading vim with macros like
```vim
let @a='03wdei^R=2012-^R"^M^[0j'
```
Call function from the command mode
```
:call CalculateAge()
```
#### Configuration
The config file is located at `.config/nvim/init.vim`
```vim
if empty(glob('~/.local/share/nvim/site/autoload/plug.vim'))
silent !curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs
\ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
call plug#begin('~/.vim/plugged')
Plug 'junegunn/fzf'
Plug 'neovim/nvim-lspconfig'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'vim-syntastic/syntastic'
Plug 'tokorom/syntastic-swiftlint.vim'
call plug#end()
```
- `set relativenumber`
- `set encoding=utf-8`
- `syntax on`
- `map za :FZF<CR>` &rarr; fuzzy finder over `za`
Indentation setup
- `set tabstop=2 shiftwidth=2 expandtab`
- `filetype plugin indent on`
```vim
let g:syntastic_swift_checkers = ['swiftlint', 'swiftpm']
lua << EOF
local lspconfig = require('lspconfig')
lspconfig.sourcekit.setup{}
EOF
```
#### Rename current file
```vim
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
exec ':bd ' . old_file
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
```
<!--
### Navigation in Vimr
- jump to the next empty line (the next paragraph)`}`
* Recording macros
* `"xp` pastes the contents of the register `x`.
* `~ ` : invert case (upper->lower; lower->upper) of current character
* `gf ` : open file name under cursor (SUPER)
* `ggg?G` : rot13 whole file
* `xp` : swap next two characters around
* `CTRL-A,CTRL-X` : increment, decrement next number on same line as the cursor
* `CTRL-R=5*5` : insert 25 into text
* `'.` : jump to last modification line (SUPER)
* *`.* : jump to exact spot in last modification line
* `<C-O>` : retrace your movements in file (backward)
* `<C-I>` : retrace your movements in file (forward)
* `:ju(mps)` : list of your movements {{help|jump-motions}}
:history : list of all your commands
Sorting with external sort
:%!sort -u : contents of the current file is sorted and only unique lines are kept
:'v,'w!sort : sort from line marked v thru lines marked w
:g/^$/;,/^$/-1!sort : sort each block (note the crucial ;)
!1} sort : sorts paragraph; this is issued from normal mode!)
:wn : write file and move to next (SUPER)
:bd : remove file from buffer list (SUPER)
:sav php.html : Save current file as php.html and "move" to php.html
:w /some/path/%:r : save file in another directory, but with the same name
:e # : edit alternative file
:args : display argument list
:n : next file in argument list
:prev : previous file in argument list
:rew : rewind to first file in argument list
:ls : display buffer list
:bn : next buffer
:bp : previous buffer
:brew : rewind to first buffer in buffer list
:tabe : open new tab page (Ctrl-PgUp, Ctrl-PgDown for next/previous tab)
:tabm n : move tab to position n (0=leftmost position)
# editing a register/recording
"ap
<you can now see register contents, edit as required>
"add
@a
Ctrl-D move half-page down
Ctrl-U move half-page up
Ctrl-B page up
Ctrl-F page down
Ctrl-O jump to last (older) cursor position
Ctrl-I jump to next cursor position (after Ctrl-O)
Ctrl-Y move view pane up
Ctrl-E move view pane down
n next matching search pattern
N previous matching search pattern
g* next matching search (not whole word) pattern under cursor
g# previous matching search (not whole word) pattern under cursor
de — Delete to the end of the word
^R= — Insert the contents of the special = register, which accepts an expression to evaluate
gUgn - uppercase
gn
n move to the next match
Undo and redo
You can use u to undo the last change. CTRL-R redoes a change that has been undone. U returns the current line to its original state.
You can use g- or g+ to go between text-states.
Search and replace
* `\vpattern` - 'very magic' pattern: non-alphanumeric characters are interpreted as special regex symbols (no escaping needed)
* `n` - repeat search in same direction
* `N` - repeat search in opposite direction
* `:noh` - remove highlighting of search matches
Search in multiple files
* `:vimgrep /pattern/ {file}` - search for pattern in multiple files
* e.g. `:vimgrep /foo/ **/*`
* `:cn` - jump to the next match
* `:cp` - jump to the previous match
* `:copen` - open a window containing the list of matches
folding from selection
`: '<,'>fo`
`:help folding`
set foldmethod=syntax
`set foldlevel=1`
`set foldclose=all`
Sequence forfolding lines `Shift+V:fo`
`:set foldmethod=syntax` intent,
`zo` unfolding
`za` toogle folding
`zf#j` creates a fold from the cursor down # lines.
:CheckHealth
-->