Welcome

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!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

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

Password request dialog from the command line with AppleScript

unset -v input

#input="$(/usr/bin/osascript <<-'__HEREDOC__'
input="$(/usr/bin/osascript 2>/dev/null <<-'__HEREDOC__'
   with timeout of 300 seconds
      tell application "Finder"
--      tell application "System Events"
         activate
         set Input to display dialog "Please enter your password:" \
            with title "Password" \
            with icon caution \
            default answer "" \
            buttons {"Cancel", "OK"} \
            default button 2 \
            with hidden answer \
            giving up after 295
         return text returned of Input as string
      end tell
   end timeout
__HEREDOC__
)"

printf "%s\n" "${input}"


open -a 'Script Editor'

# copy & paste the following snippet into Script Editor 

with timeout of 300 seconds
	tell application "Finder"
		activate
		set Input to display dialog "Please enter your password:" with title "Password" with icon caution default answer "" buttons {"Cancel", "OK"} default button 2 giving up after 295 with hidden answer
		return text returned of Input as string
	end tell
end timeout


#---------------------------------------


unset -v input name
#export name="$(/usr/bin/logname)"
export name="$(/usr/bin/whoami)"

input="$(/usr/bin/osascript 2>/dev/null <<-__HEREDOC__
   with timeout of 300 seconds
      tell application "Finder"
--      tell application "System Events"
         activate
         set my_name to "${name}"
         set my_pass to display dialog "Enter password for " & quoted form of my_name \
            with title "Login Window" \
            with icon note \
            default answer "" \
            buttons {"Cancel", "OK"} \
            default button 2 \
            with hidden answer \
            giving up after 295
            return text returned of my_pass as string
      end tell
   end timeout
__HEREDOC__
)"


printf "%s\n" "${input}"

Login window from the command line with Pashua

export PATH="/usr/bin:/bin:/usr/sbin:/sbin"
export IFS=$' \t\n'

mkdir -p ~/Applications

ls -ld ~/Applications
stat -x ~/Applications

cd ~/Applications
curl -L -O http://www.bluem.net/files/Pashua.dmg
hdiutil mount Pashua.dmg
cp -R /Volumes/Pashua ~/Applications/Pashua
hdiutil unmount /Volumes/Pashua

cd ~/Applications/Pashua/Examples
cp -p example.sh example.sh.orig   # backup


# some in-place text editing commands to modify ~/Applications/Pashua/Examples/example.sh
# cf. http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed

export FILE="${HOME}/Applications/Pashua/Examples/example.sh"

# replace #!/bin/sh with #!/bin/bash
/bin/ed -s "${FILE}" <<< $'1,1s|bin/sh|bin/bash|\nw'

# to set the encoding to UTF-8 we add: set -- test utf8
/bin/ed -s "${FILE}" <<< $',s|\(.*Manage encoding.*\)|set -- test utf8 # set $2 to "utf8"\\\n\\\n\\1|\nw'

# delete all lines after first regex match /conf="/
/bin/ed -s "${FILE}" <<< $'/conf="/;$d\nw'


# add the following configuration

/bin/cat >> "${FILE}" <<-'EOF'

conf="

# Set transparency: 0 is transparent, 1 is opaque
*.transparency=0.95

# Set window title
*.title = Login Window

*.x = 550
*.y = 300
*.autoclosetime = 300

name.type = textfield
name.label = Please enter your name:
name.width = 280
name.x = 0
name.y = 110

password.type = password
password.label = Please enter your password:
password.width = 280
password.x = 0          
password.y = 45        

# Add a cancel button with default label
cb.type = cancelbutton

";   # end conf


pashua_run "$conf"
#pashua_run "$conf" "utf8"   # alternative to "set -- test utf8" above


if [[ ${cb} -ne 0 ]]; then echo 'Login cancelled!'; exit 1; fi

printf "%s\n" "name = ${name}"

printf "%s\n" "${name}" | ruby -n -e 'p $_.to_s'

# the following command requires #!/bin/bash
# cf. http://www.lugbz.org/pipermail/lugbz-list/2006-December/016360.html
/bin/ed -s <((printf "%s\n" "${name}")) <<< $',l'   

printf "%s\n" "password = ${password}"
printf "%s\n" "cb = ${cb}"

#printf "%s\n" "${password}" | /usr/bin/sudo -S /bin/ls | /usr/bin/head -n 5

/sbin/md5 -qs "${password}"

EOF


# run the script
~/Applications/Pashua/Examples/example.sh

mycmds

help set
set -xv

#echo $-
#shopt -u
#shopt -s
#shopt -s | grep expand_aliases
#shopt -q expand_aliases; echo $?
#help shopt
#shopt -p
#shopt -s expand_aliases   

unalias mycmds1 mycmds2 mycmds3  2>/dev/null
alias mycmds1="declare -F | /usr/bin/awk '{print \$NF}' | /usr/bin/sort"
alias mycmds2="declare -F | /usr/bin/awk '{print $NF}' | /usr/bin/sort"
alias mycmds3='declare -F | /usr/bin/awk "{print $NF}" | /usr/bin/sort'

mycmds1
mycmds2
mycmds3


alias mycmds="alias -p | /usr/bin/awk -F= '{print \$1}' | /usr/bin/sort; \
              declare -F | /usr/bin/awk '{print \$NF }' | /usr/bin/sort"

mycmds

Find solved forum threads with Google

A method of using google which allows for fast and accurate searching of forums and other websites for solved threads matching your criteria.

Just so everyone is aware, I just put the tag "hack" in the tag list so that those looking for google hacks might stumble on this. We'll see how that works out.
http://www.google.com/search?q=intitle:solved+intext:nvidia+5200
// This will find tons of solved issues regarding the NVidia 5200 graphics card

http://www.google.com/search?q=intitle:solved+intext:nvidia+5200+"no+screens+found"
// This should help you fix a problem with "No screens found" on an NVidia 5200 card

Lispify Ruby

// description of your code here

   require 'rubygems'  
   require 'parse_tree'  
   require 'ruby2ruby'  
     
   Sexp.class_eval do  
     def unbox  
       if length == 1  
         self.first  
       else  
         self  
       end  
     end  
   end  
     
   class Lispify < SexpProcessor  
     def initialize  
       super  
       self.auto_shift_type = true  
       self.require_empty   = false  
     end  
     
     def process_vcall(expr)  
       s(expr.first)  
     end  
     
     def process_call(expr)  
       expr = Sexp.from_array(expr)  
     
       first  = process(expr[0]).unbox  
       second = process(expr[2]).unbox  
     
       s(expr[1], first, second)  
     end  
     
     def process_array(expr)  
       process(expr.first)  
     end  
   end  


Which results in:


>> Lispify.new.process(ParseTree.translate(%q{ x + x * x - x }))
=> s(:-, s(:+, :x, s(:*, :x, :x)), :x)

Cross-platform file encryption with TrueCrypt

# first download & install the free, open-source TrueCrypt program from http://www.truecrypt.org/downloads.php

ls -ld /Applications/TrueCrypt.app
ls -l /Applications/TrueCrypt.app/Contents/MacOS/TrueCrypt

open -a TrueCrypt

1. click "Create Volume"
2. TrueCrypt Volume Creation Wizard: select "Create a file container"
3. click Next
4. Volume Type: select "Standard TrueCrypt volume"
5. click Next
6. Volume Location: click "Select File ..."
7. navigate to ~/Desktop with the file browser, then click "New Folder"
8. enter "Name of new folder": TrueCrypt, then click Create
9. enter in "Save As": MyTrueCrypt, then click Save
10. Volume Location: the "Select File ..." field should contain /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt
11. click Next
12. Encryption Options:
    Encryption Algorithm: AES
    Hash Algorithm: RIPEMD-160
13. click Next
14. Volume Size: 3 MB
15. click Next
16. Volume Password: *********************  (more than 20 characters recommended)
17. click Next
18. Format Options: Filesystem Options: Filesystem type: select FAT
19. click Next
20. Volume Format: Move your mouse as randomly as possible within this window
21. click Format
22. "The TrueCrypt volume has been successfully created."
23. click OK
24. Volume Created
25. click Exit
26. click Close (to quit TrueCrypt)

open -a TrueCrypt

1. click "Select File ..."
2. navigate with the file browser to /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt
3. click Open
4. click Mount and enter your password: *********************
5. double-click: Slot 1 : Volume: /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt  Size: ...

touch '/Volumes/NO NAME/file.txt'    # or copy a text file to '/Volumes/NO NAME'
echo 'This is a test!' >> "$_"
cat '/Volumes/NO NAME/file.txt'
ls -l "$_"
# hdiutil unmount '/Volumes/NO NAME'

6. click Dismount
7. click Close


# References:
# Beginner's Tutorial, http://www.truecrypt.org/docs/?s=tutorial
# http://www.truecrypt.org/faq.php
# http://blogs.oreilly.com/digitalmedia/2008/03/truecrypt-51-open-source-file.html
# http://www.askstudent.com/security/a-step-by-step-guide-on-encrypting-files-using-truecrypt/
# http://techvj.blogspot.com/2007/03/secure-email-attachments-with-truecrypt.html
# http://www.osxcrypt.org

television

Shows to follow:
Battlestar Galactica
The Office
Weeds
Dollhouse
Dr. Horrible's Sing-Along Blog
How I Met Your Mother
Grey's Anatomy
Diggnation?
Totally Rad Show
House M.D.
The Soup
The Cleaner
Gossip Girl
Heroes
Kitchen Nightmares
Fringe

To Catch up on and decide if I wanna follow:
Lost
Eureka
Doctor Who
Supernatural
Jericho
It's Always Sunny in Philadelphia
Hell's Kitchen
Dexter
The Sarah Connor Chronicles
Torchwood
Rescue Me?
The Big Bang Theory?
My Boys?
Chuck?
Kyle XY?
Bones?

movies

Wanted
Hellboy II
21
Indiana Jones and The Kingdom of the Crystal Skull
The Chronicles of Narnia: Prince Caspian
Iron Man
The Incredible Hulk
WALL-E
The Happening
Hancock
Cloverfield
Forgetting Sarah Marshall
27 Dresses
Harold and Kumar Escape from Guantanamo Bay
88 Minutes
The Spiderwick Chronicles
Presto
An American Crime
Young People Fucking
Charlie Bartlett
The Other Boleyn Girl
--
3:10 to Yuma
Sunshine
Enchanted
Stardust
Wristcutters
Goodfellas
Cheaters
It's a Boy/Girl Thing
Spun
28 Days Later
28 Weeks Later
Castaway
The Golden Compass
Scoop
50 First Dates
The Shining
Indiana Jones and the Raiders of the Lost Ark
Alpha Dog
I'm Reed Fish
The Ballad of Jack and Rose
Cashback
Helvetica
There Will Be Blood
Into the Wild
The Dangerous Lives of Altar Boys
My Blueberry Nights
Penelope
Starter for 10
Lucky Number Slevin
The Nanny Diaries
In Good Company
Dedication

ipfwdump, ipfwto & ipfwfrom

Three basic Bash functions to get some current ipfw ruleset information.

unset -f ipfwfrom
function ipfwfrom() {

   declare sudo=/usr/bin/sudo ipfw=/sbin/ipfw
   declare IF CIF ipnum rule url num

   OPATH=$PATH; OIFS=$IFS
   export PATH="/usr/bin:/bin:/usr/sbin:/sbin"; export IFS=$' \t\n'

   /usr/sbin/ipconfig waitall

   IF="en0"
   CIF="$(/sbin/route -n get default | grep interface | awk '{ print $NF }')"   # current default interface
   #CIF="$(/usr/sbin/netstat -rn | grep default | awk '{ print $NF }')"          # current default interface

   if [[ "$1" = "-n" ]]; then    # print IP numbers

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1, $7 }'  | sort -n | uniq | while read -d $'\n' line; do
         ipnum="${line##* }"
         rule="$(/usr/bin/sudo /sbin/ipfw list ${line%% *} )"
         printf "%-27s %s\n" "${ipnum}" "${rule}"
      done

   else

      if [[ "${IF}" != "${CIF}" ]]; then echo "No internet connection!"; return 1; fi

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1, $7 }'  | sort -n | uniq | while read -d $'\n' line; do
         ipnum="${line##* }"
         url="$(/usr/bin/dig +short +time=3 +tries=2 -x ${ipnum} | head -n 1)"
         if [[ -z "${url}" ]]; then url=${ipnum}; fi
         rule="$(/usr/bin/sudo /sbin/ipfw list ${line%% *} )"
         printf "%-27s %-45s %s\n" "${ipnum}" "${url}" "${rule}"
      done

   fi

   export PATH=$OPATH; export IFS=$OIFS

   return 0
}
export -f ipfwfrom



unset -f ipfwto
function ipfwto() { 

   declare sudo=/usr/bin/sudo ipfw=/sbin/ipfw
   declare IF CIF ipnum rule url num

   OPATH=$PATH; OIFS=$IFS
   export PATH="/usr/bin:/bin:/usr/sbin:/sbin"; export IFS=$' \t\n'

   /usr/sbin/ipconfig waitall

   IF="en0"
   CIF="$(/sbin/route -n get default | grep interface | awk '{ print $NF }')"   # current default interface

   if [[ "$1" = "-n" ]]; then    # print IP numbers

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1, $10 }'  | sort -n | uniq | while read -d $'\n' line; do
         ipnum="${line##* }"
         rule="$(/usr/bin/sudo /sbin/ipfw list ${line%% *} )"
         printf "%-27s %s\n" "${ipnum}" "${rule}"
      done

   else

      if [[ "${IF}" != "${CIF}" ]]; then echo "No internet connection!"; return 1; fi

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1, $10 }'  | sort -n | uniq | while read -d $'\n' line; do
         ipnum="${line##* }"
         url="$(/usr/bin/dig +short +time=3 +tries=2 -x ${ipnum} | head -n 1)"
         if [[ -z "${url}" ]]; then url=${ipnum}; fi
         rule="$(/usr/bin/sudo /sbin/ipfw list ${line%% *} )"
         printf "%-27s %-45s %s\n" "${ipnum}" "${url}" "${rule}"
      done

   fi

   export PATH=$OPATH; export IFS=$OIFS

   return 0
}
export -f ipfwto



unset -f ipfwdump
function ipfwdump() { 

   declare sudo=/usr/bin/sudo ipfw=/sbin/ipfw
   declare IF CIF ipnum rule url num ipfrom ipto ip1 ip2

   OPATH=$PATH; OIFS=$IFS
   export PATH="/usr/bin:/bin:/usr/sbin:/sbin"; export IFS=$' \t\n'

   /usr/sbin/ipconfig waitall

   IF="en0"
   CIF="$(/sbin/route -n get default | grep interface | awk '{ print $NF }')"   # current default interface

   if [[ "$1" = "-n" ]]; then    # print IP numbers

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1,$7,$10 }' | sort -n | uniq | while read -d $'\n' line; do
         read num ipfrom ipto <<< "${line}"
         rule="$(/usr/bin/sudo /sbin/ipfw list ${num} )"
         printf "%-45s %s\n" "${ipfrom}  ->  ${ipto}" "${rule}"
      done

   else

      if [[ "${IF}" != "${CIF}" ]]; then echo "No internet connection!"; return 1; fi

      $sudo $ipfw -de list | awk '/ \(.*\) / { print $1,$7,$10 }' | sort -n | uniq | while read -d $'\n' line; do
         read num ipfrom ipto <<< "${line}"
         rule="$(/usr/bin/sudo /sbin/ipfw list ${num})"
         ip1="$(/usr/bin/dig +short +time=3 +tries=2 -x ${ipfrom} | head -n 1)"
         ip2="$(/usr/bin/dig +short +time=3 +tries=2 -x ${ipto} | head -n 1)"
         if [[ -z "${ip1}" ]]; then ip1=${ipfrom}; fi
         if [[ -z "${ip2}" ]]; then ip2=${ipto}; fi
         printf "%-65s %s\n" "${ip1}  ->  ${ip2}" "${rule}"
      done
   fi


   export PATH=$OPATH; export IFS=$OIFS

   return 0
}

export -f ipfwdump



ipfwdump
ipfwdump -n
ipfwdump -n | grep 7400
ipfwdump -n | grep allow
ipfwdump -n | grep deny

ipfwto
ipfwto -n | grep deny
ipfwfrom -n
ipfwfrom | grep allow