<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: 413x's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Mon, 06 Oct 2008 11:41:10 GMT</pubDate>
    <description>DZone Snippets: 413x's Code Snippets</description>
    <item>
      <title>to_hoa</title>
      <link>http://snippets.dzone.com/posts/show/4404</link>
      <description>&lt;code&gt;&lt;br /&gt;class Array&lt;br /&gt;  &lt;br /&gt;  # Make a hash of arrays out of an array&lt;br /&gt;  # of somethings by involving each element.&lt;br /&gt;  #&lt;br /&gt;  # Pass a block returning each keys' name.&lt;br /&gt;  #&lt;br /&gt;  # Example usage:&lt;br /&gt;  #&lt;br /&gt;  # &gt;&gt; [1, 2, 3].to_hoa { |n| (n+96).chr }&lt;br /&gt;  # =&gt; {"a"=&gt;[1], "b"=&gt;[2], "c"=&gt;[3]}&lt;br /&gt;  #&lt;br /&gt;  # &gt;&gt; ['a', 'a', 'a', 'b', 'b', 'c'].to_hoa {|x|x}&lt;br /&gt;  # =&gt; {"a"=&gt;["a", "a", "a"], "b"=&gt;["b", "b"], "c"=&gt;["c"]}&lt;br /&gt;    &lt;br /&gt;  def to_hoa&lt;br /&gt;    inject({}) { |h,v| (h[yield(v)] ||= []).push v; h }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;update:&lt;/em&gt; RoR provides &lt;strong&gt;group_by&lt;/strong&gt;, which does exactly the same using Enumerable (thanks Matt for pointing this out).</description>
      <pubDate>Thu, 09 Aug 2007 16:36:20 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4404</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>word-style TOC with roman- and page-numbers</title>
      <link>http://snippets.dzone.com/posts/show/2252</link>
      <description>&lt;code&gt;&lt;br /&gt;ol { list-style:upper-roman; }&lt;br /&gt;li { &lt;br /&gt;	/* color depends */&lt;br /&gt;	border-bottom:1px dashed black; &lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;li span { &lt;br /&gt;	float:right; &lt;br /&gt;	padding-left:10px; &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;li a { &lt;br /&gt;	text-decoration:none; &lt;br /&gt;	padding-right:10px; &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;li a, li span {&lt;br /&gt;	position:relative;		&lt;br /&gt;	background:white; /* depends */&lt;br /&gt;	top:2px;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;source: http://blogger.xs4all.nl/peterned/archive/2006/06/30/103089.aspx&lt;br /&gt;</description>
      <pubDate>Thu, 06 Jul 2006 22:01:15 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2252</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>lighttpd (or anything else) through apache2 proxy</title>
      <link>http://snippets.dzone.com/posts/show/1945</link>
      <description>&lt;code&gt;&lt;br /&gt;&lt;VirtualHost *:80&gt;&lt;br /&gt;  ServerAdmin        webmaster@inter.net&lt;br /&gt;  ServerName         www.inter.net&lt;br /&gt;  ProxyRequests      Off&lt;br /&gt;  ProxyPreserveHost  On&lt;br /&gt;  RewriteEngine      On&lt;br /&gt;  RewriteRule        ^/(.*) http://127.0.0.1:3000/$1 [P,L]&lt;br /&gt;  ProxyPassReverse   / http://127.0.0.1:3000/&lt;br /&gt;&lt;/VirtualHost&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 20 Apr 2006 15:44:06 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1945</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>Leak Free Javascript Closures</title>
      <link>http://snippets.dzone.com/posts/show/1905</link>
      <description>Javascript closures can be a powerful programming technique. Unfortunately in Internet Explorer they are a common source of memory leaks. Therefore I propose a method to create closures that don't leak memory.&lt;br /&gt;&lt;br /&gt;Solution:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;Function.prototype.closure = function(obj)&lt;br /&gt;{&lt;br /&gt;  // Init object storage.&lt;br /&gt;  if (!window.__objs)&lt;br /&gt;  {&lt;br /&gt;    window.__objs = [];&lt;br /&gt;    window.__funs = [];&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  // For symmetry and clarity.&lt;br /&gt;  var fun = this;&lt;br /&gt;&lt;br /&gt;  // Make sure the object has an id and is stored in the object store.&lt;br /&gt;  var objId = obj.__objId;&lt;br /&gt;  if (!objId)&lt;br /&gt;    __objs[objId = obj.__objId = __objs.length] = obj;&lt;br /&gt;&lt;br /&gt;  // Make sure the function has an id and is stored in the function store.&lt;br /&gt;  var funId = fun.__funId;&lt;br /&gt;  if (!funId)&lt;br /&gt;    __funs[funId = fun.__funId = __funs.length] = fun;&lt;br /&gt;&lt;br /&gt;  // Init closure storage.&lt;br /&gt;  if (!obj.__closures)&lt;br /&gt;    obj.__closures = [];&lt;br /&gt;&lt;br /&gt;  // See if we previously created a closure for this object/function pair.&lt;br /&gt;  var closure = obj.__closures[funId];&lt;br /&gt;  if (closure)&lt;br /&gt;    return closure;&lt;br /&gt;&lt;br /&gt;  // Clear references to keep them out of the closure scope.&lt;br /&gt;  obj = null;&lt;br /&gt;  fun = null;&lt;br /&gt;&lt;br /&gt;  // Create the closure, store in cache and return result.&lt;br /&gt;  return __objs[objId].__closures[funId] = function ()&lt;br /&gt;  {&lt;br /&gt;    return __funs[funId].apply(__objs[objId], arguments);&lt;br /&gt;  };&lt;br /&gt;};&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Usage example:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;function attach()&lt;br /&gt;{&lt;br /&gt;  var element = document.getElementById("my-element");&lt;br /&gt;  element.attachEvent("onclick", function()&lt;br /&gt;    {&lt;br /&gt;      alert("Clicked: " + this.innerHTML);&lt;br /&gt;    }.closure(element));&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;So now we have truly leak free closures.&lt;br /&gt;&lt;br /&gt;In addition we can also easily remove an object from the global array. The following code allows the garbage collector to free an object if there are no other references to it: &lt;br /&gt;&lt;br /&gt;&lt;code&gt;window.__objs[obj.__objId] = null;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://laurens.vd.oever.nl/weblog/items2005/closures/"&gt;Leak Free Javascript Closures&lt;/a&gt;&lt;br /&gt;</description>
      <pubDate>Wed, 12 Apr 2006 05:46:09 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1905</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>decimal value of an ASCII letter</title>
      <link>http://snippets.dzone.com/posts/show/1813</link>
      <description>converting a "A" to a 65:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;p 'A'[0]&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 31 Mar 2006 15:20:06 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1813</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>Cheapest rsync replacement (with Ruby)</title>
      <link>http://snippets.dzone.com/posts/show/1812</link>
      <description>I often use rsync to keep a local copy of some HTTPD logs (around ~200MB atm.). Since they are append-only, having rsync compute and compare the checksums for the parts I already have seems wasteful: both my box and the one I'm copying from would be happier if they didn't have to process a couple hundred MBs for nothing. (...)&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/env ruby&lt;br /&gt;&lt;br /&gt;REMOTE_RUBY = "ruby"&lt;br /&gt;# TODO: allow REMOTE_RUBY to be specified via a cmdline opt&lt;br /&gt;&lt;br /&gt;if ARGV.size != 2 || ARGV[0][/:/].nil? || !File.exist?(ARGV[1])&lt;br /&gt;  puts &lt;&lt;EOF&lt;br /&gt;  ruby logfetcher.rb host:path/to/src dst&lt;br /&gt;EOF&lt;br /&gt;  exit&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;FILE = ARGV[1]&lt;br /&gt;REMOTE_HOST, REMOTE_FILE = ARGV[0].split(/:/)&lt;br /&gt;BLOCK_SIZE = 8192&lt;br /&gt;&lt;br /&gt;osize = File.size(FILE)&lt;br /&gt;#FIXME: cheap escaping&lt;br /&gt;command = "File.open(#{REMOTE_FILE.inspect}){|f| " + &lt;br /&gt;          "f.pos = #{osize}; print f.read(#{BLOCK_SIZE}) until f.eof? }"&lt;br /&gt;&lt;br /&gt;command.gsub!(/"/){'\\"'}&lt;br /&gt;fetched = 0&lt;br /&gt;t = nil&lt;br /&gt;$stdout.sync = true&lt;br /&gt;print "Establishing connection\r"&lt;br /&gt;File.open(FILE, "a") do |os|&lt;br /&gt;  IO.popen(%{ssh #{REMOTE_HOST} ruby -e '"#{command}"'}) do |is|&lt;br /&gt;    until is.eof?&lt;br /&gt;      data = is.read(BLOCK_SIZE)&lt;br /&gt;      t ||= Time.new # ignore the time it takes to establish the SSH connection&lt;br /&gt;      fetched += data.size&lt;br /&gt;      print "Read #{fetched}                          \r"&lt;br /&gt;      os.write(data)&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;print(" " * 50  + "\r")&lt;br /&gt;&lt;br /&gt;dt = Time.new - t&lt;br /&gt;puts "Fetched #{fetched} bytes."&lt;br /&gt;puts "Total size #{osize + fetched}."&lt;br /&gt;puts "Needed %4.1f seconds." % dt&lt;br /&gt;puts "Average speed %d bytes/sec." % (fetched / dt)&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://eigenclass.org/hiki.rb?cheap+rsync"&gt;Cheapest rsync replacement&lt;/a&gt;</description>
      <pubDate>Fri, 31 Mar 2006 15:06:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1812</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>simple IRC bot written in Ruby</title>
      <link>http://snippets.dzone.com/posts/show/1785</link>
      <description>A simple IRC bot written in Ruby. It's only 100 lines long!&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/local/bin/ruby&lt;br /&gt;&lt;br /&gt;require "socket"&lt;br /&gt;&lt;br /&gt;# Don't allow use of "tainted" data by potentially dangerous operations&lt;br /&gt;$SAFE=1&lt;br /&gt;&lt;br /&gt;# The irc class, which talks to the server and holds the main event loop&lt;br /&gt;class IRC&lt;br /&gt;    def initialize(server, port, nick, channel)&lt;br /&gt;        @server = server&lt;br /&gt;        @port = port&lt;br /&gt;        @nick = nick&lt;br /&gt;        @channel = channel&lt;br /&gt;    end&lt;br /&gt;    def send(s)&lt;br /&gt;        # Send a message to the irc server and print it to the screen&lt;br /&gt;        puts "--&gt; #{s}"&lt;br /&gt;        @irc.send "#{s}\n", 0 &lt;br /&gt;    end&lt;br /&gt;    def connect()&lt;br /&gt;        # Connect to the IRC server&lt;br /&gt;        @irc = TCPSocket.open(@server, @port)&lt;br /&gt;        send "USER blah blah blah :blah blah"&lt;br /&gt;        send "NICK #{@nick}"&lt;br /&gt;        send "JOIN #{@channel}"&lt;br /&gt;    end&lt;br /&gt;    def evaluate(s)&lt;br /&gt;        # Make sure we have a valid expression (for security reasons), and&lt;br /&gt;        # evaluate it if we do, otherwise return an error message&lt;br /&gt;        if s =~ /^[-+*\/\d\s\eE.()]*$/ then&lt;br /&gt;            begin&lt;br /&gt;                s.untaint&lt;br /&gt;                return eval(s).to_s&lt;br /&gt;            rescue Exception =&gt; detail&lt;br /&gt;                puts detail.message()&lt;br /&gt;            end&lt;br /&gt;        end&lt;br /&gt;        return "Error"&lt;br /&gt;    end&lt;br /&gt;    def handle_server_input(s)&lt;br /&gt;        # This isn't at all efficient, but it shows what we can do with Ruby&lt;br /&gt;        # (Dave Thomas calls this construct "a multiway if on steroids")&lt;br /&gt;        case s.strip&lt;br /&gt;            when /^PING :(.+)$/i&lt;br /&gt;                puts "[ Server ping ]"&lt;br /&gt;                send "PONG :#{$1}"&lt;br /&gt;            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]PING (.+)[\001]$/i&lt;br /&gt;                puts "[ CTCP PING from #{$1}!#{$2}@#{$3} ]"&lt;br /&gt;                send "NOTICE #{$1} :\001PING #{$4}\001"&lt;br /&gt;            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]VERSION[\001]$/i&lt;br /&gt;                puts "[ CTCP VERSION from #{$1}!#{$2}@#{$3} ]"&lt;br /&gt;                send "NOTICE #{$1} :\001VERSION Ruby-irc v0.042\001"&lt;br /&gt;            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+)\s:EVAL (.+)$/i&lt;br /&gt;                puts "[ EVAL #{$5} from #{$1}!#{$2}@#{$3} ]"&lt;br /&gt;                send "PRIVMSG #{(($4==@nick)?$1:$4)} :#{evaluate($5)}"&lt;br /&gt;            else&lt;br /&gt;                puts s&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;    def main_loop()&lt;br /&gt;        # Just keep on truckin' until we disconnect&lt;br /&gt;        while true&lt;br /&gt;            ready = select([@irc, $stdin], nil, nil, nil)&lt;br /&gt;            next if !ready&lt;br /&gt;            for s in ready[0]&lt;br /&gt;                if s == $stdin then&lt;br /&gt;                    return if $stdin.eof&lt;br /&gt;                    s = $stdin.gets&lt;br /&gt;                    send s&lt;br /&gt;                elsif s == @irc then&lt;br /&gt;                    return if @irc.eof&lt;br /&gt;                    s = @irc.gets&lt;br /&gt;                    handle_server_input(s)&lt;br /&gt;                end&lt;br /&gt;            end&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# The main program&lt;br /&gt;# If we get an exception, then print it out and keep going (we do NOT want&lt;br /&gt;# to disconnect unexpectedly!)&lt;br /&gt;irc = IRC.new('efnet.skynet.be', 6667, 'Alt-255', '#cout')&lt;br /&gt;irc.connect()&lt;br /&gt;begin&lt;br /&gt;    irc.main_loop()&lt;br /&gt;rescue Interrupt&lt;br /&gt;rescue Exception =&gt; detail&lt;br /&gt;    puts detail.message()&lt;br /&gt;    print detail.backtrace.join("\n")&lt;br /&gt;    retry&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://rubystuff.org/"&gt;rubystuff.org&lt;/a&gt;&lt;br /&gt;</description>
      <pubDate>Tue, 28 Mar 2006 16:10:26 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1785</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>Sierpinski Triangle - ruby one-liner</title>
      <link>http://snippets.dzone.com/posts/show/1784</link>
      <description>&lt;code&gt;&lt;br /&gt;ruby -le'32.times{|y|print" "*(31-y),(0..y).map{|x|~y&amp;x&gt;0?" .":" A"}}'&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://ruby-talk.org/cgi-bin/vframe.rb/ruby/ruby-talk/122644?122482-123428"&gt;Signatures and one liners&lt;/a&gt;</description>
      <pubDate>Tue, 28 Mar 2006 15:49:57 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1784</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>uP2P &#8212; micro P2P file sharing application</title>
      <link>http://snippets.dzone.com/posts/show/1783</link>
      <description>&lt;code&gt;&lt;br /&gt;#!/bin/sh&lt;br /&gt;# uP2P.sh 0.0.1, 436 characters (excluding comments)&lt;br /&gt;[ $3 ]&amp;&amp;export W=$1 H="$2 $3" K=`mktemp`;Z=/dev/null;e(){ echo "$*";};n(){&lt;br /&gt;nc $* 2&gt;$Z;};x(){ nc -lp ${H#* } -e $1 &amp;&gt;$Z &lt;$Z&amp;};f(){ cat $K|while read h;do&lt;br /&gt;e $W $1 "$2"|n $h;done };case $# in 4)e $W s "$4"|n $H|while read h p f; do&lt;br /&gt;e $W g "$f"|n $h $p&gt;"$f";done;;5)e $H&gt;$K;e $W d $H|n $4 $5&gt;&gt;$K;x $0;;0)x $0&lt;br /&gt;read w c r;[ $W = $w ]&amp;&amp;case $c in s)f l "$r";;g)cat "$r";;a)e $r&gt;&gt;$K;;d)cat $K&lt;br /&gt;f a "$r";;l)ls|grep "$r"|sed "s/^/$H /";;esac;;esac&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://www.crossflux.org/uP2P/"&gt;uP2P&lt;/a&gt;, mentioned &lt;a href="http://ansuz.sooke.bc.ca/software/molester/"&gt;here&lt;/a&gt;</description>
      <pubDate>Tue, 28 Mar 2006 15:45:07 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1783</guid>
      <author>413x ()</author>
    </item>
    <item>
      <title>six line peer-to-peer client/server in ruby</title>
      <link>http://snippets.dzone.com/posts/show/1782</link>
      <description>&lt;pre&gt;&lt;br /&gt;slonik AZ wrote:&lt;br /&gt;&gt; slashdot published an article on someone's&lt;br /&gt;&gt; 15 lines long Peer-2-Peer application&lt;br /&gt;&gt; http://developers.slashdot.org/article.pl?sid=04/12/15/1953227&lt;br /&gt;&lt;br /&gt;&gt; Another person followed up with a 9 line equivalent Perl code.&lt;br /&gt;&lt;br /&gt;&gt; I wonder what an equivalent Ruby program would look like?&lt;br /&gt;&lt;br /&gt;I did this 9.5 hours ago. Compared to the python one it is not&lt;br /&gt;vulnerable to File stealing attacks (a client can request a file&lt;br /&gt;../foobar and ~/foobar from the python server and will get it back&lt;br /&gt;AFAIK) and 6 lines long. It is however vulnerable to the DRb style&lt;br /&gt;.instance_eval exploits. I will fix this shortly, but I might have to&lt;br /&gt;use 7 lines then.&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Server: ruby p2p.rb password server server-uri merge-servers&lt;br /&gt;# Sample: ruby p2p.rb foobar server druby://localhost:1337 druby://foo.bar:1337&lt;br /&gt;# Client: ruby p2p.rb password client server-uri download-pattern&lt;br /&gt;# Sample: ruby p2p.rb foobar client druby://localhost:1337 *.rb&lt;br /&gt;require'drb';F,D,C,P,M,U,*O=File,Class,Dir,*ARGV;def s(p)F.split(p[/[^|].*/])[-1&lt;br /&gt;]end;def c(u);DRbObject.new((),u)end;def x(u)[P,u].hash;end;M=="client"&amp;&amp;c(U).f(&lt;br /&gt;x(U)).each{|n|p,c=x(n),c(n);(c.f(p,O[0],0).map{|f|s f}-D["*"]).each{|f|F.open(f,&lt;br /&gt;"w"){|o|o&lt;&lt;c.f(p,f,1)}}}||(DRb.start_service U,C.new{def f(c,a=[],t=2)c==x(U)&amp;&amp;(&lt;br /&gt;t==0&amp;&amp;D[s(a)]||t==1&amp;&amp;F.read(s(a))||p(a))end;def y()(p(U)+p).each{|u|c(u).f(x(u),&lt;br /&gt;p(U))rescue()};self;end;private;def p(x=[]);O.push(*x).uniq!;O;end}.new.y;sleep) &lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Source: &lt;a href="http://groups.google.ca/group/comp.lang.ruby/msg/8fc335f67f99536c"&gt;p2p.rb (Florian Gross)&lt;/a&gt;, mentioned &lt;a href="http://ansuz.sooke.bc.ca/software/molester/"&gt;here&lt;/a&gt;&lt;br /&gt;</description>
      <pubDate>Tue, 28 Mar 2006 15:39:33 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1782</guid>
      <author>413x ()</author>
    </item>
  </channel>
</rss>
