DZone 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

Snippets

  • submit to reddit

Recent Snippets

                    
var MANY_ZEROS = "000000000000000000";

function leftZeroPad(val, minLength) {
    if (typeof(val) != "string")
        val = String(val);
    return (MANY_ZEROS.substring(0, minLength - val.length)) + val;
}

leftZeroPad(3, 2) ==> "03"
                
                    Use this class to parse RSS at a specific URL.

require 'rexml/document'
class ParseRss
	def initialize(url)
		@url = url
	end
	
	def parse
		@content = Net::HTTP.get(URI.parse(@url))
		xml = REXML::Document.new(@content)
		data = {}
		data['title'] = xml.root.elements['channel/title'].text
		data['home_url'] = xml.root.elements['channel/link'].text
		data['rss_url'] = @url
		data['items'] = []
		xml.elements.each('//item') do |item|
			it = {}
			it['title'] = item.elements['title'].text
			it['link'] = item.elements['link'].text
			it['description'] = item.elements['description'].text
			if item.elements['dc:creator']
				it['author'] = item.elements['dc:creator'].text
			end
			if item.elements['dc:date']
				it['publication_date'] = item.elements['dc:date'].text
			elsif item.elements['pubDate']
				it['publication_date'] = item.elements['pubDate'].text
			end
			data['items'] << it
		end
		data
	end
end

Used like so: ParseRss.new('http://someurl.com/rss').parse(). It returns a hash full of nice RSS goodness that you can use as you wish                 
                    A very simple, if not particularly portable or fast, quest for selecting a set of random rows from MySQL.
SELECT * from my_table ORDER BY RAND() LIMIT 25
I use this a lot when testing.                
                    Opens pydoc in your browser.  If pydoc has not been started it starts it for you.

#!/bin/bash

PYDOC=`which pydoc`
if [ ! -x ${PYDOC} ]
then
    echo "could not find executable pydoc (tried: ${PYDOC})"
    exit 1
fi

# passthru ...
if [ $# -gt 0 ]
then
    ${PYDOC} $@
    exit $?
fi

#--------------------------------------
# or else... start it up automagically :

PYDOC_PORT=9000
PYDOC_SERVER=http://localhost:${PYDOC_PORT}/
running=0
pydoc_pses=0

function browse_docs()
{
    open ${PYDOC_SERVER}
}

for ps in `ps ax | grep "${PYDOC}" | awk '{ print $1 }'`
do
    let pydoc_pses++
done

if [ $pydoc_pses -ge 2 ]
then
    browse_docs
else
    ${PYDOC} -p ${PYDOC_PORT} &
    until `curl -o /dev/null ${PYDOC_SERVER} &>/dev/null`
    do
        echo "waiting for pydoc server ..."
        sleep 2
    done
    browse_docs
fi
exit 0
                
                    
screencapture -S /tmp/screengrab.pdf ; sips -s format png /tmp/screengrab.pdf --out /tmp/screengrab.png; open /tmp/screengrab.png
                
                    These routes allow URLs like tags/whatever/whatever/whatever to put 'whatever', 'whatever', and 'whatever' into the @params[:tags] array, etc.

map.connect '', :controller => "posts", :action => "index"
map.connect 'tags/*tags', :controller => 'tag', :action => 'show'
map.connect 'user/:user', :controller => 'user', :action => 'show'
map.connect 'user/:user/tags/*tags', :controller => 'tag', :action => 'show'

                
                    With this code, create "next generation" bookmarklets.

The good points are that :
- the code is remotely loaded (so updatable and more simply testable)
- you have no length limitation 
- you can dispatch the code in various libaries

To disable the browser cache, we've added a random parameter in the the last javascript url. For performance, it's better to not disable the cache but it's very useful when testing.


baseurl = 'http://example.com/bookmarklet/';

var scripts = new Array(

baseurl + 'date.js',
baseurl + 'encoding.js',
baseurl + 'http.js',
baseurl + 'bookmarklet.js?x=' + Math.floor(Math.random() * 9999)

);

for (i=0;i<scripts.length;i++) {

var x = document.getElementsByTagName('head').item(0);
var o = document.createElement('script');

if (typeof o != 'object') o = document.standardCreateElement('script');
o.setAttribute('src', scripts[i] );
o.setAttribute('type','text/javascript');
x.appendChild(o);

}

Past the code above in a bookmarklet crunchinator to generate the bookmarklet. http://ted.mielczarek.org/code/mozilla/bookmarklet.html

Not fully tested. It may have some issues.                
                    
/*
 * create a new DOM element with (optionally) specified className, CSS and text/html content
 * if text contains any markup, it's used as innerHTML value - else a child text node is attached
 * if there's also a parent node given, the new element will be appended as child node
 */
function createStyledElement(tag, parent, cls, css, txt) {
    var el = document.createElement(tag);
    if(cls) el.className = cls;
    if(css) for(var s in css) el.style[s]=css[s];
    if(txt) {
        if (txt.indexOf('<')!=-1) el.innerHTML=txt;
        else el.appendChild(document.createTextNode(txt));
    }
    if(parent) parent.appendChild(el);
    return el;
}

// usage example...
// 1st define some style params
var style1={
    background: '#def',
    color: '#f00',
    padding: '0.5em',
    border: '1px black dotted'
};

createStyledElement(
  'div',
  document.getElementsByTagName('body').item(0),
  null,
  style1,
  'hello <em>world</em>!'
);
                
                    Using SnippetCompiler (http://www.sliver.com) a lot, I needed a template which has the nUnit components started... Here it is.

using System;
using System.Collections;
using NUnit.Framework;

#region entry point
public class EntryClass
{
	public static void Main()
	{
		NewClass t = new NewClass();
	}

}
#endregion entry point

// To test, select Build|Build To File... then point nunit's guii at the resultant dll


// Class we will build up for testing
public class NewClass
{
    // Sample Method which is tested
    public int MyMethod(int firstNumber, int secondNumber)
    {
        return firstNumber + secondNumber;
    }
}


// Class that does the nunit testing ([TestFixture] tells nunit it's the test class)
[TestFixture]
public class MyNewClassTestClass
{    
        // Method for testing the method in the class above ([Test] tells nunit this is a test method)
		[Test]
		public void MyMethodTest() 
		{
            // create an instance of the class
			NewClass obj_newClass = new NewClass();
            
            // Verify assertion
			Assertion.Assert(obj_newClass.MyMethod(10, 20) == 30);
		}    

} 

                
                    This RegEx should return all the Wiki Words (i.e. any word in Camel Case):

[^A-Za-z]*([A-Z][a-z]+[A-Z][a-z]+([A-Z][a-z]+)*)[^A-Za-z]*