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!

Enable or disable access to specified web sites through ipfw

# cf. Example ipfw ruleset, http://codesnippets.joyent.com/posts/show/1267

# choose appropriate numbers for num1 & num2 according to your ipfw ruleset
function free_ipfw_rule_num() {
   declare -i num1=6701 num2=6799 lastipfwnum
   if [[ $(/usr/sbin/sysctl -n net.inet.ip.fw.autoinc_step) -ne 100 ]]; then 
      printf "%s\x21\n" "sysctl -n net.inet.ip.fw.autoinc_step is not set to 100"
      return 1
   fi
   lastipfwnum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/tail -n 2 | /usr/bin/head -n 1 | /usr/bin/awk '{print $1}')
   if [[ $num2 -ge $lastipfwnum ]]; then 
      printf "%s\x21\n" "${num2} is greater than or equal to ${lastipfwnum}"
      return 1
   fi
   while $(/usr/bin/sudo /sbin/ipfw show ${num1} &>/dev/null) ; do
      let "num1 += 1"
      if [[ $num1 -gt $num2 ]]; then num1=; break; return 1; fi
   done
   printf "%s\n" "${num1}"
   return 0
}


function opensite() {
   declare ipnum ipfwnum
   if [[ $# -eq 0 ]] || [[ $# -gt 2 ]]; then printf "%s\n" "Wrong number of arguments: $#"; return 1; fi
   ipnum=$(/usr/bin/dig +short ${1} 2>/dev/null | /usr/bin/tail -n 1; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${1}"
      return 1
   fi
   ipfwnum=$(free_ipfw_rule_num)
   if [[ $# -eq 1 ]]; then
      /usr/bin/sudo /sbin/ipfw -q add ${ipfwnum} allow { src-ip "${ipnum}" or dst-ip "${ipnum}" } keep-state
      printf "%s\n" "... opening ipfw rule no. ${ipfwnum} for internet access to site: ${1}"
   elif [[ $# -eq 2 ]]; then
      /usr/bin/sudo /sbin/ipfw -q add ${ipfwnum} allow { src-ip "${ipnum}" or dst-ip "${ipnum}" } dst-port "${2//[^[:digit:]]/}" keep-state
      printf "%s\n" "... opening ipfw rule no. ${ipfwnum} for internet access to site: ${1} on port ${2}"
   fi
   return 0
}


function closesite() {
   declare ipnum rulenum
   ipnum=$(/usr/bin/dig +short "${@}" 2>/dev/null | /usr/bin/tail -n 1; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${@}"
      return 1
   fi
   rulenum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/awk "/${ipnum}/ {print \$1}")
   if [[ -z "${rulenum}" ]]; then printf "%s\n" "No ipfw rule for: ${@}"; return 1; fi
   /usr/bin/sudo /sbin/ipfw -q delete ${rulenum}
   printf "%s\n%s\n" "... deleting ipfw rule no. ${rulenum//[[:cntrl:]]/ }" "... closing internet access to site: ${@}"
   return 0
}



# usage: 
# opensite [www.website.com] [optional: portnumber]
# closesite [www.website.com]

# example: http://wooledge.org:8000/BashFAQ

host wooledge.org
dig +short wooledge.org

opensite wooledge.org
opensite wooledge.org
opensite wooledge.org
opensite wooledge.org

closesite wooledge.org


opensite wooledge.org 8080
/usr/bin/sudo /sbin/ipfw show [rule no.]
closesite wooledge.org


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


man bash | less -p PIPESTATUS
help set | sed -E "s/(pipefail)/$(printf '\e[1m\\1\e[m')/"

set +o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 

set -o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 


# remove all non-numeric characters from a string
str="74n237k ab454c e 4 6 6g6fg6d66d"
echo ${#str}
echo ${str}
echo ${str//[^[:digit:]]/}

Command line audio players for Mac OS X

For information on how to install MacPorts see here and here.
# qtplay & mpg123

export PATH="/opt/local/bin:/opt/local/lib:/opt/local/include:/opt/local/man:${PATH}"
alias port=/opt/local/bin/port

port list | grep -i audio

port info qtplay 
port info mpg123

/usr/bin/sudo port -c install qtplay
/usr/bin/sudo port -c install mpg123

mpg123 file.MP3

qtplay file.MP3
qtplay 'http://file.mp3'
qtplay 'http://file.mov'     # http://www.apple.com/trailers/


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


# play, http://www.hieper.nl/html/play.html

export PATH="/usr/local/bin:${PATH}"

# create /usr/local/bin
/usr/bin/sudo /bin/mkdir -p /usr/local/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/local /usr/local/bin
/usr/bin/sudo /bin/chmod 0755 /usr/local /usr/local/bin

cd ~/Desktop
curl -L -O http://www.hieper.nl/downloads/play.dmg
hdiutil mount ~/Desktop/play.dmg
open -a Safari '/Volumes/play 1.3/readme.html'
/usr/bin/sudo /bin/cp -i '/Volumes/play 1.3/play' /usr/local/bin
ls -l /usr/local/bin/play
hdiutil unmount '/Volumes/play 1.3'

play ~/Music/Winterreise/Gute\ Nacht.mp3

# listen to the first 10 seconds of each Schubert song on your computer
mdfind "kMDItemComposer == Schubert" | play -vt 10


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


# afplay
# compile & install afplay and related command line audio tools (Mac OS X 10.4.11)
# requires Xcode, http://developer.apple.com/tools/xcode/index.html

ls -1 /usr/bin/af*     # Mac OS X 10.5
ls -1 /usr/bin/au* 

# Mac OS X 10.4
open /Developer/Examples/CoreAudio/Services/AudioFileTools/AudioFileTools.xcodeproj
# ... then just press "Build"

ls -l /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | nl
ls -1 /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | nl


#/usr/bin/find /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther -mindepth 1 | \
#     /usr/bin/xargs -I '{}' /usr/bin/sudo /bin/cp -i '{}' /usr/local/bin

/bin/ls -1 /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | \
     /usr/bin/xargs -I '{}' /usr/bin/sudo /bin/cp -i '{}' /usr/local/bin

ls -l /usr/local/bin/af*
ls -l /usr/local/bin/au*

afconvert
afinfo
afinterleave
afplay
afrecord
auprocess
auprofile


# background music
# cf. http://codesnippets.joyent.com/posts/show/1508
/usr/bin/screen -d -m afplay "/path/to/file.MP3"

kill -HUP $$
kill -HUP $PPID
killall -HUP Terminal


apropos audio
apropos sound

# set global Mac OS X sound output volume
# see http://osxutils.sourceforge.net
man setvolume   
setvolume 50

seticon - set icon of Mac OS X files

# See:
# http://osxutils.sourceforge.net
# http://www.sveinbjorn.org/osxutils_docs
# Mac OS X: Changing the Icon for a File Type, http://9stmaryrd.com/2008/05/16/158

cd ~/Desktop
curl -L -O http://surfnet.dl.sourceforge.net/sourceforge/osxutils/osxutils1.7.pkg.zip
unzip -qq osxutils1.7.pkg.zip
open -a Installer osxutils1.7.pkg

/bin/mkdir -p ~/Desktop/IconDir
/bin/cp /Library/Desktop\ Pictures/Nature{/Ladybug.jpg,'/Evening Reflections.jpg'} ~/Desktop/IconDir
/usr/bin/sips -i ~/Desktop/IconDir/*

/usr/bin/touch ~/Desktop/IconDir/testfile.txt
/bin/chmod 0777 ~/Desktop/IconDir/*

ls -l ~/Desktop/IconDir/*

open ~/Desktop/IconDir

# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/Ladybug.jpg ~/Desktop/IconDir/testfile.txt

# update file system changes of open Finder window
/usr/local/bin/wsupdate ~/Desktop/IconDir/testfile.txt
#/bin/mv ~/Desktop/IconDir{/testfile.txt,/tmp.txt} && /bin/mv ~/Desktop/IconDir{/tmp.txt,/testfile.txt} 


# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/'Evening Reflections'.jpg ~/Desktop/IconDir
/usr/local/bin/wsupdate ~/Desktop/IconDir

/bin/chmod -R 0755 ~/Desktop/IconDir
ls -al ~/Desktop/IconDir/*


# list files with resource forks
# cf. http://www.entropy.ch/blog/Mac+OS+X/2005/03/30/,
# http://forums.macosxhints.com/showthread.php?t=70224 and
# "can UNIX resolve OS X aliases?", http://forums.macosxhints.com/showthread.php?t=19960

cd ~/Desktop/IconDir
ls -1 | while IFS= read -r i; do if [[ -s ${i}/..namedfork/rsrc ]]; then ls -l "${i}/..namedfork/rsrc"; fi; done
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ls -l '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' sed -n -e 'l' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ruby -n -e 'p $_.to_s' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' strings '{}'/..namedfork/rsrc
#find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -delete

dotmacsyncclient

Sync with .Mac (MobileMe) from the command line

locate *dotmacsyncclient

/usr/bin/sudo /bin/ln -is /System/Library/CoreServices/dotmacsyncclient /usr/bin/dotmacsyncclient
dotmacsyncclient
dotmacsyncclient --version
dotmacsyncclient --listclients

Clear the terminal screen & scrollback buffer

# make sure access for assistive devices is enabled in the "Universal Access" System Preference
open /System/Library/PreferencePanes/UniversalAccessPref.prefPane

# cf. Terminal -> Scrollback -> Clear Scrollback [cmd-k]
function clear_screen() {
   /usr/bin/open -a Terminal
   /usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
   return 0
}

clear_screen


# you may use clear instead if scrollback is disabled in Terminal.app
defaults read com.apple.Terminal Scrollback
defaults write com.apple.Terminal Scrollback -string NO
#defaults write com.apple.Terminal Scrollback -string YES
kill -HUP $$
[cmd-n]
ls -l
clear

# in addition it may be useful to disable adding commands to the history list
#open -e ~/.bash_history
#set +o history   

Setting the CrashReporter mode to "Developer"

locate *CrashReporterPrefs.app
open /Developer/Applications/Utilities/CrashReporterPrefs.app

/usr/bin/defaults write com.apple.CrashReporter DialogType -string developer
#/usr/bin/defaults write com.apple.CrashReporter DialogType -string basic
#/usr/bin/defaults write com.apple.CrashReporter DialogType -string server

jQuery.innerWrap

The innerWrap method acts almost identical to the wrap method. The only real difference is that it wraps the contents of the element instead of the actual element. Authored by Brandon Aaron, author of the fantastic jQuery.Dimensions plugin.


jQuery.fn.innerWrap = function() {
	var a, args = arguments;
	return this.each(function() {
		if (!a)
			a = jQuery.clean(args, this.ownerDocument);
		// Clone the structure that we’re using to wrap
		var b = a[0].cloneNode(true),
		    c = b;
		// Find the deepest point in the wrap structure
		while ( b.firstChild )
			b = b.firstChild;
		// append the child nodes to the wrapper
		jQuery.each(this.childNodes, function(i, node) { 
			b.appendChild(node); 
		});
		jQuery(this)
			// clear the element
			.empty()
			// add the new wrapper with the previous child nodes appended
			.append(c);
	});
};


Usage:

The following example would effectively turn <h2>Title</h2> into <h2><span>Title</span></h2>

$(document).ready(function(){
      $(‘h2′).innerWrap(‘<span></span>’)
});


jQuery.emailProt

jQuery function to obfuscate email addresses.

jQuery.fn.emailProt = function(e) {
	$(this).each(function(){
		e = this.rel.replace('|','@');
		this.href = 'mailto:' + e;
		$(this).text(e);
	});
};


Usage:

$(document).ready(function(){
	$('.email').emailProt();	
});


<a rel="user|stylephreak.com" class="email"></a>

jQuery.attrToClass

Jquery function that appends a css class to all designated elements on a page by extracting a specific attribute from that element.

For instance, the example code below would change

<input type="submit" name="submit" value="Submit" />

to:

<input type="submit" name="submit" value="Submit" class="submit" />


jQuery.fn.attrToClass = function(attribute) {
	$(this).each(
		function(intIndex){
		    $(this).addClass($(this).attr(attribute));
	});
};

$(document).ready(function(){
        // designate the tag and the attribute to be extracted
	$("input").attrToClass("type");
});

jruby MySQL Database Configuration

Configuration for rails app using jdbc MySQL drivers on Mac OS X but should work for other platforms just as well but have not tested.
# install
sudo jruby -S gem install activerecord-jdbc-adapter activerecord-jdbcmysql-adapter 

# add to database.yml 
development:
  adapter: jdbcmysql
  encoding: utf8
  database: testapp_development
  username: root
  password:

# add to environment.rb just bellow require File.join(File.dirname(__FILE__), 'boot')
# this may only be needed for earlier releases
if RUBY_PLATFORM =~ /java/
    require 'rubygems'
    RAILS_CONNECTION_ADAPTERS = %w(jdbc)
end

# migrate
jruby -S rake db:migrate

# start testapp with glassfish (requires glassfish gem 'sudo jruby -S gem install glassfish')
# use at your own risk should not be sudo but for some reason getting errors with out about domain dir not being writable so did the risky but easy fix
sudo jruby -S glassfish_rails testapp