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!)

Use Tweetstream in Ruby

// description of your code here

Successfully installed yajl-ruby-0.6.3
Successfully installed daemons-1.0.10
Successfully installed intridea-tweetstream-0.1.3
3 gems installed
Installing ri documentation for yajl-ruby-0.6.3...
Installing ri documentation for daemons-1.0.10...
Installing RDoc documentation for yajl-ruby-0.6.3...
Installing RDoc documentation for daemons-1.0.10...


require 'rubygems'
require 'tweetstream'

user, pass = 'jrobertson', 'secret'
TweetStream::Client.new(user,pass).sample do |status|
  puts "[#{status.user.screen_name}] #{status.text}" 
  sleep 0.5
end

Anchor a footer to the bottom of a page

/* file: layout.css */

* {
  margin:0;
  padding:0;
}
html,body {
  margin:0;
  padding:0;
  height:100%; /* needed for container min-height */
  background:gray;
  
  font-family:arial,sans-serif;
  font-size:small;
  color:#666;
}

div#frame {
  position:relative; /* needed for footer positioning*/
  margin:0 auto; /* center, not in IE5 */
  width:750px;
  background:#f0f0f0;
  
  height:auto !important; /* real browsers */
  height:100%; /* IE6: treaded as min-height*/

  min-height:100%; /* real browsers */
}

  div#footer {
    position:absolute;
    width:100%;
    bottom:0; /* stick to bottom */
    background:#ddd;
    border-top:6px double gray;
  }

  div#footer p {
    padding:1em;
    margin:0;
  }

viagra acheter en france
acheter viagra en ligne
// desc of this that
comprare viagra senza ricetta
viagra vendita in italia

linux mmap cpp

linux mmap cpp

#ifndef _MMAP_H_20090819_
#define _MMAP_H_20090819_
#include <sys/stat.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>

class mmap_t {
        protected:
                int _fd;
                size_t _size;
                const char *_filename;
                char *_ptr;
                int _oflag;

                int _fileresize(size_t size) {
                        if(size==0 || _fd==-1 || _oflag==O_RDONLY) return -1;
                        if(ftruncate(_fd, size)==-1) return -1;
                        _size = size;
                        return 0;
                }
                void _closefd() {
                        if(_fd != -1)
                                ::close(_fd);
                        _fd = -1;
                        _filename = 0;
                        _oflag = 0;
                }
                void _destroy() {
                        if(_ptr != 0) {
                                msync((caddr_t)_ptr, 0, MS_ASYNC);
                                munmap((caddr_t)_ptr, _size);
                                _ptr = 0;
                                _size = 0;
                        }
                }

        public:
                mmap_t():_fd(-1),_size(0),_filename(0),_ptr(0),_oflag(0) {}
                ~mmap_t() {this->close();}

                size_t size() {
                        return _size;
                }
                char *ptr() {
                        return _ptr;
                }
                int open(const char *file, bool write_able = false, size_t size = 0, const mode_t perm_mode = 0644) {
                        this->close();
                        this->_filename = file;

                        if(write_able)
                                _oflag = O_RDWR|O_CREAT;
                        else
                                _oflag = O_RDONLY;

                        struct stat st;

                        if((_fd=::open(file, _oflag, perm_mode))<0)
                                return -1;

                        if(fstat(_fd, &st) != 0)
                                return -1;

                        _size = st.st_size;
                        if(size>0 && _size!=size && _fileresize(size)!=0) return -1;
                        if(_size==0) return -1;
int prot = PROT_READ;
                        if(_oflag&O_RDWR) prot |= PROT_WRITE;
                        _ptr = (char*) mmap(NULL, _size, prot, MAP_FILE|MAP_SHARED, _fd, 0);
                        if(_ptr==MAP_FAILED) return -1;

                        return 0;
                }

                int resize(size_t size) {
                        if(size==0) return -1;
                        this->_destroy();
                        if(_fileresize(size)!=0) return -1;
                        int prot = PROT_READ;
                        if(_oflag&O_RDWR) prot |= PROT_WRITE;
                        _ptr = (char*) mmap(NULL, _size, prot, MAP_SHARED, _fd, 0);
                        if(_ptr==MAP_FAILED) return -1;
                        return 0;
                }
                int close() {
                        this->_destroy();
                        this->_closefd();
                        return 0;
                }
                int flush() {
                        if(_ptr==0) return -1;
                        if(msync(_ptr, _size, MS_ASYNC)==-1)
                                return -1;
                        return 0;
                }
};

#endif


commander kamagra en ligne acheter kamagra en ligne
//desc of this that
compra viagra in italia
cialis acheter en france

JavaScript: Changing an Element's text content

It is possible to set the text, to cope with various browsers from IE 4,
5, 6, Netscape 6, 7, Mozilla, Opera 7, 8 and other DOM compliant
browsers you can use:

function setInnerText (elementId, text) {

  var element;

  if (document.getElementById) {
    element = document.getElementById(elementId);
  }

  else if (document.all) {
    element = document.all[elementId];
  }

  if (element) {

    if (typeof element.textContent != 'undefined') {
      element.textContent = text;
    }

    else if (typeof element.innerText != 'undefined') {
      element.innerText = text;
    }

    else if (typeof element.removeChild != 'undefined') {

      while (element.hasChildNodes()) {
        element.removeChild(element.lastChild);
      }

      element.appendChild(document.createTextNode(text));
    }
  }
}


acheter viagra en ligne and viagra vente
// desc of this that
kamagra

Grep Rails log file targeting particular client/action

#!/usr/bin/env ruby

if ARGV.empty?
  puts <<-USAGE
Use like tail -f log/production.log | #{ $PROGRAM_NAME } request_regexp

Examples:

Show only local requests:
tail -f log/production.log | #{ $PROGRAM_NAME } 127.0.0.1

Show only GET requests:
tail -f log/production.log | #{ $PROGRAM_NAME } GET

Show only requests to /updates path:
tail -f log/production.log | #{ $PROGRAM_NAME } /updates
  USAGE
  exit(0)
end

request_regexp = /#{ ARGV[0] }/

STDIN.slice_before(/Started (GET|POST|PUT|DELETE)/).each do |request_log|
  puts request_log if request_log.first =~ request_regexp
end


kamagra vente
kamagra sans ordonnance
// desc of this that
cialis acheter en ligne and cialis suisse

Apache IP2Location

// description of your code here

static const int ENV_SET_MODE    = 0x0001;
static const int NOTES_SET_MODE  = 0x0002;
static const int ALL_SET_MODE    = 0x0003;

typedef struct {
                int enableFlag;
                int setMode; 
                char* dbFile;
                IP2Location* ip2locObj;
} ip2location_server_config;

module AP_MODULE_DECLARE_DATA IP2Location_module;

static apr_status_t ip2location_cleanup(void *cfgdata) {
   // cleanup code here, if needed
   return APR_SUCCESS;
}

static void ip2location_child_init(apr_pool_t *p, server_rec *s) {
   apr_pool_cleanup_register(p, NULL, ip2location_cleanup, ip2location_cleanup);
}

static int ip2location_post_read_request(request_rec *r) {
                char* ipaddr;
                ip2location_server_config* config;
                IP2LocationRecord* record;
                char buff[20];
                
                config = (ip2location_server_config*)
                                                                                               ap_get_module_config(r->server->module_config, &IP2Location_module);
                
                if(!config->enableFlag)
                                return OK;
                
                ipaddr = r->connection->remote_ip;
                record = IP2Location_get_all(config->ip2locObj, ipaddr);
                if(record) {
                                if(config->setMode & ENV_SET_MODE) {
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_COUNTRY_SHORT", record->country_short); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_COUNTRY_LONG", record->country_long); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_REGION", record->region); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_CITY", record->city); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_ISP", record->isp); 
                                                sprintf(buff, "%f", record->latitude);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_LATITUDE", buff); 
                                                sprintf(buff, "%f", record->longitude);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_LONGITUDE", buff); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_DOMAIN", record->domain); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_ZIPCODE", record->zipcode); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_TIMEZONE", record->timezone); 
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_NETSPEED", record->netspeed);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_IDDCODE", record->iddcode);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_AREACODE", record->areacode);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_WEATHERSTATIONCODE", record->weatherstationcode);
                                                apr_table_set(r->subprocess_env, "IP2LOCATION_WEATHERSTATIONNAME", record->weatherstationname);
                                }
                                if(config->setMode & NOTES_SET_MODE) {
                                                apr_table_set(r->notes, "IP2LOCATION_COUNTRY_SHORT", record->country_short); 
                                                apr_table_set(r->notes, "IP2LOCATION_COUNTRY_LONG", record->country_long); 
                                                apr_table_set(r->notes, "IP2LOCATION_REGION", record->region); 
                                                apr_table_set(r->notes, "IP2LOCATION_CITY", record->city); 
                                                apr_table_set(r->notes, "IP2LOCATION_ISP", record->isp); 
                                                sprintf(buff, "%f", record->latitude);
                                                apr_table_set(r->notes, "IP2LOCATION_LATITUDE", buff); 
                                                sprintf(buff, "%f", record->longitude);
                                                apr_table_set(r->notes, "IP2LOCATION_LONGITUDE", buff); 
                                                apr_table_set(r->notes, "IP2LOCATION_DOMAIN", record->domain); 
                                                apr_table_set(r->notes, "IP2LOCATION_ZIPCODE", record->zipcode); 
                                                apr_table_set(r->notes, "IP2LOCATION_TIMEZONE", record->timezone); 
                                                apr_table_set(r->notes, "IP2LOCATION_NETSPEED", record->netspeed);
                                                apr_table_set(r->notes, "IP2LOCATION_IDDCODE", record->iddcode);
                                                apr_table_set(r->notes, "IP2LOCATION_AREACODE", record->areacode);
                                                apr_table_set(r->notes, "IP2LOCATION_WEATHERSTATIONCODE", record->weatherstationcode);
                                               apr_table_set(r->notes, "IP2LOCATION_WEATHERSTATIONNAME", record->weatherstationname);
                                }
                
                                IP2Location_free_record(record);                           
                }
                
                return OK;
}

static const char* set_ip2location_enable(cmd_parms *cmd, void *dummy, int arg) {
                ip2location_server_config* config = (ip2location_server_config*)
                                                                                                                                                                                                                                                                                                                ap_get_module_config(cmd->server->module_config, &IP2Location_module);
  if(!config) 
                return NULL;
  
  config->enableFlag = arg;
  return NULL;
}

static const char* set_ip2location_dbfile(cmd_parms* cmd, void* dummy, const char* dbFile, int arg) {
  ip2location_server_config* config = (ip2location_server_config*)
                                                                                                                                                                                                                                                                                                ap_get_module_config(cmd->server->module_config, &IP2Location_module);
                if(!config) 
                                return NULL;
                                
                config->dbFile = apr_pstrdup(cmd->pool, dbFile);
                if(config->enableFlag) {
                                config->ip2locObj = IP2Location_open(config->dbFile); 
                                if(!config->ip2locObj)
                                                return "Error opening dbFile!";
                }
                
                return NULL; 
}

static const char* set_ip2location_set_mode(cmd_parms* cmd, void* dummy, const char* mode, int arg) {
                ip2location_server_config* config = (ip2location_server_config*)
                                                                                                                                                                                                                                                                                                ap_get_module_config(cmd->server->module_config, &IP2Location_module);
                if(!config) 
                                return NULL;
                
                if(strcmp(mode, "ALL") == 0)      
                                config->setMode = ALL_SET_MODE;
                else if(strcmp(mode, "ENV") == 0)           
                                config->setMode = ENV_SET_MODE;
                else if(strcmp(mode, "NOTES") == 0)
                                config->setMode = NOTES_SET_MODE;                
                else
                                return "Invalid mode for IP2LocationSetMode";
                
                return NULL; 
}

static void* ip2location_create_svr_conf(apr_pool_t* pool, server_rec* svr) {
  ip2location_server_config* svr_cfg = apr_pcalloc(pool, sizeof(ip2location_server_config));
                svr_cfg->enableFlag = 0;
                svr_cfg->dbFile = NULL;
                svr_cfg->setMode = ALL_SET_MODE;
                svr_cfg->ip2locObj = NULL;
  return svr_cfg ;
}

static const command_rec ip2location_cmds[] = {
   AP_INIT_FLAG( "IP2LocationEnable", set_ip2location_enable, NULL, OR_FILEINFO, "Turn on mod_ip2location"),
   AP_INIT_TAKE1( "IP2LocationDBFile", set_ip2location_dbfile, NULL, OR_FILEINFO, "File path to DB file"),
   AP_INIT_TAKE1( "IP2LocationSetMode", set_ip2location_set_mode, NULL, OR_FILEINFO, "Set scope mode"),
   {NULL} 
};

static void ip2location_register_hooks(apr_pool_t *p) {
                ap_hook_post_read_request( ip2location_post_read_request, NULL, NULL, APR_HOOK_MIDDLE );
                ap_hook_child_init(        ip2location_child_init, NULL, NULL, APR_HOOK_MIDDLE );

}

// API hooks
module AP_MODULE_DECLARE_DATA IP2Location_module = {
   STANDARD20_MODULE_STUFF, 
   NULL,                        /* create per-dir    config structures */
   NULL,                        /* merge  per-dir    config structures */
   ip2location_create_svr_conf, /* create per-server config structures */
   NULL,                        /* merge  per-server config structures */
   ip2location_cmds,            /* table of config file commands       */
   ip2location_register_hooks   /* register hooks                      */
};




Deep' in Ruby

// description of your code here

#!/usr/local/bin/ruby

##!/opt/local/bin/ruby1.9

# Update Ruby via MacPorts:
# port info ruby19
# sudo port install ruby19


# See:
# - Tailin' Ruby, http://judofyr.net/posts/tailin-ruby.html
# - Re: Ruby and recursion (Ackermann benchmark), http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/145593

class Class
  # Sweet stuff!
  def tailcall_optimize( *methods )
    methods.each do |meth|
      org = instance_method( meth )
      define_method( meth ) do |*args|
        if Thread.current[ meth ]
          throw( :recurse, args )
        else
          Thread.current[ meth ] = org.bind( self )
          result = catch( :done ) do
            loop do
              args = catch( :recurse ) do
                throw( :done, Thread.current[ meth ].call( *args ) )
              end
            end
          end
          Thread.current[ meth ] = nil
          result
        end
      end
    end
  end
end



# tail-call optimization test

# example 1

class TCOTest
  # tail-recursive factorial
  def fact( n, acc = 1 )
    if n < 2 then acc else fact( n-1, n*acc ) end
  end

  # length of factorial
  def fact_size( n )
    fact( n ).size
  rescue
    $!
  end   
end

t = TCOTest.new

# normal method
puts t.fact_size( 10000 )  # => stack level too deep

# enable tail-call optimization
class TCOTest
  tailcall_optimize :fact
end

# tail-call optimized method
puts t.fact_size( 10000 )  # => 14808                                  


# example 2

class TCOTest2
   def addnum(i) 
      p i
      addnum(i+1) 
   end
end


#TCOTest2.new.addnum 0   # stack level too deep (SystemStackError)

# enable tail-call optimization
class TCOTest2
  tailcall_optimize :addnum
end

TCOTest2.new.addnum 0

Selected Code

// description of your code here

/// <summary>
    /// Selected Items Facade
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Selected<T>
    {
        /// <summary>
        /// Gets selected items as T from the specified list box.
        /// </summary>
        /// <param name="listBox">The list box.</param>
        /// <returns></returns>
        public static IEnumerable<T> From(ListBox listBox)
        {
            List<T> result = new List<T>();

            foreach (T item in listBox.SelectedItems)
            {
                result.Add(item);
            }

            return result;
        }

        /// <summary>
        /// Gets selected item as T from the specified combo box.
        /// </summary>
        /// <param name="comboBox">The combo box.</param>
        /// <returns></returns>
        public static T From(ComboBox comboBox)
        {
            return comboBox.SelectedIndex > -1
                       ? (T) comboBox.Items[comboBox.SelectedIndex]
                       : default(T);
        }
    }

To aligh text in SVG apply the text-align style within the text style attribute

// description of your code here

<g
   inkscape:label="Layer 1"
   inkscape:groupmode="layer"
   id="layer1">
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="57.362206" />
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="76.981842"
     id="text2884-8"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0"
       x="94.043755"
       y="76.981842">text07</tspan></text>
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-3"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="83.013474" />

  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-5"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="108.6647" />
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-1"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="134.31596" />
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="102.34161"
     id="text2884-8-1"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0-3"
       x="94.043755"
       y="102.34161">text07</tspan></text>
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:end;line-height:125%;writing-mode:lr-tb;text-anchor:end;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="127.70137"
     id="text2884-8-3"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0-2"
       x="94.043755"
       y="127.70137">text07</tspan></text>
</g>

Private IP Detection

// description of your code here

Extending IPAddr:

require 'ipaddr'
class IPAddr
  PrivateRanges = [
    IPAddr.new("10.0.0.0/8"),
    IPAddr.new("172.16.0.0/12"),
    IPAddr.new("192.168.0.0/16")
  ]
  
  def private?
    return false unless self.ipv4?
    PrivateRanges.each do |ipr|
      return true if ipr.include?(self)
    end
    return false
  end

  def public?
    !private?
  end
end



TestCase:

require 'ipaddr'

class IpResolutionTest < Test::Unit::TestCase
  def ip(ipaddr)
    IPAddr.new(ipaddr)
  end
  
  def self.should_be_public_ip(ip)
    should "identify #{ip} as being public" do
      ip(ip).should be_public
    end
  end

  def self.should_be_private_ip(ip)
    should "identify #{ip} as being private" do
      ip(ip).should be_private
    end
  end
  
  context "Ip Resolution" do
    should_be_public_ip "9.255.255.255"
    should_be_public_ip "11.0.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "10.#{r1*50}.#{r2*50}.10"
      end
    end

    should_be_public_ip "172.15.255.255"
    should_be_public_ip "172.32.0.0"

    (16..31).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "172.#{r1}.#{r2*50}.10"
      end
    end

    should_be_public_ip "192.167.255.255"
    should_be_public_ip "192.169.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "192.168.#{r1*50}.#{r2*50}"
      end
    end
  end
end