Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Snip - extract a named element from an html file

This is a primitive way of achieving the kind of data extraction that is more commonly associated with true XML for any reasonably modern html file (i.e. that it is well-formed and makes proper use of the id property). The purpose is mainly to get simple, yet fast and efficient text browsing, especially useful for quick look-ups and the like, e.g. dictionaries, thesauruses (thesauri?), encyclopedias etc. Since the data you're interested in is usually put into a specific element, text browsing is often greatly enhanced by extracting the element in question and discarding the rest. You run the script by specifying an element in the standard css way (element#id) and the file which is to be 'parsed', and the script responds by spitting out the element (and only that element) through html2text which does a really nice job of turning html code into legible console text.

#! /bin/bash

printhelp () {
echo "snip is a simple bash html cutter that works by extracting a specific element 
from an html file and feeding it to html2text. It presupposes wellformed html
and that you know the kind of element you want and it's id. It depends on wget,
grep, sed, cut and html2text.

Syntax:
snip <element  type>#<element id> <file to parsed>

Example:
snip div#bodyContent /tmp/index.html
"
exit
}

quitter () {
echo "Element id not found. Quitting."; exit
}

[ "$1" = "-h" -o "$1" = "--help" -o "$1" = "" ] && printhelp

elementtype="$(echo $1 | cut -d '#' -f 1)"
id="$(echo $1 | cut -d '#' -f 2)"
htmlfile="$2"
thebegin=$(grep -nioE "id=\"$id\"" $htmlfile | cut -d ':' -f 1)
# echo $thebegin
[ -n "$thebegin" ] || quitter

i=0
element=0
sed -n $thebegin,\$p $htmlfile | while read line; do
	elementbegincount="$(echo $line | grep -io "<$elementtype" | grep -c .)"
	elementendcount="$(echo $line | grep -io "</$elementtype" | grep -c .)"
	element=$(($element+$elementbegincount-$elementendcount))
	if [ "$element" -le 0 ]; then
		theend=$(($thebegin+$i))
		# echo $theend
		sed -n $thebegin,${theend}p $htmlfile | html2text -style pretty
		exit
	fi
	let i++
done


As an example of how the script can be put to use, here's my Wikipedia lookup (the script above is referred to as 'snip' here):

#! /bin/bash

useragent="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071619 Firefox/3.0.1"
if wget -q -U "$useragent" -O /tmp/wpfile "http://en.wikipedia.org/wiki/Special:Search?search=$*"; then
	clear
	echo "Page downloaded..."
	snip div#content /tmp/wpfile | less
else
	echo "No connection, sorry. Please try again."
fi

Interactive LAME-ifyer to convert WAV or AIFF files to MP3

I wrote this as a bash script because I wanted to accomplish two things that I didn't find in any of the prebuilt GUI tools I've seen for OS X: First, I wanted to enable accurate ReplayGain, and second, I wanted to avoid clipping in the output, which requires iteratively encoding to home in on the best scale factor to avoid clipping while keeping the audio otherwise at its highest fidelity. I present what I call semilame &#x2009; semiautomatic LAME:

#!/usr/local/bin/bash

SDIR=$PWD                       # Assumes xxx/Artist/Album hierarchy
TDIR=${PWD}/../../Out           # Assumes xxx/Out hierarchy
CUT="/usr/bin/cut"              # Set the correct path
LAME="/usr/local/bin/lame"      # Set the correct path

for fn in $(/bin/ls -1 *.aif *.aiff *.aifc 2>/dev/null); do
    clear   # Start with a clear screen, for goodness sake
    # First try to parse the filename; set other defaults appropriately
     FName="${fn/\.aifc/}"
     g_Track=$(echo $FName | $CUT - -f 1)
     g_Artist=${u_Artist:=$(echo $FName | $CUT - -f 2 | sed -e 's,_,\ ,g')}
     g_Title=$(echo $FName | $CUT - -f 3 | sed -e 's,_,\ ,g')
        # N.B. Expected format: TRACK÷Artist÷Title.aifc 
        #      with spaces converted to underscores.
        #      Album name is picked up from $PWD.
        #      Adjust to your needs!
     g_Album=${u_Album:=$(pwd | sed -E -e 's,(.*)/(.*)$,\2,')}
     g_Scale="1"
     if [[ $u_Qual ]]; then
        g_Qual=$u_Qual
        # Keep what we had from the last encoding
     else
        g_Qual="2"
     fi

     # Now prompt for user input for corrections
     BOLD="\033[1m"     # Set to "" if your term doesn't support bold
     NORM="\033[0m"     # Set to "" if your term doesn't support bold

     echo -e "${BOLD}FILENAME: ${NORM}====== « ${BOLD}$fn${NORM} »\n"
     echo -e "${BOLD}Track:           ${NORM}[${BOLD}${g_Track}${NORM}]: \c"
          read u_Track
     echo -e "${BOLD}Total Tracks:    ${NORM}[${BOLD}${g_Total}${NORM}]: \c"
          read u_Total
     echo -e "${BOLD}Artist:          ${NORM}[${BOLD}${g_Artist}${NORM}]: \c"
          read u_Artist
     echo -e "${BOLD}Title:           ${NORM}[${BOLD}${g_Title}${NORM}]: \c"
          read u_Title
     echo -e "${BOLD}Album:           ${NORM}[${BOLD}${g_Album}${NORM}]: \c"
          read u_Album
     echo -e "${BOLD}Year:            ${NORM}[${BOLD}${g_Year}${NORM}]: \c"
          read u_Year
     echo -e "${BOLD}Quality Level:   ${NORM}[${BOLD}${g_Qual}${NORM}]: \c"
        read u_Qual
         # Compare u_* values with g_* values
     if [[ -z $u_Track ]]; then
          u_Track=$g_Track
     fi
     if [[ -z $u_Total ]]; then
          u_Total=$g_Total
     elif [[ -z $g_Total ]]; then
          g_Total=$u_Total
     fi
     if [[ -z $u_Artist ]]; then
          u_Artist=$g_Artist
     fi
     if [[ -z $u_Title ]]; then
          u_Title=$g_Title
     fi
     if [[ -z $u_Album ]]; then
          u_Album=$g_Album
     fi
     if [[ -z $u_Year ]]; then
          u_Year=$g_Year
     elif [[ -z $g_Year ]]; then 
          g_Year=$u_Year
     fi
     if [[ -z $u_Qual ]]; then
          u_Qual=$g_Qual
     elif [[ -z $g_Qual ]]; then
          g_Qual=$u_Qual
     fi

     u_Scale=$g_Scale
     # while loop = each interation through the track
     while [[ $u_Scale != "0" ]]; do
          echo -e "${BOLD}Scale:           ${NORM}[${BOLD}${g_Scale}${NORM}]: \c"
              read u_Scale

          if [[ $u_Scale == "0" ]]; then
              g_Scale=1
              continue
          fi
          if [[ -z $u_Scale ]]; then
              u_Scale=$g_Scale
          elif [[ -z $g_Scale ]]; then
              g_Scale=$u_Scale
          fi
          g_Scale=$u_Scale
     
          # At this point, the real values should all be in the u_* variables. 
          # The g_* variables are simply placeholders for the next round 
          # through the loop, for the ones that aren't auto guessed.
     
          # Construct the lame command and run it. Adjust to your liking.
          LAMEOPTS="--replaygain-accurate
--clipdetect
--big-endian
--nohist
--id3v2-only
--vbr-new
-V
$u_Qual
-q
$u_Qual
--temporal-masking
1
--ignore-tag-errors
"

# LAMEARGS is constructed separately because it changes with each file.

         LAMEARGS="--tt
$u_Title
--tl
$u_Album"
        if [[ -n $u_Artist ]]; then
            LAMEARGS="$LAMEARGS
--ta
${u_Artist}"
        fi
         if [[ -n $u_Total ]]; then
              LAMEARGS="$LAMEARGS
--tn
${u_Track}/${u_Total}"
         else
              LAMEARGS="$LAMEARGS
--tn
${u_Track}"
         fi
         if [[ -n $u_Year ]]; then
              LAMEARGS="$LAMEARGS
--ty
$u_Year"
         fi
        if [[ -n $u_Scale ]]; then
            LAMEARGS="$LAMEARGS
--scale
$u_Scale"
        fi  
        OLDIFS=$IFS
        IFS='
'
        LAMELINE="${LAME}
${LAMEOPTS}
${LAMEARGS}
$fn
${TDIR}/${fn/aifc/mp3}"
        $LAMELINE
        
        # Restore IFS
        IFS=$OLDIFS
        
        echo -e "Set Scale to ${BOLD}0${NORM} to continue.\n"
    done 
done

Webdav upload utility

Command line utility to upload files to a webdav server.

Requires net_digest_auth.rb (snippet)

NB: Does not handle MKCOL, so the directory where you place the file must already exist.

Usage

$ ruby upload.rb cert.yml source destination


where cert.yml is a file of the form

username: USERNAME
password: PASSWORD


source is the path to the file to upload

destination is the URL of a directory on a webdav server to upload to.

# upload.rb
# Command line webdav upload script. Based off of 
# http://theexciter.com/articles/bingo

require 'net_digest_auth'
require 'yaml'
require 'uri'

abort("Usage: #{$0} <credentials.yml> <src> <dst> ") unless ARGV.size==3

auth = YAML.load_file(ARGV[0])
username = auth['username']
password = auth['password']

src = ARGV[1]
dst = ARGV[2]

if File.exists?(src)
  url = URI.parse(dst)
  Net::HTTP.start(url.host) do |http|
    res = http.put(url.request_uri, 'hello') # try putting something so
                                             # the server will return a
                                             # www-authenticate header
    req = Net::HTTP::Put.new("#{url.path}#{File.basename(src)}")
    req.digest_auth(username, password, res)
    response = http.request(req, File.open(src).read)
    puts response.code + " " + response.message
  end
else
  puts "No such file #{src.inspect}"
end

sort ip addresses


just alias this to something like ipsort
sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

disable built-in isight

sudo chmod a-rx /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Con
tents/MacOS/QuickTimeUSBVDCDigitizer

and to restore:
sudo chmod a+rx /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Con
tents/MacOS/QuickTimeUSBVDCDigitizer

fast user switch from the command line

#!/bin/sh  
MENUEXTRAS="/System/Library/CoreServices/Menu Extras"
CGSESSION="$MENUEXTRAS/User.menu/Contents/Resources/CGSession"
if [[ -z $1 ]]; then
    "$CGSESSION" -suspend
else  
    USERID=`id -u $1`;
    if [[ -z $USERID ]]; then
        exit -1;
    fi;
    "$CGSESSION" -switchToUserID $USERID
fi;

power off the displays

this really powers off the displays, unlike other solutions which just put them to the dimmest setting
#!/bin/sh
  
MAGIC_NUMBER=107374183
PMSET=/usr/bin/pmset
GREP=/usr/bin/grep
AWK=/usr/bin/awk
SLEEP=/bin/sleep
    
$PMSET force -a displaysleep $MAGIC_NUMBER
$SLEEP 1
$PMSET force -a displaysleep `$PMSET -g | $GREP displaysleep | $AWK '{print $2}'`
$SLEEP 1

/etc/sysctl.conf

These are my settings for sysctl.conf
# Max number of incoming connections in queue
kern.ipc.somaxconn=512
# Maximum number of processes
kern.maxproc=2048
kern.maxprocperuid=1024
# Network buffers; 2K each; check current usage with `netstat -m`
kern.ipc.nmbclusters=2048
kern.ipc.maxsockets=2048
# Maximum segment size; other possible values are 1452 and 1460
net.inet.tcp.mssdflt=1440
# Window scaling is only necessary if buffers > 64K
net.inet.tcp.rfc1323=0
# Increase buffer sizes
kern.ipc.maxsockbuf=131070
net.inet.tcp.sendspace=32768
net.inet.tcp.recvspace=65535
net.inet.udp.recvspace=65535
net.inet.udp.maxdgram=57344
net.inet.raw.recvspace=65535
# Max number of ICMP "Unreachable" and also TCP RST packets per second
net.inet.icmp.icmplim=50
# Stop redirects
net.inet.icmp.drop_redirect=1
net.inet.icmp.log_redirect=1
net.inet.ip.redirect=0
# Stop source routing
net.inet.ip.sourceroute=0
net.inet.ip.accept_sourceroute=0
# Stop broadcast ECHO response
net.inet.icmp.bmcastecho=0
# Stop other broadcast probes
net.inet.icmp.maskrepl=0
# Cuts down on the number of tiny packets
net.inet.tcp.delayed_ack=1
# Turn off forwarding/routing
net.inet.ip.forwarding=0
# Defend against sequence number attacks
net.inet.tcp.strict_rfc1948=1
# Defend agains stealth simple port scans
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2
# Expire dead connections
net.inet.tcp.always_keepalive=1
net.inet.tcp.keepintvl: 1500
net.inet.tcp.keepinit: 3000
# Verbose firewall logging
net.inet.ip.fw.verbose=1
net.inet.ip.fw.verbose_limit=65535
# Prevent core dumps
kern.coredump=0

Create an ecrypted sparse disk image to store private stuff

hdiutil create Private -type SPARSE -encryption -fs HFS+J -volname Private

If you want it to be case-sensitive AND journaled, you can't simply use HFSX+J, you have to use HFSX, then issue this command:
diskutil enableJournal /Volumes/Private

Lock the keychain when idle

Lock the keychain when system sleeps or is idle for 10 minutes.
security set-keychain-settings -l -u -t 600