Morse code generator with Sed
#!/bin/sed -rf s/.*/\U&/ s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../ :a s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/ ta s/\n.*//
Morse code generator with Sed
#!/bin/sed -rf s/.*/\U&/ s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../ :a s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/ ta s/\n.*//
Calculate area and perimeter of any triangle
#!/usr/bin/python3
import sys, math
a, b, c = map(float, sys.argv[1:])
if a + b <= c or a + c <= b or b + c <= a:
print("Error: not a valid triangle")
sys.exit(1)
peri = a + b + c
area = math.sqrt((a + b + c) *
(a + b - c) *
(a - b + c) *
(-a + b + c)) / 4
print("Perimeter =", peri)
print("Area =", area)
Vidir (part of Debian’s moreutils) lets me edit the names of files in a directory in vim as though the directory was just a file, which it really is.
Put text in an ASCII art box:
#!/usr/bin/env python3
import sys
print("+" + "-" * 62 + "+")
for line in sys.stdin:
print(f"| {line.rstrip():<60} |")
print("+" + "-" * 62 + "+")
Print all primes less than 5000:
$ python3 -c 'print([i for i in range(2,5000) if all(i%j for j in range(2,int(i**0.5)+1))])'
Break a GIF into individual frames:
ffmpeg -i taarna.gif frame_%d.jpg
List all the words in a file with no matches in the dictionary:
aspell list < huckfinn.txt
Play a G major chord on ‘guitar’ using the sox package:
play -n synth pl G2 pl B2 pl D3 pl G3 pl D4 pl G4 delay 0 .05 .1 .15 .2 .25 remix - fade 0 4 .1 norm -1
Convert a PDF file to JPEG:
pdftocairo path/to/file.pdf -jpeg
Tally a column of figures in awk:
awk '{sum += $3} END {print "Total:", sum}' tribes
Tell Python to recite the powers of two in English
seq 1 16|while read n;do echo $((2**n));done|python3 -c "import sys,inflect;p=inflect.engine();[print(p.number_to_words(int(x.strip()))) for x in sys.stdin if x.strip()]"
Extract pages from a PDF file:
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -dFirstPage=34 -dLastPage=34 -sOutputFile=test2.pdf The-Cambridge-Handbook-of-Physics-Formulas.pdf
Display an image without a border:
feh --borderless /home/teresita/Downloads/48773.jpg &
Batch convert HTML to text:
for i in *.html; do lynx --dump "$i" > "${i%%.*}.txt";done
Build a list of words from a file:
cat gettysburg.txt | tr ' ' '\012'|tr '[A-Z]' '[a-z]' |sed "s/punct://g" |sort|uniq
Sort the Holy Bible by verse length with Perl:
perl -e 'print sort {length $b <=> length $a} <>' kjv.txt
Batch convert HTML to text:
for i in *.html; do lynx --dump "$i" > "${i%%.*}.txt";done
Use awk to print a count of words ending by letter:
awk 'length > 1{++a[substr(tolower($0), length)]}END{for (k in a) print a[k], k}' words.big | sort -n
Grab a stretch of unicode while inside #vim
:py3 import vim;vim.current.buffer.append(" ".join(chr(i) for i in range(945,970)))
Get a weather forecast at the console:
curl -s -L https curl wttr.in/seattle
Shuffle and rename the files in a directory of images
echo '#!/bin/bash' > files; chmod 744 files; ls -1 | shuf | nl -i1 -s' ' -nrz -w5 | awk '{print "mv " $2 " " $1 ".jpg"}' >> files ; ./files
Build thumbnails with the same basename from a directory of video files using ffmpegthumbnailer and bash:
for oldfile in *.mp4; do filename="${oldfile%.*}"; ffmpegthumbnailer -i "$filename.mp4" -o "$filename.jpg"; done
Calculate parallel resistance (or series capacitance) for any number of discrete components with Python
python3 -c "import sys; print(f'{1/sum(1/float(x) for x in sys.argv[1:]):.2f}')" 1800 2700 3300
Interplanetary mission velocity change and time of flight using Python (example used is outbound leg to Mars):
#!/usr/bin/env python3
import sys
from math import sqrt, pi, radians, sin
muP, muD, r1, rp1, muA, r2, rp2, inc = map(float, sys.argv[1:])
a = (r1 + r2) / 2.0
tof = pi * sqrt(a**3 / muP)
v1 = sqrt(muP / r1)
v2 = sqrt(muP / r2)
vt1 = sqrt(muP * (2.0 / r1 - 1.0 / a))
vt2 = sqrt(muP * (2.0 / r2 - 1.0 / a))
vinf1 = abs(vt1 - v1)
vinf2 = abs(v2 - vt2)
vc1 = sqrt(muD / rp1)
vp1 = sqrt(vinf1**2 + 2.0 * muD / rp1)
dv1 = vp1 - vc1
vc2 = sqrt(muA / rp2)
vp2 = sqrt(vinf2**2 + 2.0 * muA / rp2)
dv2 = vp2 - vc2
plane_speed = min(vt1, vt2)
plane = 2.0 * plane_speed * sin(radians(inc) / 2.0)
print(f"Transfer time {tof/86400:12.3f} days")
print(f"Injection Δv {dv1:12.6f} km/s")
print(f"Capture Δv {dv2:12.6f} km/s")
print()
print(f"Best case total Δv {dv1+dv2:12.6f} km/s")
print(f"Plane change {plane :12.6f} km/s")
print(f"Worst case total Δv{dv1+dv2+plane:12.6f} km/s")
Calculate a great circle route in kilometers:
#!/usr/bin/env python3 import sys from math import radians, degrees, sin, cos, sqrt, asin lat1, lon1, lat2, lon2 = map(float, sys.argv[1:5]) dLat = radians(lat2 - lat1) dLon = radians(lon2 - lon1) lat1 = radians(lat1) lat2 = radians(lat2) a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) print(6372.8 * c)
Nashville International Airport (BNA)
N 36°7.2', W 86°40.2' (36.12, -86.67)
Los Angeles International Airport (LAX)
N 33°56.4', W 118°24.0' (33.94, -118.40)
Find barycentric L1 and L2 Lagrange points from normalized mass ratio
#!/usr/bin/env python3
import sys
from scipy.optimize import brentq
R = float(sys.argv[1])
m1 = R / (R + 1.0)
m2 = 1.0 / (R + 1.0)
x1 = -m2
x2 = m1
def f(x):
r1 = abs(x - x1)
r2 = abs(x - x2)
return (
x
- m1 * (x - x1) / r1**3
- m2 * (x - x2) / r2**3
)
eps = 1e-12
L1 = brentq(f, x1 + eps, x2 - eps)
L2 = brentq(f, x2 + eps, x2 + 2.0)
r1 = x2 - L1
r2 = L2 - x2
print(f"Primary : {x1:.12f}")
print(f"Secondary : {x2:.12f}")
print(f"L1 : {L1:.12f}")
print(f"L2 : {L2:.12f}")
print(f"L1 offset : {r1:.12f}")
print(f"L2 offset : {r2:.12f}")
Python script for calculating the separation in AU between two stars in a binary system with known masses and period of revolution (the example uses Kruger 60 A/B):
#!/usr/bin/env python3
import math
import sys
m1 = float(sys.argv[1])
m2 = float(sys.argv[2])
P = float(sys.argv[3])
a = ((m1 + m2) * P**2) ** (1/3)
print(f"Total mass : {m1 + m2:.4f} M☉")
print(f"Orbital period : {P:.2f} years")
print(f"Separation : {a:.3f} AU")
With Python calculate the “comfort zone” of a star system based on visual magnitude and distance. Example is for Ran aka Epsilon Eridani (at Sol the comfort zone happens to be at 1 AU, what a coincidence!)
#!/usr/bin/env python3
import math
import sys
SUN_ABS_MAG = 4.83
LY_PER_PC = 3.26156
m = float(sys.argv[1])
d_ly = float(sys.argv[2])
d_pc = d_ly / LY_PER_PC
M = m - 5 * (math.log10(d_pc) - 1)
L = 10 ** ((SUN_ABS_MAG - M) / 2.5)
R = math.sqrt(L)
print(f"Distance : {d_ly:.3f} ly ({d_pc:.3f} pc)")
print(f"Absolute magnitude : {M:.3f}")
print(f"Luminosity : {L:.3f} L☉")
print(f"Goldilocks radius : {R:.3f} AU")