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

Disable right click

Disable Right Click - PAGE WIDE EFFECT

<tbody oncontextmenu="return false">

HTML stripper

// description of your code here

str = <<HTML_TEXT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
  <h1>Application error</h1>
  <p>Change this error message for exceptions thrown outside of an action (like 
in Dispatcher setups or broken Ruby code) in public/500.html</p>
</body>
</html>
HTML_TEXT

puts str.gsub(/<\/?[^>]*>/, "")

snippet

Download code snippets (http://textsnippets.com) from the command line and convert them to text files using man textutil (on Mac OS X 10.4).

Usage:
snippet 345
snippet 1268
snippet 1281



# $ cat $HOME/.bash_login

function snippet() {
   mkdir -p $HOME/Desktop/Snippets
   OPWD="$PWD"
   cd $HOME/Desktop/Snippets
   curl -L -O -s --max-time 25 http://textsnippets.com/posts/show/"$1" || exit 1
   file="$HOME/Desktop/Snippets/$(basename $_)"
   textutil -convert txt "$file"
   rm "$file"
   new_file="$file.txt"
   sed -i "" -e '1,5d' -e 's/.See related posts.//' "$new_file"  # delete first 5 lines of file
   sed -i "" -e :a -e '1,6!{P;N;D;};N;ba' "$new_file"            # delete last 6 lines of file
   cd "$OPWD"
   return 0
}


JavaScript Roll Overs

// JavaScript roll overs

<script type="text/javascript">
<!--
function MM_swapImgRestore() { //v3.0
 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
 var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
 if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
 d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
 if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
 for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
 if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
 if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
</script>

// html code
<a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image1','','2.png',1)"><img src="1.png" name="Image1" width="155" height="71" border="0" id="Image1" /></a>

MailMan listserve signup template

Simple template for adding a MailMan mailing list subscribe form to a page. Found on a mailing list somewhere a long time ago and cleaned up dramatically.

Note: I almost always just include the email and digest options, but I've included the whole spiel for completeness.


<h2>Join the XYZ list</h2>

<form method="post" action="SERVER/mailman/subscribe/LISTNAME">

  <p>
    Your E-mail address: <input type="text" name="email" size="30" value=""><br />
    Your Name (optional): <input type="text" name="fullname" size="30" value=""><br />
  </p>

  <p>You may enter a privacy password below. This provides only mild security, but should<br />
  prevent others from messing with your subscription. <b>Do not use a valuable password</b> as it<br />
  will occasionally be emailed back to you in cleartext.</p>

  <p>If you choose not to enter a password, one will be automatically generated for you, and it will<br />
  be sent to you once you've confirmed your subscription. You can always request a mail-back<br />
  of your password when you edit your personal options.</p>

  <p>
    Password choice: <input type="password" name="pw" size="15"><br />
    Confirm Password: <input type="password" name="pw-conf" size="15">
  </p>

  <p>
    Would you like to receive list mail batched in a daily digest? (You may choose NoMail after you join.)<br />
    <input type="radio" name="digest" value="0" checked> No 
    <input type="radio" name="digest" value="1"> Yes <br />
  </p>
  
  <p><input type="submit" name="email-button" value="Subscribe"></p>

</form>


HTML link regex

// use url group and ignore case (because of something like HREF)
// based on http://regexlib.com/REDetails.aspx?regexp_id=1048
href="(?<url>(((ht|f)tp(s?))\://)?((([a-zA-Z0-9_\-]{2,}\.)+[a-zA-Z]{2,})|((?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(\.?\d)\.)){4}))(:[a-zA-Z0-9]+)?(/[a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~]*)?)"

Standard CSS helpers

Some really common layout classes I use in almost every CSS file.

/********* helpers *********/
.floatRight { float: right; }
.floatLeft  { float: left; }
.right  { text-align: right; }
.left   { text-align: left; }
.center { text-align: center; }
.clear, .clearer { clear: both; }
.block  { display: block; }

PHP State-Array Generator

Simple array for HTML mockups.

function state_selection() {
	echo '<select name="state">';
		$states = array(
			'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
		);
		foreach ($states as $state_name) {
			echo '<option value="'.$state_name.'">'.$state_name.'</option>';
		}
	echo '</select>';
}
state_selection();

US States Pop-up

Simply a pop-up form element of all 50 US States. Save you creating your own.

            <select name="state">
              <option value="" selected="selected">Select a state...</option>
              <option value="AL">Alabama</option>
              <option value="AK">Alaska</option>
              <option value="AZ">Arizona</option>
              <option value="AR">Arkansas</option>
              <option value="CA">California</option>
              <option value="CO">Colorado</option>
              <option value="CT">Connecticut</option>
              <option value="DC">District of Columbia</option>
              <option value="DE">Delaware</option>
              <option value="FL">Florida</option>
              <option value="GA">Georgia</option>
              <option value="HI">Hawaii</option>
              <option value="ID">Idaho</option>
              <option value="IL">Illinois</option>
              <option value="IN">Indiana</option>
              <option value="IA">Iowa</option>
              <option value="KS">Kansas</option>
              <option value="KY">Kentucky</option>
              <option value="LA">Louisiana</option>
              <option value="ME">Maine</option>
              <option value="MD">Maryland</option>
              <option value="MA">Massachusetts</option>
              <option value="MI">Michigan</option>
              <option value="MN">Minnesota</option>
              <option value="MS">Mississippi</option>
              <option value="MO">Missouri</option>
              <option value="MT">Montana</option>
              <option value="NE">Nebraska</option>
              <option value="NV">Nevada</option>
              <option value="NH">New Hampshire</option>
              <option value="NJ">New Jersey</option>
              <option value="NM">New Mexico</option>
              <option value="NY">New York</option>
              <option value="NC">North Carolina</option>
              <option value="ND">North Dakota</option>
              <option value="OH">Ohio</option>
              <option value="OK">Oklahoma</option>
              <option value="OR">Oregon</option>
              <option value="PA">Pennsylvania</option>
              <option value="RI">Rhode Island</option>
              <option value="SC">South Carolina</option>
              <option value="SD">South Dakota</option>
              <option value="TN">Tennessee</option>
              <option value="TX">Texas</option>
              <option value="UT">Utah</option>
              <option value="VT">Vermont</option>
              <option value="VA">Virginia</option>
              <option value="WA">Washington</option>
              <option value="WV">West Virginia</option>
              <option value="WI">Wisconsin</option>
              <option value="WY">Wyoming</option>
            </select>