Utente:Amux/Memorandum

Explorer.exe modifica

Aprire Windows Explorer con una certa cartella come radice:

explorer.exe /e,/root,"path"

Per inciso, se un'anima pia mi sussurrasse dal cielo come sia possibile farlo con Konqueror loderei a vita le sue gesta.

Ricodifica di video per Nokia N70 modifica

Good quality:

mencoder $INFILE -cache 1024 -vf scale=208:176 -srate 22050 -ovc xvid -oac mp3lame -xvidencopts bitrate=224 -lameopts vbr=0:mode=3:br=40 -o $OUTFILE.avi

Normal quality:

mencoder $INFILE -cache 1024 -vf scale=208:176 -srate 16000 -ovc xvid -oac mp3lame -xvidencopts bitrate=112 -lameopts vbr=0:mode=3:br=32 -ofps 12 -sws 2 -o $OUTFILE.avi

Con ffmpeg:

ffmpeg -i $INFILE.avi -f 3gp -vcodec 3gp -b 100000 -s 208x176 -r 12 -acodec aac -ar 8000 -ab 16 -ac 1 $OUTFILE.3gp

fonte: [1]

Socat modifica

socat -u TCP4-LISTEN:3334,reuseaddr,fork OPEN:/tmp/in.log,creat,append

Dump su disco di stream video con VLC modifica

vlc --demux dump --demuxdump-file outfile.ext protocol://address

Dump di audio da video FLV modifica

FOR %%I IN (*.flv) DO mplayer -dumpaudio -dumpfile "%%~nI.mp3" "%%I"

o in alternativa:

ffmpeg -i input.flv -vn -acodec pcm_s16le -ar 44100 -ac 2 output.wav

Creazione di una immagine Ubuntu JEOS modifica

sudo vmbuilder vmw6 ubuntu --arch i386 --user user --name user --pass user --suite lucid --flavour virtual

Quickstart Mercurial modifica

Minimal hgrc file modifica

Create /etc/mercurial/hgrc, or ~/.hgrc with the following contents:

[ui]
username = username <email@domain.com>
merge = kdiff3

# since Mercurial 4.3
#   hg status prints relative paths
#   hg diff produces patches in git format
#   hg {commit,shelve} --interactive use a curses UI
#   hg diff uses worddiff
tweakdefaults = True

[alias]
# Source: https://stackoverflow.com/questions/2228188/finding-the-author-of-a-line-of-code-in-mercurial#2243667
blame = annotate --user --number
log = log --graph
serve-insecure = !echo "Run this command:\nhg serve --config web.push_ssl=No --config \"web.allow_push=*\""

[extensions]
extdiff =
histedit =
mq =
rebase =
strip =

[extdiff]
cmd.vdiff = meld

[web]
allow_archive = gz, zip, bz2

Without a username you will not be able to commit.

Install hg-git modifica

Step 1: install dulwich:

# system-level on debian-like systems
sudo apt install python-dulwich

# or better: user-level on any system
pip install --user dulwich

Step 2: install hg-git extension:

Before going on, ensure dulwich is installed following step 1 above

# hg-git will be installed in <BASE_DIR>/hg-git
BASE_DIR="/opt/mercurial"

MYUSER="id --user --name"
MYGROUP="id --group --name"

# install hg-git
mkdir "${BASE_DIR}"
chown "${MYUSER}":"${MYGROUP}" "${BASE_DIR}"
hg clone https://foss.heptapod.net/mercurial/hg-git "${BASE_DIR}"/hg-git

cat <<EOF

Now add this to your /etc/mercurial/hgrc (or ~/.hgrc):
   [ui]
   ...
   # if the repository is a git clone, show the git
   # commit hash in the output of hg log:
   #
   #    changeset:   5253:267f2e2e089c
   #    git-commit:  686ce054fae4
   #
   logtemplate = "{changeset_git}"

   [extensions]
   ...
   hggit = ${BASE_DIR}/hg-git/hggit

   Append the contents of map-cmdline.default and add the following lines:
   [templates]
   # support "git-commit" line in hg log
   changeset_git = '{cset}{cset_git}{branches}{bookmarks}{tags}{parents}{luser}{ldate}{ltroubles}{lobsfate}{summary}\n'
   cset_git      = '{if(gitnode, "git-commit:  {label("status.unknown", gitnode|short)}\n")}'

   ...the rest of 'templates' section of map-cmdline.default...

   [templatealias]
   ...the whole 'templatealias' section of map-cmdline.default...

EOF

Servire repository multipli con Mercurial modifica

Creare il file hgweb.config, che servirà ad istruire Mercurial sui percorsi dei repository da servire.

[paths]
Etichetta1 = /percorso/repo1
Etichetta2 = /precorso/repo2

Il seguente script (start-server.sh) può essere utilizzato per lanciare il server interno di Mercurial:

#!/bin/sh
hg serve --webdir-conf ./hgweb.config

Dopo l'esecuzione di start-server.sh il repository sarà disponibile sulla porta 8000

TortoiseHg/Windows: aprire Cygwin nella directory del repository modifica

Se si usa TortoiseHg su Windows e si vuole utilizzare Cygwin anziché la shell di Windows, inserire questo comando in File | Settings | TortoiseHg | Shell:

C:\cygwin64\bin\mintty.exe --title "%(reponame)s" --icon /Cygwin-Terminal.ico /bin/env CHERE_INVOKING=1 /bin/bash -l

Serving a repository allowing plaintext push from everywhere modifica

Quick and temporary way to set up a mercurial server

hg serve --config web.push_ssl=No --config "web.allow_push=*"

Grub.cfg using loopback files with Grub 2 modifica

In a contemporary (e.g., post UEFI) world, it is better to prepare an hybrid USB drive following the instructions on the Arch Linux wiki.


Dopo aver installato Grub 2 su un drive flash Usb, è possibile far partire delle distribuzioni live direttamente dai file iso usando questo file grub.cfg:

set timeout=10
set default=0

menuentry "Lubuntu Live 17.10 64bit UEFI" {
	set isofile="/boot/lubuntu-17.10-desktop-amd64.iso"
	loopback loop $isofile
	linux (loop)/casper/vmlinuz.efi boot=casper iso-scan/filename=$isofile bootkbd=it
	initrd (loop)/casper/initrd.lz
}

# source: https://github.com/aguslr/multibootusb/blob/master/mbusb.d/fedora.d/workstation-generic.cfg
menuentry "Start Fedora 27 LXQt Live" {
   set iso_path="/boot/iso/Fedora-LXQt-Live-x86_64-27-1.6.iso"
   loopback loop "$iso_path"
   probe --label --set=cd_label (loop)
   bootoptions="iso-scan/filename=$iso_path root=live:CDLABEL=$cd_label rd.live.image"
   linux (loop)/isolinux/vmlinuz $bootoptions
   initrd (loop)/isolinux/initrd.img
}

menuentry "SystemRescueCD 2.0.0 32bit" {
	set isofile="/boot/systemrescuecd-x86-2.0.0.iso"
	loopback loop $isofile
	linux    (loop)/isolinux/rescuecd isoloop=$isofile setkmap=it
	initrd   (loop)/isolinux/initram.igz
}

menuentry "SystemRescueCD - FreeDOS" {
	loopback loop /boot/systemrescuecd-x86-2.0.0.iso
	linux16  (loop)/isolinux/memdisk
	initrd16 (loop)/bootdisk/freedos.img
}

menuentry "netboot.me ERR" {
   loopback loop /boot/netbootme.iso
   linux16  (loop)/GPXE.KRN
}

menuentry "Fedora BFO" {
  linux /boot/bfo.lkrn
}

menuentry "Tinycore 3.4.1" {
  loopback loop /boot/tinycore_3.4.1.iso
  linux    (loop)/boot/bzImage
  initrd   (loop)/boot/tinycore.gz
}

Servire una directory via HTTP con Python modifica

Con Python >= 2.5 è possibile condividere immediatamente il contenuto di una cartella via HTTP:

cd <directory_da_condividere>
python -m SimpleHTTPServer 8080

Lista di tutti i file e dei relativi permessi di una directory modifica

Genera una lista di tutti i file nella directory corrente e nelle sottocartelle. Dalla lista viene escluso (in questo esempio) il contenuto della directory ".hg". Per ciascun file, viene aggiunto in testa il permesso e l'ownership.

find . -type f -and -not -path './.hg/*' -print0 | xargs -0 ls -l | awk '{print $1,$3,$4,$9}'

Esempio di output:

-rw-r--r--. root root ./wp-includes/post-thumbnail-template.php
-rw-r--r--. root root ./wp-includes/query.php
-rw-r--r--. root root ./wp-includes/registration-functions.php

Somma md5 di tutti i file di una directory, escludendo la .hg modifica

Se un cattivone non ti fa usare il controllo versione, devi pur trovare un'alternativa:

find . -type f -and -not -path './.hg/*' -print0 | xargs -0 md5sum | sort -k 2

Scrivere script bash un po' meno che pessimi modifica

#!/bin/bash

# Impostazioni di sicurezza:
#
# - Facciamo terminare lo script al primo comando che non ritorna exit code 0
#   (failsafe: farlo in mancanza di una routine di trap degli errori)
# - Usciamo se delle varibili non vengono valorizzate ("-u")
# - Se un comando in una pipe fallisce, ritorniamo l'exit code del comando che è
#   fallito ("pipefail")
#
# Si noti che in generale sarebbe bene impostare settings ancora più stretti, ad
# esempio "set -euf -o pipefail".
#
# Si veda: https://sipb.mit.edu/doc/safe-shell/
set -eu -o pipefail

Overlay OpenWrt on USB pendrive modifica

#!/bin/sh

mountOverlay() {
	BASEOVERLAY=/mnt/usb/overlay
	mount -t overlayfs -o lowerdir=$1,upperdir=${BASEOVERLAY}$1 overlayfs $1
}

mountOverlay /bin
mountOverlay /etc
mountOverlay /lib
mountOverlay /sbin
mountOverlay /usr
mountOverlay /www

Generare password casuali modifica

Per generare una password fatta di 20 caratteri casualissimi (e print-safe):

tr --complement --delete '[:graph:]' < /dev/urandom | fold --width=20 | head --lines 1

Esempio di output:

B8V6f:lhr*\WS8'&e;fR

Estrarre informazioni da una pagina web con XPath modifica

  • Selezionare il nodo che interessa e, usando Firebug, copiare l'XPath (ad esempio, il secondo <a> all'interno di tutte le prime colonne di una tabella).
  • Semplificare l'XPath ottenuto per far sì che matchi tutti i nodi di nostro interesse (ad esempio, eliminare il riferimento alla particolare <tr> su cui si è fatto click)
  • Stampare le informazioni contenute nei nodi (ad esempio l'href dei link):
const xpath = "/html/body/div[7]/table/tbody/tr/td/a[2]";

const nodesSnapshot = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < nodesSnapshot.snapshotLength; i++) {
  console.log(nodesSnapshot.snapshotItem(i).href);
}

Se si vuole il contenuto testuale di un nodo anziché un suo attributo, usare .textContent

MAC2UNIX modifica

I line endings MacOS (CR, ASCII 13) in formato Unix (LF, ASCII 10)

sed 's/\o015/\n/g' inputfile

Per convertire in place aggiungere --in-place.

Konsole: clear scrollback with "reset" modifica

In Konsole, reset command does not clear scrollback (and is slow).

Add this line to ~/.bash_aliases:

alias res="clear && printf '\e[3J'"

source: http://askubuntu.com/questions/25077/how-to-really-clear-the-terminal#473770

Alternatively (and without any additional configuration), the keystroke Control+ Maiusc+K can be used.

  • Advantages: super fast;
  • Disadvantages: KDE Konsole-specific, does not work with other terminal emulators.

Long running TCP capture modifica

Capturing all the packet that go to a Kafka Broker and rotate the files every hour:

screen -S packet-capture
tcpdump -i bond0  "(dst port 9000)"  -G 3600 -w '/some/big/dir/packet-capture_%Y-%m-%d_%H.%M.pcap'

If you want to see only the TCP retransmissions:

tshark -r captured.pcap -Y tcp.analysis.retransmission

Remove al "rc" packages in debian-like systems modifica

dpkg --list | egrep "^rc" | awk '{ print $2 }' | xargs sudo dpkg --purge

Find out what is wasting disk space modifica

You do not know if there is some network file system mounted. So better you do not cross file system boundaries when scanning. You can repeat the search for each different file system.

# du requires special options to scan hidden files when using bash expansion
du --one-file-system  -sch .[!.]* * | sort --human-numeric-sort

Or just use ncdu, which has a TUI interface. "-x" means do not cross file system boundaries.

ncdu -x

Sample output from ncdu:

ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ------------------------------------------------------
    5,3 GiB [##########] /usr
    1,8 GiB [###       ] /home
    1,5 GiB [##        ] /opt
  485,1 MiB [          ] /var
  436,4 MiB [          ] /lib

Spark Streaming performance: find slowest tasks modifica

Go to the directory containing the driver log. Run:

grep "Finished task " stderr | cut -d' ' -f 1,2,11,12,14- | sort -k 5 --numeric-sort

Expected output:

17/02/03 17:07:03 (TID 5) 1987 ms on ssd-01 (12/15)
17/02/03 17:07:03 (TID 8) 2018 ms on ssd-01 (13/15)
17/02/03 17:07:03 (TID 12) 2088 ms on ssd-03 (14/15)
17/02/03 17:07:03 (TID 11) 2090 ms on ssd-01 (15/15)
17/02/04 07:15:35 (TID 191448) 30030 ms on ssd-02 (10/10)   <=== you have a problem here
17/02/03 22:09:50 (TID 66286) 30036 ms on ssd-01 (10/10)
17/02/04 12:10:50 (TID 262447) 30036 ms on ssd-01 (1/1)
17/02/04 16:31:25 (TID 323582) 30039 ms on ssd-01 (1/1)

Tested on Spark 1.6.x.

You can tail -f the driver log in real time and show only the tasks that complete in more than a certain amount of time (for example, 25 seconds).

tail -f driver-XXXX/stderr | awk '(/Finished task/ && ($14 > 25000) ) { print $1,$2,$11,$12,$14,$15 }'

Cygwin: enable CTRL + arrows in mintty modifica

Add the following to ~/.inputrc:

# Source: https://superuser.com/questions/488157/how-do-i-make-ctrl-arrow-keys-move-forward-backward-a-word-at-a-time-in-cygwin-b#488158
"\e[1;5C": forward-word   # ctrl + right
"\e[1;5D": backward-word  # ctrl + left

Bash: case-insensitive TAB completion modifica

To make Bash autocompletion case-insensitive, add the following to ~/.inputrc:

# source: https://superuser.com/questions/271530/make-bashs-tab-completion-case-insensitive#271534
set completion-ignore-case on

Coexisting with Puppet modifica

List all the packages that Puppet wants to enforce:

puppet resource package | grep package | awk '{ print gensub(/package { '\''(.*)'\'':/, "\\1", "g");}' | sort

Compare it with the list of actually installed packages (on CentOS / RHEL):

rpm -qa --qf "%{NAME}\n" | sort | uniq

Measure network latency via a TCP socket, without Ping modifica

Nmap can "ping" a host via TCP (in order to measure its latency):

# Source: https://superuser.com/questions/769541/is-it-possible-to-ping-an-addressport#772287
nping --tcp -p <dest_port> --count 20 <dest_host>

Output:

Starting Nping 0.6.40 ( http://nmap.org/nping ) at 2017-06-06 13:52 CEST
SENT (0.0205s) TCP 10.120.199.23:53291 > 10.120.169.61:1521 S ttl=64 id=50779 iplen=40  seq=2161527960 win=1480
RCVD (0.0221s) TCP 10.120.169.61:1521 > 10.120.199.23:53291 SA ttl=63 id=0 iplen=44  seq=1354236295 win=29200 <mss 1460>
[...]
SENT (49.1121s) TCP 10.120.199.23:53291 > 10.120.169.61:1521 S ttl=64 id=50779 iplen=40  seq=2161527960 win=1480
RCVD (49.1135s) TCP 10.120.169.61:1521 > 10.120.199.23:53291 SA ttl=63 id=0 iplen=44  seq=2121287952 win=29200 <mss 1460>

Max rtt: 1.873ms | Min rtt: 0.761ms | Avg rtt: 1.222ms
Raw packets sent: 50 (2.000KB) | Rcvd: 50 (2.300KB) | Lost: 0 (0.00%)
Nping done: 1 IP address pinged in 49.13 seconds

The latency can be estimated with the Round Trip Time statistics at the end.

Firewalld: open a port only from a specific source IP modifica

Taken from: https://serverfault.com/questions/684602/how-to-open-port-for-a-specific-ip-address-with-firewall-cmd-on-centos#684603

firewall-cmd --permanent --zone=public --add-rich-rule='
  rule family="ipv4"
  source address="1.2.3.4/32"
  port protocol="tcp" port="4567" accept'

Check the zone file later to inspect the XML configuration

cat /etc/firewalld/zones/public.xml

Reload the firewall:

firewall-cmd --reload

pack/unpack tar.gz across remote destinations modifica

This is an old trick, but comes in handy when you are short of disk space:

# take a folder on a remote host and create tar.gz of it in your PC
ssh root@hostname "cd /dir ; tar zcf - foldername" > local-archive.tar.gz

# take a tar.gz on your PC and directly decompress it on a remote
# host without moving it there
cat local-archive.tar.gz | ssh root@hostname "cd /dir ; tar xf -"

Download JDK via cURL modifica

To download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html via cURL.

Change version numbers as needed.

curl \
   --verbose \
   --location \
   --remote-name \
   -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0" \
   -H "cookie: oraclelicense=accept-securebackup-cookie" \
   http://download.oracle.com/otn-pub/java/jdk/8u152-b16/aa0333dd3019491ca4f6ddbe78cdb6d0/jdk-8u152-linux-x64.tar.gz

The checksums are found at https://www.oracle.com/webfolder/s/digest/8u152checksum.html

Full path of processes keeping handles of deleted files modifica

More than anything, this is an exercise in awk-fu.

# lsof | awk ' (/deleted/) { print $2 } ' | sort | uniq --count | sort --numeric --reverse | awk ' BEGIN { print "COUNT PATH PID" } { cmd = "readlink --canonicalize /proc/"$2"/exe" ; cmd | getline proc_path ; print $1,proc_path,$2 } ' | column --table

Output sample:

COUNT  PATH                                                  PID
1080   /opt/OV/bin/oacore                                    2633
652    /usr/oemagent/app/core/12.1.0.5.0/jdk/bin/java        9555
234    /u01/app/12.1.0/grid/bin/ohasd.bin                    2652
190    /u01/app/12.1.0/grid/bin/ocssd.bin                    11727
114    /u01/app/12.1.0/grid/bin/oraagent.bin                 3683
42     /u01/app/12.1.0/grid/bin/scriptagent.bin              3686
32     /u01/app/12.1.0/grid/bin/evmd.bin                     3786
30     /u01/app/12.1.0/grid/bin/cssdagent                    11694
12     /u01/app/12.1.0/grid/bin/evmlogger.bin                5486
2      /usr/oemagent/app/core/12.1.0.5.0/perl/bin/perl       9483
2      /u01/app/12.1.0/grid/bin/oracle                       31894
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    19918
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    17365
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    15496
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    15399
2      /u01/app/oracle/product/11.2.0.4/dbhome_1/bin/oracle  15049
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    14917
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    14810
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    14799
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    14797
2      /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle    14459
[...]

Record a screencast via command line modifica

Sometimes you are lazy and you do not want a GUI for recording a screencast. You can always use byzanz:

byzanz-record --delay=1 --duration=10 --x=1 --y=26 --width=935 --height=535 out.flv

To find the required window geometry you can use xwininfo:

$ xwininfo 

xwininfo: Please select the window about which you
          would like information by clicking the
          mouse in that window.

xwininfo: Window id: 0x1c00003 "window title"

  Absolute upper-left X:  153
  Absolute upper-left Y:  408
  Relative upper-left X:  1
  Relative upper-left Y:  26
  Width: 1126
  Height: 573
  Depth: 32
  [...]

Generate animated gif from a video with ffmpeg modifica

GitHub only accepts animated gifs for screencasts.

#!/usr/bin/env bash

INPUT_FILE=input-file.flv
OUTPUT_FILE=output-file.gif
PALETTE_FILE=palette.png
FPS=10

ffmpeg -y -i "${INPUT_FILE}" -vf fps="${FPS}",scale=-1:-1:flags=lanczos,palettegen "${PALETTE_FILE}"
ffmpeg -i "${INPUT_FILE}" -i "${PALETTE_FILE}" -filter_complex "fps=${FPS},scale=-1:-1:flags=lanczos[x];[x][1:v]paletteuse" "${OUTPUT_FILE}"
rm "${PALETTE_FILE}"

Simplified from: https://superuser.com/questions/556029/how-do-i-convert-a-video-to-gif-using-ffmpeg-with-reasonable-quality#556031

Super low level Makefile debugging modifica

make SHELL="/bin/bash -x" <target>

Source on Stack Overflow

PDF: remove pages and print 2 per sheet modifica

I used to use pdftk for this, but since ubuntu 18.04 it is no longer included in the default repositories.


Generate a new PDF file, preserving metadata, but containing only page 3 and 7 to 23:

qpdf inputfile.pdf --pages inputfile.pdf 3,7-23 -- less-pages.pdf

Generate a new PDF that has 2 pages per sheet:

pdfnup less-pages.pdf --outfile two-per-sheet.pdf

Capture packets on a server, see them in Wireshark on another, in real time modifica

You want to capture packets on a headless server, but want to see them in Wireshark GUI instead of reading tcpdump output, because today you do not feel geek enough.

# source: https://openwrt.org/docs/guide-user/firewall/misc/tcpdump_wireshark
ssh root@router "tcpdump -i br-lan --packet-buffer --snapshot-length=0 -w - '(not port 22) and (not host iPhone.lan) and (not ip6)'" | wireshark -k -i -

mercurial: compare each single commit of a rebased change series modifica

Suppose you have rebased a series of commits on top of another base, keeping the original series. Before deleting the original commits, you may want to compare the each diff of the two branches and ensure they are effectively the same.

Observing that the distance between corresponding commits in the two branches is always the same, you can just start from the first commit of branch 1 and move on. The corresponding rebased commit on the other branch will be identified summing a constant offset.

o  changeset:   5:916ce4310330  <-- LAST_BRANCH_2
|  tag:         tip
|  summary:     second commit
|
o  changeset:   4:0889409942eb  <-- INITIAL_BRANCH_2
|  summary:     first commit
|
@  changeset:   3:7350499e6075
|  parent:      0:0afbc30b129e
|  summary:     new-base
|
| o  changeset:   2:9ddea66d56e1  <-- LAST_BRANCH_1
| |  summary:     second commit
| |
| o  changeset:   1:6812974f7138  <-- INITIAL_BRANCH_1
|/   summary:     first commit
|
|
o  changeset:   0:0afbc30b129e
   summary:     original-base

To verify that commits 4,5 are identical to commit 1,2 you can use the following command:

for X in $(seq 1 2) ; do diff --unified <(hg diff --change $X) <(hg diff --change $((X+3))) ; done

In general:

for X in $(seq INITIAL_COMMIT_BRANCH_1 LAST_COMMIT_BRANCH_1) ; do diff --unified <(hg diff --change $X) <(hg diff --change $((X+ <INITIAL_BRANCH_1 - INITIAL_BRANCH_2> ))) ; done


python: serve a directory via ssl modifica

A version of SimpleHTTPServer that serves a directory via SSL. Useful for testing purposes.

#!/usr/bin/env python

import BaseHTTPServer, SimpleHTTPServer
import ssl

LISTEN_ADDRESS='0.0.0.0'
LISTEN_PORT=30161
CERTFILE = '/path/to/certificate.crt'
KEYFILE  = '/path/to/certificate.key'

httpd = BaseHTTPServer.HTTPServer((LISTEN_ADDRESS, LISTEN_PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile=CERTFILE, keyfile=KEYFILE, server_side=True)

Manually install Libreoffice on Windows modifica

This method realizes a "portable" installation of LibreOffice on a Windows System without requiring administrative privileges.

msiexec -a LibreOffice_6.2.2_Win_x64.msi /qb TARGETDIR=d:\<destpath>\libreoffice

Finalization passes:

  • Create a link in the start menu
  • If the shared libraries for vcruntime are not installed system-wide, manually copy msvcp140.dll and vcruntime140.dll from <TARGETDIR>\System64 to <TARGETDIR>\program.

Remove last token with awk modifica

cat somefile.txt | awk -F'/' 'sub(FS $NF,x)'

Input:

aj/org/objectweb/asm/AnnotationVisitor.class
aj/org/objectweb/asm/signature/SignatureWriter.class

Output

aj/org/objectweb/asm
aj/org/objectweb/asm/signature

Source: https://www.unix.com/302542666-post5.html?s=63fcd6f5f711f8cdb76bf82e8133538f

Encrypt a directory with gpg modifica

Source code for encrypt-dir.sh:

#!/usr/bin/env bash
#
# Uses gpg to symmetrically encrypt a directory.
# The encrypted file is created in the same directory containing the input directory.

set -eu
set -o pipefail

DIR_NAME="$1"

DIR_FULL_NAME=$(realpath --canonicalize-existing "$1")

if ! [[ -d "${DIR_FULL_NAME}" ]]; then
        echo "\"${DIR_FULL_NAME}\" must be a directory. It isn't"
        exit 1
fi

OUTPUT_FILE="${DIR_FULL_NAME}.gpg"

if [[ -f "${OUTPUT_FILE}" ]]; then
        echo "ERROR: ${OUTPUT_FILE} already exists"
        exit 2
fi

echo "Encrypting directory ${DIR_FULL_NAME} and writing ${OUTPUT_FILE}"
tar czv "${DIR_NAME}" | gpg2 --symmetric --cipher-algo aes256 --output="${OUTPUT_FILE}"

md5sum "${OUTPUT_FILE}"

This will create a <dirname.gpg> file in the current directory. To decrypt it:

gpg --decrypt <dirname.gpg> | tar zxf -

pyenv: prevent Python compilation problems modifica

On a standard ubuntu 19.04 system, compiling Python via pyenv will require installing the following packages:

sudo apt install -y libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev libncurses5-dev libncursesw5-dev libffi-dev liblzma-dev

Source: https://github.com/pyenv/pyenv/wiki/common-build-problems#prerequisites


Whatsapp: poor man's media backup modifica

On a rooted Android phone:

cd /sdcard/WhatsApp/Media
find . -type f | egrep -iv "sent|nomedia" > /sdcard/whatsapp-media-list.txt

On the PC:

adb shell 'cd /sdcard/WhatsApp/Media ; tar -zcf - -T /sdcard/whatsapp-media-list.txt' > whatsapp-media-backup.tar.gz

systemd-nspawn: boot into an ephemeral snapshot of the host system modifica

Runs a copy of the host system in a snapshot which is removed immediately when the container exits. All file system changes made during runtime will be lost on shutdown. Works flawlessly when the host's filesystem is on btrfs (or any other COW FS).

systemd-nspawn --ephemeral --boot --directory /


Taken from systemd-nspawn manual

sqlite: default configuration modifica

Put this in ~/.sqliterc:

.mode box
.headers on
.nullvalue NULL
PRAGMA foreign_keys = ON