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

About this user

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

to_hoa

class Array
  
  # Make a hash of arrays out of an array
  # of somethings by involving each element.
  #
  # Pass a block returning each keys' name.
  #
  # Example usage:
  #
  # >> [1, 2, 3].to_hoa { |n| (n+96).chr }
  # => {"a"=>[1], "b"=>[2], "c"=>[3]}
  #
  # >> ['a', 'a', 'a', 'b', 'b', 'c'].to_hoa {|x|x}
  # => {"a"=>["a", "a", "a"], "b"=>["b", "b"], "c"=>["c"]}
    
  def to_hoa
    inject({}) { |h,v| (h[yield(v)] ||= []).push v; h }
  end

end


update: RoR provides group_by, which does exactly the same using Enumerable (thanks Matt for pointing this out).

word-style TOC with roman- and page-numbers

ol { list-style:upper-roman; }
li { 
	/* color depends */
	border-bottom:1px dashed black; 
} 

li span { 
	float:right; 
	padding-left:10px; 
}

li a { 
	text-decoration:none; 
	padding-right:10px; 
}

li a, li span {
	position:relative;		
	background:white; /* depends */
	top:2px;
}


source: http://blogger.xs4all.nl/peterned/archive/2006/06/30/103089.aspx

lighttpd (or anything else) through apache2 proxy

<VirtualHost *:80>
  ServerAdmin        webmaster@inter.net
  ServerName         www.inter.net
  ProxyRequests      Off
  ProxyPreserveHost  On
  RewriteEngine      On
  RewriteRule        ^/(.*) http://127.0.0.1:3000/$1 [P,L]
  ProxyPassReverse   / http://127.0.0.1:3000/
</VirtualHost>

Leak Free Javascript Closures

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.

Solution:

Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};


Usage example:

function attach()
{
  var element = document.getElementById("my-element");
  element.attachEvent("onclick", function()
    {
      alert("Clicked: " + this.innerHTML);
    }.closure(element));
}


So now we have truly leak free closures.

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:

window.__objs[obj.__objId] = null;


Source: Leak Free Javascript Closures

decimal value of an ASCII letter

converting a "A" to a 65:
p 'A'[0]

Cheapest rsync replacement (with Ruby)

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. (...)

#!/usr/bin/env ruby

REMOTE_RUBY = "ruby"
# TODO: allow REMOTE_RUBY to be specified via a cmdline opt

if ARGV.size != 2 || ARGV[0][/:/].nil? || !File.exist?(ARGV[1])
  puts <<EOF
  ruby logfetcher.rb host:path/to/src dst
EOF
  exit
end

FILE = ARGV[1]
REMOTE_HOST, REMOTE_FILE = ARGV[0].split(/:/)
BLOCK_SIZE = 8192

osize = File.size(FILE)
#FIXME: cheap escaping
command = "File.open(#{REMOTE_FILE.inspect}){|f| " + 
          "f.pos = #{osize}; print f.read(#{BLOCK_SIZE}) until f.eof? }"

command.gsub!(/"/){'\\"'}
fetched = 0
t = nil
$stdout.sync = true
print "Establishing connection\r"
File.open(FILE, "a") do |os|
  IO.popen(%{ssh #{REMOTE_HOST} ruby -e '"#{command}"'}) do |is|
    until is.eof?
      data = is.read(BLOCK_SIZE)
      t ||= Time.new # ignore the time it takes to establish the SSH connection
      fetched += data.size
      print "Read #{fetched}                          \r"
      os.write(data)
    end
  end
end
print(" " * 50  + "\r")

dt = Time.new - t
puts "Fetched #{fetched} bytes."
puts "Total size #{osize + fetched}."
puts "Needed %4.1f seconds." % dt
puts "Average speed %d bytes/sec." % (fetched / dt)


Source: Cheapest rsync replacement

simple IRC bot written in Ruby

A simple IRC bot written in Ruby. It's only 100 lines long!

#!/usr/local/bin/ruby

require "socket"

# Don't allow use of "tainted" data by potentially dangerous operations
$SAFE=1

# The irc class, which talks to the server and holds the main event loop
class IRC
    def initialize(server, port, nick, channel)
        @server = server
        @port = port
        @nick = nick
        @channel = channel
    end
    def send(s)
        # Send a message to the irc server and print it to the screen
        puts "--> #{s}"
        @irc.send "#{s}\n", 0 
    end
    def connect()
        # Connect to the IRC server
        @irc = TCPSocket.open(@server, @port)
        send "USER blah blah blah :blah blah"
        send "NICK #{@nick}"
        send "JOIN #{@channel}"
    end
    def evaluate(s)
        # Make sure we have a valid expression (for security reasons), and
        # evaluate it if we do, otherwise return an error message
        if s =~ /^[-+*\/\d\s\eE.()]*$/ then
            begin
                s.untaint
                return eval(s).to_s
            rescue Exception => detail
                puts detail.message()
            end
        end
        return "Error"
    end
    def handle_server_input(s)
        # This isn't at all efficient, but it shows what we can do with Ruby
        # (Dave Thomas calls this construct "a multiway if on steroids")
        case s.strip
            when /^PING :(.+)$/i
                puts "[ Server ping ]"
                send "PONG :#{$1}"
            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]PING (.+)[\001]$/i
                puts "[ CTCP PING from #{$1}!#{$2}@#{$3} ]"
                send "NOTICE #{$1} :\001PING #{$4}\001"
            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]VERSION[\001]$/i
                puts "[ CTCP VERSION from #{$1}!#{$2}@#{$3} ]"
                send "NOTICE #{$1} :\001VERSION Ruby-irc v0.042\001"
            when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+)\s:EVAL (.+)$/i
                puts "[ EVAL #{$5} from #{$1}!#{$2}@#{$3} ]"
                send "PRIVMSG #{(($4==@nick)?$1:$4)} :#{evaluate($5)}"
            else
                puts s
        end
    end
    def main_loop()
        # Just keep on truckin' until we disconnect
        while true
            ready = select([@irc, $stdin], nil, nil, nil)
            next if !ready
            for s in ready[0]
                if s == $stdin then
                    return if $stdin.eof
                    s = $stdin.gets
                    send s
                elsif s == @irc then
                    return if @irc.eof
                    s = @irc.gets
                    handle_server_input(s)
                end
            end
        end
    end
end

# The main program
# If we get an exception, then print it out and keep going (we do NOT want
# to disconnect unexpectedly!)
irc = IRC.new('efnet.skynet.be', 6667, 'Alt-255', '#cout')
irc.connect()
begin
    irc.main_loop()
rescue Interrupt
rescue Exception => detail
    puts detail.message()
    print detail.backtrace.join("\n")
    retry
end


Source: rubystuff.org

Sierpinski Triangle - ruby one-liner

ruby -le'32.times{|y|print" "*(31-y),(0..y).map{|x|~y&x>0?" .":" A"}}'


Source: Signatures and one liners

uP2P — micro P2P file sharing application

#!/bin/sh
# uP2P.sh 0.0.1, 436 characters (excluding comments)
[ $3 ]&&export W=$1 H="$2 $3" K=`mktemp`;Z=/dev/null;e(){ echo "$*";};n(){
nc $* 2>$Z;};x(){ nc -lp ${H#* } -e $1 &>$Z <$Z&};f(){ cat $K|while read h;do
e $W $1 "$2"|n $h;done };case $# in 4)e $W s "$4"|n $H|while read h p f; do
e $W g "$f"|n $h $p>"$f";done;;5)e $H>$K;e $W d $H|n $4 $5>>$K;x $0;;0)x $0
read w c r;[ $W = $w ]&&case $c in s)f l "$r";;g)cat "$r";;a)e $r>>$K;;d)cat $K
f a "$r";;l)ls|grep "$r"|sed "s/^/$H /";;esac;;esac


Source: uP2P, mentioned here

six line peer-to-peer client/server in ruby


slonik AZ wrote:
> slashdot published an article on someone's
> 15 lines long Peer-2-Peer application
> http://developers.slashdot.org/article.pl?sid=04/12/15/1953227

> Another person followed up with a 9 line equivalent Perl code.

> I wonder what an equivalent Ruby program would look like?

I did this 9.5 hours ago. Compared to the python one it is not
vulnerable to File stealing attacks (a client can request a file
../foobar and ~/foobar from the python server and will get it back
AFAIK) and 6 lines long. It is however vulnerable to the DRb style
.instance_eval exploits. I will fix this shortly, but I might have to
use 7 lines then.


# Server: ruby p2p.rb password server server-uri merge-servers
# Sample: ruby p2p.rb foobar server druby://localhost:1337 druby://foo.bar:1337
# Client: ruby p2p.rb password client server-uri download-pattern
# Sample: ruby p2p.rb foobar client druby://localhost:1337 *.rb
require'drb';F,D,C,P,M,U,*O=File,Class,Dir,*ARGV;def s(p)F.split(p[/[^|].*/])[-1
]end;def c(u);DRbObject.new((),u)end;def x(u)[P,u].hash;end;M=="client"&&c(U).f(
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,
"w"){|o|o<<c.f(p,f,1)}}}||(DRb.start_service U,C.new{def f(c,a=[],t=2)c==x(U)&&(
t==0&&D[s(a)]||t==1&&F.read(s(a))||p(a))end;def y()(p(U)+p).each{|u|c(u).f(x(u),
p(U))rescue()};self;end;private;def p(x=[]);O.push(*x).uniq!;O;end}.new.y;sleep) 


Source: p2p.rb (Florian Gross), mentioned here
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS