Never been to DZone Snippets 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

« Newer Snippets
Older Snippets »
Showing 11-20 of 80 total

parameterized layouts as "page classes":

// within application controller:

  # layout selector
  def simple_page
    @show_fader = true
    return "application"
  end 

  # layout selector
  def complex_page
    @show_fader = false
    return "application"
  end 



// from within an individual page layout
 layout :simple_page


// finally, from within layout:
 show_fader: <%= @show_fader %>

get current action or controller from within a view

<%= controller.action_name %> 
or 
<%= controller.controller_name %>

SCGI connector (Java)

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.HashMap;

/**
 * SCGI connector.<br>
 * Version: 1.0<br>
 * Home page: http://snippets.dzone.com/posts/show/4304
 */
public class SCGI {
  public static class SCGIException extends IOException {
    private static final long serialVersionUID = 1L;

    public SCGIException(String message) {
      super(message);
    }
  }

  /** Used to decode the headers. */
  public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");

  /**
   * Read the <a href="http://python.ca/scgi/protocol.txt">SCGI</a> request headers.<br>
   * After the headers had been loaded,
   * you can read the body of the request manually from the same {@code input} stream:<pre>
   *   // Load the SCGI headers.
   *   Socket clientSocket = socket.accept();
   *   BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream(), 4096);
   *   HashMap<String, String> env = SCGI.parse(bis);
   *   // Read the body of the request.
   *   bis.read(new byte[Integer.parseInt(env.get("CONTENT_LENGTH"))]);
   * </pre>
   * @param input an efficient (buffered) input stream.
   * @return strings passed via the SCGI request.
   */
  public static HashMap parse(InputStream input) throws IOException {
    StringBuilder lengthString = new StringBuilder(12);
    String headers = "";
    for (;;) {
      char ch = (char) input.read();
      if (ch >= '0' && ch <= '9') {
        lengthString.append(ch);
      } else if (ch == ':') {
        int length = Integer.parseInt(lengthString.toString());
        byte[] headersBuf = new byte[length];
        int read = input.read(headersBuf);
        if (read != headersBuf.length)
          throw new SCGIException("Couldn't read all the headers (" + length + ").");
        headers = ISO_8859_1.decode(ByteBuffer.wrap(headersBuf)).toString();
        if (input.read() != ',') throw new SCGIException("Wrong SCGI header length: " + lengthString);
        break;
      } else {
        lengthString.append(ch);
        throw new SCGIException("Wrong SCGI header length: " + lengthString);
      }
    }
    HashMap env = new HashMap();
    while (headers.length() != 0) {
      int sep1 = headers.indexOf(0);
      int sep2 = headers.indexOf(0, sep1 + 1);
      env.put(headers.substring(0, sep1), headers.substring(sep1 + 1, sep2));
      headers = headers.substring(sep2 + 1);
    }
    return env;
  }
}

Babelfish translate

Ok, so maybe some of you might think that Babelfish's the best translator out there. I don't know about that , but I do know where my towel is ;)
So, boys and girls, here's the bookmarklet that allows to translate your current web-page using the babelfish translation engine.

javascript:location.href='http://babelfish.altavista.com/babelfish/tr?trurl='+encodeURIComponent(location.href)+'&lp=%s&btnTrUrl=Translate'


To make it useful, save it as a bookmark in FF (or as a new search engine in Opera) and give it a keyword/shortcut by editing the bookmark's properties in FF (or the search properties in Opera). Let's call him, say 'bf', that should do it.

Here are some examples:
bf en_fr
bf fr_en
bf en_ja


Enjoy!
G.R.

Google translate bookmarklet

Here's perhaps the most powerful bookmarklet I've ever created ...
This one translates the current web page from your current browser session into another language!

Syntax from the address bar in your FF or Opera browser:
 tr <FROM>|<TO>


Examples:
 tr en|de
 tr en|fr
 tr en|pt
 tr de|en


Here's the bookmarklet code
javascript:location.href='http://translate.google.com/translate?u='+encodeURIComponent(location.href)+'&langpair=%s&hl=EN&ie=UTF-8&oe=UTF-8&prev=%2Flanguage_tools'


FF instructions:
Copy/paste the code in a new bookmark. Then, in the new bookmark properties, edit the keyword/shortcut field and insert 'tr'. That's it!

Opera instructions:
Copy the bookmarklet code. Then, in tools-->preferences-->search-->add-->details, paste the code in the address field, fill in a name for in the name field, and write 'tr' in the keyword field. Then save all. That's it!

jaiku.py

// Set and view Jaiku statuses

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="28 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4223"

import sys, getopt, urllib2, xmlrpclib

import configreader

STATUS_MODE="STATUS"
VIEW_MODE="VIEW"

def set_status(settings, status):
	s=xmlrpclib.ServerProxy(settings["xmlrpcurl"])
	
	calldata={"user":settings["username"], "personal_key":settings["personalkey"], "message":status, "location":settings["location"]}
	
	try:
		s.presence.send(calldata)
	except:
		raise "Could not connect."

def view_status(settings):
	item=settings["itemdelimeter"]
	t1=settings["titledelimeter1"]
	t2=settings["titledelimeter2"]

	try:
		instream=urllib2.urlopen(
			settings["feedurlstart"]+settings["username"]+settings["feedurlend"]
		)

		for line in instream:
			if item in line:
				break

		title=instream.readline()

		instream.close()

		status=title[title.index(t1)+len(t1):title.index(t2)]

		return status

	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options]" % (sys.argv[0])
	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
	print "\n-u|--username <username> specified in jaiku.conf"
	print "-p|--personal-key <key>"
	print "-l|--location <location>"
	print "-s|--status mode"
	print "-v|--view status"
	print "-c|--config <configfile>"
	print "-h|--help"

	sys.exit()

def main():
	global STATUS_MODE
	global VIEW_MODE

	systemArgs=sys.argv[1:]

	mode=STATUS_MODE

	settings={
		"config":"jaiku.conf",
		"xmlrpcurl":"http://api.jaiku.com/xmlrpc",
		"feedurlstart":"http://",
		"feedurlend":".jaiku.com/feed/atom",
		"itemdelimeter":"<entry>",
		"titledelimeter1":"<title>",
		"titledelimeter2":"</title>",
		"username":"mcandre",
		"personalkey":"",
		"location":""
	}

	optlist, args=[], []

	try:
		optlist, args=getopt.getopt(systemArgs, "u:p:l:svc:h", ["username=", "personal-key=", "location=", "status", "view", "config=", "help"])
	except e:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-u" or option=="--username":
			settings["username"]=value
		elif option=="-p" or option=="--personal-key":
			settings["personalkey"]=value
		elif option=="-l" or option=="--location":
			settings["location"]=value
		elif option=="-s" or option=="--status":
			mode=STATUS_MODE
		elif option=="-v" or option=="--view":
			mode=VIEW_MODE

	if mode==STATUS_MODE:
		if len(args)<1:
			usage()

		message=" ".join(args)

		set_status(settings, message)
	elif mode==VIEW_MODE:
		print view_status(settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

tiny.py

#!/usr/bin/env python

"""Converts long URLs to tiny URLs, with either tinyurl, urltea, or a custom url."""

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="22 Jun 2007 - 24 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4195"
__credits__="http://lateral.netmanagers.com.ar/weblog/2007/04/08.html#BB548"

import sys, getopt, urllib

import configreader

def tiny(url, settings):
	try:
		encodedurl=settings["posting url"]+urllib.urlencode({"url":url})
		instream=urllib.urlopen(encodedurl)
		tinyurl=instream.read()
		instream.close()

		if len(tinyurl)==0:
			return url

		if settings["service"]=="urltea" and len(settings["description"])>0:
				tinyurl+=settings["description delimeter"]+settings["description"]

		return tinyurl
	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options] <url1> <url2> <url3> ..." % (sys.argv[0])
	print "\nDefaults to urlTea unless specified in options or a config file."
	print "\n-s|--service [tinyurl|urltea]"
	print "-u|--custom-url <posting url>"
	print "-d|--description <comment> May only be used with urltea."
	print "-c|--config <configfile>"
	print "-h|--help (usage)"

	sys.exit()

def main():
	systemArgs=sys.argv[1:]
	oplist, args=[], []

	settings={
		"config":"tiny.conf",
		"service":"urltea",
		"urltea url":"http://urltea.com/api/text/?url=",
		"tinyurl url":"http://tinyurl.com/api-create.php?",
		"description delimeter":"?",
		"description":""
	}

	try:
		optlist, args=getopt.getopt(systemArgs, "s:u:d:c:h", ["service=", "custom-url=", "description=", "config=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()
		elif option=="-s" or option=="--service":
			settings["service"]=value
		elif option=="-d" or option=="--description":
			settings["description"]=value

	if settings["service"]!="urltea" and len(settings["description"])>0:
		usage()

	try:
		settings["posting url"]=settings[settings["service"]+" url"]
	except:
		usage()

	for option, value in optlist:
		if option=="-u" or option=="--custom-url":
			settings["posting url"]=value

	if len(args)<1:
		usage()

	for u in args:
		print tiny(u, settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

tw.py

// Sets and views Twitter status

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="17 Jun 2007 - 28 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__credits__="Based on tweetyPy (http://muffinresearch.co.uk/archives/2007/03/24/tweetypy-python-based-cli-client-for-twitter/)"
__URL__="http://snippets.dzone.com/posts/show/4150"

import sys, getopt, getpass, urllib, urllib2

import configreader

STATUS_MODE="STATUS"
VIEW_MODE="VIEW"
COMMAND_MODE="COMMAND"

COMMANDS="""Command\t\tMeaning

d username\tDirect Text
@username\tReply
follow username\tReceive updates via phone or IM
leave username\tStop following username
leave all\tStop following all friends
remove username\tRemove username from friends list
delete username\tDelete username from friends list
get username\tGet the last update from username
get\tGet the most recent updates from all friends
nudge username\tTwitter aks what the person is currently up to
whois username\tGet username's bio
add phonenumber\tSend text invite. If already a member, invite will turn into a friend request.
accept username\tAccept username as a friend
deny username\tDeny username as friend"""

def usage():
	print "Usage: %s [options]" % (sys.argv[0])
	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
	print "\n-u|--username <username> specified in tw.conf"
	print "-s|--status mode"
	print "-v|--view status"
	print "-l|--list-commands List Twitter commands"
	print "-c|--config <configfile>"
	print "-h|--help"

	sys.exit()

def set_status(settings, status):
	auth=urllib2.HTTPPasswordMgrWithDefaultRealm()
	auth.add_password(None, settings["rootauthurl"], settings["username"], settings["password"])
	authHandler=urllib2.HTTPBasicAuthHandler(auth)
	opener=urllib2.build_opener(authHandler)

	url="http://twitter.com/statuses/update.xml"
	post=urllib.urlencode({"status":status})

	request=urllib2.Request(url, post)
	request.add_header("User-Agent", settings["useragent"])

	try:
		response=opener.open(request)
	except IOError, e:
		raise "Could not connect."

def view_status(settings):
	url="http://twitter.com/"+settings["username"]
	message=""

	statusdelimeter1=settings["statusdelimeter1"]
	statusdelimeter2=settings["statusdelimeter2"]

	try:
		instream=urllib.urlopen(url)
		for line in instream:
			if statusdelimeter1 in line:
				message=line[
					line.index(statusdelimeter1)+len(statusdelimeter1):line.index(statusdelimeter2)
				]
				break
		instream.close()

		return message
				
	except IOError, e:
		raise "Could not connect."

def main():
	global STATUS_MODE
	global VIEW_MODE
	global COMMAND_MODE
	global COMMANDS

	sysArgs=sys.argv[1:]

	mode=STATUS_MODE

	settings={
		"config":"tw.conf",
		"username":"mcandre",
		"rootauthurl":"http://twitter.com/statuses/",
		"useragent":sys.argv[0]+" "+__version__,
		"statusdelimeter1":"<p class=\"entry-title entry-content\">",
		"statusdelimeter2":"</p>"
	}

	optlist, args=[], []
	try:
		optlist, args=getopt.getopt(sysArgs, "u:svlc:h", ["username=", "status", "view", "list-commands", "config=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-u" or option=="--username":
			settings["username"]=value
		elif option=="-s" or option=="--status":
			mode=STATUS_MODE
		elif option=="-v" or option=="--view":
			mode=VIEW_MODE
		elif option=="-l" or option=="--list=commands":
			mode=COMMAND_MODE

	if mode==STATUS_MODE:
		if len(args)<1:
			usage()

		message=" ".join(args)

		settings["password"]=getpass.getpass()

		set_status(settings, message)
	elif mode==VIEW_MODE:
		print view_status(settings)
	elif mode==COMMAND_MODE:
		print COMMANDS

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

Making Columns Render with Equal Height

A problem sometimes faced by web developers is trying to get two (or more) columns in a multi-column layout to be the same height when the content is variable. Rather than using an arbitrary hardcoded value, the heights can be equalized (to the tallest one) with this script.

Assuming two columns in div tags with ids of "leftside" and "rightside" this script will set the height of the shorter to the height of the taller one. The page must be in standards compliant mode with a valid doctype or IE will mess it up in quirks mode. For longer articles and discussion visit my home site... ERT
<script type="text/javascript">
function setH()
{
   var maxH = Math.max(document.getElementById('leftside').offsetHeight,document.getElementById('rightside').offsetHeight);
   document.getElementById('leftside').style.height=maxH+'px';
   document.getElementById('rightside').style.height=maxH+'px';
}
onload=setH;
</script>

Setting Element Height Dynamically

There are times when you need to control the height of an element based on the screen size. However youcan control the user setup, and of course there are browser differences so this snippet handles browser and object detection and sets the height during page load and for any re-sizing event.

An example of the snippet in action

  var minorOffset = (document.all)? 25 : 38;
   function setHgt()
   {
      var sHGT;
      srcobj=document.getElementById('main');
      if (self.innerHeight)
      {
	   sHGT = self.innerHeight;
	}
      else
      { 
         if (document.documentElement && document.documentElement.clientHeight)
         {
	      sHGT = document.documentElement.clientHeight;
         }
         else
         {
            if (document.body)
            {
              sHGT = document.body.clientHeight;
            }
         }
      }
      sHGT=sHGT-(document.getElementById('main').offsetTop+minorOffset);
  document.getElementById('main').style.height=sHGT+"px";
   }
window.onload=setHgt;
window.onresize=setHgt;
« Newer Snippets
Older Snippets »
Showing 11-20 of 80 total