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
  • submit to reddit
        // GStreamer Pipeline for ripping MP3s

audio/x-raw-int,rate=44100,channels=2 ! lame name=enc vbr=4 vbr-quality=2 ! xingmux ! id3v2mux
    
        Some simple S3 utils in Ruby

Specifically written to copy one bucket to another (for testing on production on staging)

PLEASE BE CAREFUL WITH THIS - THERE IS CODE THAT DELETES ALL CONTENTS OF A BUCKET

Example:
a = AmazoneS3Asset.new
a.copy_over_bucket("myapp_production", "myapp_production")

require 'aws/s3'
require 'mechanize'

class AmazonS3Asset
  
  include AWS::S3
  S3ID = "your s3 id"
  S3KEY = "your s3 key"
  
  def initialize
    puts "connecting..."
    AWS::S3::Base.establish_connection!(
      :access_key_id     => S3ID,
      :secret_access_key => S3KEY
    )
  end

  def delete_key(bucket, key)
    if exists?(bucket, key) 
      S3Object.delete key, bucket
    end
  end
  
  def empty_bucket(bucket)
    bucket_keys(bucket).each do |k|
      puts "deleting #{k}"
      delete_key(bucket,k)
    end
  end
  
  def bucket_keys(bucket)
    b = Bucket.find(bucket)
    b.objects.collect {|o| o.key}
  end

  def copy_over_bucket(from_bucket, to_bucket)
    puts "Replacing #{to_bucket} with contents of #{from_bucket}"
    #delete to_bucket
    empty_bucket(to_bucket)
    bucket_keys(from_bucket).each do |k|
      copy_between_buckets(from_bucket, to_bucket, k)
    end
  end
  
  def copy_between_buckets(from_bucket, to_bucket, from_key, to_key = nil)
    if exists?(from_bucket, from_key)
      to_key = from_key if to_key.nil?
      puts "Copying #{from_bucket}.#{from_key} to #{to_bucket}.#{to_key}"
      url = "http://s3.amazonaws.com/#{from_bucket}/#{from_key}"
      filename = download(url)
      store_file(to_bucket,to_key,filename)
      File.delete(filename)
      return "http://s3.amazonaws.com/#{to_bucket}/#{to_key}"
    else
      puts "#{from_bucket}.#{from_key} didn't exist"
      return nil
    end
  end

  def store_file(bucket, key, filename)
     puts "Storing #{filename} in #{bucket}.#{key}"
     S3Object.store(
      key,
      File.open(filename),
      bucket,
      :access => :public_read
      )
  end

  def download(url, save_as = nil)
    if save_as.nil?
      Dir.mkdir("amazon_s3_temp") if !File.exists?("amazon_s3_temp")
      save_as = File.join("amazon_s3_temp",File.basename(url))
    end
    begin
      puts "Saving #{url} to #{save_as}"
      agent = WWW::Mechanize.new {|a| a.log = Logger.new(STDERR) }
      img = agent.get(url)
      img.save_as(save_as)
      return save_as
    rescue
      raise "Failed on " + url + "  " + save_as
    end
  end

  def exists?(bucket,key)
    begin
      res = S3Object.find key, bucket
    rescue 
      res = nil
    end
    return !res.nil?
  end
      
end
    
        This is a way to merge two arrays into one hash.
The returned hash will have the same quantity of elements that the first(self) array. 

class Array
 def merge_into_hash(anArray)
  tmp,hash = anArray.dup,{}
  self.each {|key| hash[key] = tmp.shift}
  hash
 end
end    
        Format an IPv4 address like 192.168.1.1 in dotted binary format like 11000000.10101000.00000001.00000001
You also need this class: http://snippets.dzone.com/posts/show/2472
For Rails: Put this in your controller!


  # convert a dotted decimal IPv4 address to dotted binary format
  def ipv4_to_binary(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_i.to_s(2).using("########","0",true)
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end
  
  
  # convert a IPv4 adress in binary dotted format to a dotted IPv4 address
  def binary_to_ipv4(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_s.to_i(2).to_s
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end
    
        

# From: http://www.ruby-forum.com/topic/135807
# Author: Nobuyoshi Nakada

class Hash
   def collate(h)
      raise ArgumentError unless h.is_a?(Hash)
      update(h) { |key, *values| values }
      #update(h) { |key, *values| values.flatten.uniq }
   end
end

h1 = {:a=>1, :b=>2 }
h2 = {:a=>3, :b=>4, :c=>5}
h1.collate(h2)
p h1, h2     
#=> {:b=>[2, 4], :a=>[1, 3], :c=>5}
#=> {:b=>4, :a=>3, :c=>5}

puts
h1 = {:a=>1, :b=>2 }
h2 = {:a=>3, :b=>4, :c=>5}
h2.collate(h1)
p h1, h2     
#=> {:b=>2, :a=>1}
#=> {:b=>[4, 2], :a=>[3, 1], :c=>5}


    
        คาดว่ามันใช้ในการ encapsulate โค้ดมั้ง

var t = (function(){
    var plus = function(a, b){
                    return a + b;
                };
    return function(i, j){
                return plus(i, j);
            }
})();
t(1, 2);
    
        // description of your code here

<!-- 定义一个key name, 这个key name 在运行时指向当前web app的根目录 --->
  <context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>petstore.root</param-value>
  </context-param>
  <!-- 定义一个log4j 配置文件的路径名称 -->
  <context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/log4j.properties</param-value>
  </context-param>
  <!-- 使用listener 配置 log4j  -->
  <listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
    
        // description of your code here

   1. 各种数据库的JDBC连接大全  
   2. Microsoft SQL Server series (6.5, 7.x and 2000) and Sybase 10  
   3.   
   4. JDBC Name: jTDS  
   5. URL: http://jtds.sourceforge.net/  
   6. Version: 0.5.1  
   7. Download URL: http://sourceforge.net/project/showfiles.php?group_id=33291  
   8.   
   9. 语法:   
  10. Class.forName("net.sourceforge.jtds.jdbc.Driver ");  
  11. Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://host:port/database","user","password");  
  12. or  
  13. Connection con = DriverManager.getConnection("jdbc:jtds:sybase://host:port/database","user","password");  
  14.   
  15. MySQL  
  16.   
  17. JDBC Name: Connector/J 3.0  
  18. URL: http://www.mysql.com/  
  19. Version: 3.0.8-stable  
  20. Download URL: http://www.mysql.com/downloads/api-jdbc-stable.html  
  21.   
  22. 语法:  
  23. Download URL: http://www.mysql.com/downloads/api-jdbc-stable.html  
  24.   
  25. 语法:   
  26. Class.forName("com.mysql.jdbc.Driver");  
  27. Connection con = DriverManager.getConnection("jdbc:mysql://host:port/database","user","password");  
  28.   
  29. Oracle  
  30.   
  31. JDBC Name: Connector/J 3.0  
  32. URL: http://otn.oracle.com/  
  33. Version: 3.0.8-stable  
  34. Download URL: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html  
  35.   
  36. 语法:  
  37. Download URL: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html  
  38.   
  39. 语法:   
  40. Class.forName("oracle.jdbc.driver.OracleDriver");  
  41. Connection con = DriverManager.getConnection("jdbc:oracle:thin:@host:port:databse","user","password");  
  42.   
  43. Sybase  
  44.   
  45. Driver: jConnect 4.5/5.5 (JDBC 2.0 请使用5.5)   
  46.   
  47. 语法:  
  48.   
  49. Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();  
  50. DriverManager.getConnection("jdbc:sybase:Tds:IP地址:2638?ServiceName="+数据库名称,"账号","密码");  
  51.   
  52. Postgresql  
  53.   
  54. JDBC Name: PostgreSQL JDBC  
  55. URL: http://jdbc.postgresql.org/  
  56. Version: 7.3.3 build 110  
  57. Download URL: http://jdbc.postgresql.org/download.html  
  58.   
  59. 语法:  
  60. Download URL: http://jdbc.postgresql.org/download.html  
  61.   
  62. 语法:   
  63. Class.forName("org.postgresql.Driver");   
  64. Connection con=DriverManager.getConnection("jdbc:postgresql://host:port/database","user","password");  
  65.   
  66. IBM AS400主机在用的JDBC语法  
  67.   
  68. 有装V4R4以上版本的Client Access Express  
  69. 可以在C:Program FilesIBMClient Accessjt400lib  
  70. 找到 driver 档案 jt400.zip,并更改扩展名成为 jt400.jar  
  71.   
  72. 语法语法:  
  73. Class.forName("net.sourceforge.jtds.jdbc.Driver ");  
  74. Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://host:port/database","user","password");  
  75. or  
  76. Connection con = DriverManager.getConnection("jdbc:jtds:sybase://host:port/database","user","password");  
  77.   
  78. MySQL  
  79.   
  80. JDBC Name: Connector/J 3.0  
  81. URL: http://www.mysql.com/  
  82. Version: 3.0.8-stable  
  83. Download URL: http://www.mysql.com/downloads/api-jdbc-stable.html  
  84.   
  85. 语法:  
  86. Download URL: http://www.mysql.com/downloads/api-jdbc-stable.html  
  87.   
  88. 语法:   
  89. Class.forName("com.mysql.jdbc.Driver");  
  90. Connection con = DriverManager.getConnection("jdbc:mysql://host:port/database","user","password");  
  91.   
  92. Oracle  
  93.   
  94. JDBC Name: Connector/J 3.0  
  95. URL: http://otn.oracle.com/  
  96. Version: 3.0.8-stable  
  97. Download URL: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html  
  98.   
  99. 语法:  
 100. Download URL: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html  
 101.   
 102. 语法:   
 103. Class.forName("oracle.jdbc.driver.OracleDriver");  
 104. Connection con = DriverManager.getConnection("jdbc:oracle:thin:@host:port:databse","user","password");  
 105.   
 106. Sybase  
 107.   
 108. Driver: jConnect 4.5/5.5 (JDBC 2.0 请使用5.5)   
 109.   
 110. 语法:  
 111.   
 112. Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();  
 113. DriverManager.getConnection("jdbc:sybase:Tds:IP地址:2638?ServiceName="+数据库名称,"账号","密码");  
 114.   
 115. Postgresql  
 116.   
 117. JDBC Name: PostgreSQL JDBC  
 118. URL: http://jdbc.postgresql.org/  
 119. Version: 7.3.3 build 110  
 120. Download URL: http://jdbc.postgresql.org/download.html  
 121.   
 122. 语法:  
 123. Download URL: http://jdbc.postgresql.org/download.html  
 124.   
 125. 语法:   
 126. Class.forName("org.postgresql.Driver");   
 127. Connection con=DriverManager.getConnection("jdbc:postgresql://host:port/database","user","password");  
 128.   
 129. IBM AS400主机在用的JDBC语法  
 130.   
 131. 有装V4R4以上版本的Client Access Express  
 132. 可以在C:Program FilesIBMClient Accessjt400lib  
 133. 找到 driver 档案 jt400.zip,并更改扩展名成为 jt400.jar  
 134.   
 135. 语法  
 136. java.sql.DriverManager.registerDriver (new com.ibm.as400.access.AS400JDBCDriver ());  
 137. Class.forName("com.ibm.as400.access.AS400JDBCConnection");  
 138. con = DriverManager.getConnection("jdbc:as400://IP","user","passwor");   
 139.   
 140. 1.Oracle8/8i/9i数据库(thin模式)  
 141. Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();   
 142. String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID   
 143. String user="test";   
 144. String password="test";   
 145. Connection conn= DriverManager.getConnection(url,user,password);  
 146. 2.DB2数据库  
 147. Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance();   
 148. String url="jdbc:db2://localhost:5000/sample"; //sample为你的数据库名   
 149. String user="admin";   
 150. String password="";   
 151. Connection conn= DriverManager.getConnection(url,user,password);  
 152. 3.Sql Server7.0/2000数据库  
 153. Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();   
 154. String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";   
 155. //mydb为数据库   
 156. String user="sa";   
 157. String password="";   
 158. Connection conn= DriverManager.getConnection(url,user,password);  
 159. 4.Sybase数据库  
 160. Class.forName("com.sybase.jdbc.SybDriver").newInstance();   
 161. String url =" jdbc:sybase:Tds:localhost:5007/myDB";//myDB为你的数据库名   
 162. Properties sysProps = System.getProperties();   
 163. SysProps.put("user","userid");   
 164. SysProps.put("password","user_password");   
 165. Connection conn= DriverManager.getConnection(url, SysProps);  
 166. 5.Informix数据库  
 167. Class.forName("com.informix.jdbc.IfxDriver").newInstance();   
 168. String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;  
 169. user=testuser;password=testpassword"; //myDB为数据库名   
 170. Connection conn= DriverManager.getConnection(url);  
 171. 6.MySQL数据库  
 172. Class.forName("org.gjt.mm.mysql.Driver").newInstance();   
 173. String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"   
 174. //myDB为数据库名   
 175. Connection conn= DriverManager.getConnection(url);  
 176. 7.PostgreSQL数据库  
 177. Class.forName("org.postgresql.Driver").newInstance();   
 178. String url ="jdbc:postgresql://localhost/myDB" //myDB为数据库名   
 179. String user="myuser";   
 180. String password="mypassword";   
 181. Connection conn= DriverManager.getConnection(url,user,password);  
 182. 8.access数据库直连用ODBC的  
 183. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;  
 184. String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb");  
 185. Connection conn = DriverManager.getConnection(url,"","");  
 186. Statement stmtNew=conn.createStatement() ;  
    
        A simple method that returns the current user and caches the result to reduce database hits.  This assumes you're storing user information in User and that the current user is identified by the session variable user_id.
class ApplicationController < ActionController::Base
  def current_user
    session[:user_id] ? @current_user ||= User.find(session[:user_id]) : nil
  end
end
    
        // Python Motion Detection Library + Demo
// 3 files (1 lib, 1 demo, 1 misc)
// Demo is win32-only because of win32 only library for webcam access (easily changeable)
// Can be used for eyetoy or wiimote (IR emitter+wireless mouse hack) like input

#######
#FILE 1: LIBRARY motion.py
#######
# -*- coding: cp1252 -*-
####################################
#MOTION: compare images for change#
####################################
# Copyright (C) 2007 Erol Baykal
# License: GPL
#AUTHOR:
#   Baykal Erol
#   erol@baykal.be
#   baykal.erol@gmail.com
#
#LAST UPDATED 6 SEP 07
#Version: RC1
##################################

#MODULES
########
import Image, ImageDraw, pygame
from math import fabs, sqrt, pi, atan2

#FUNCTIONS
##########

"""
getMotionArray returns an array containing the (pixelwise) X-Y coordinates of the difference between the two compared images
If the two images are identical an empty array will be returned.
"""
def getMotionArray(image1, image2, threshold = 10):
    i1 = image1
    i2 = image2
    #both images need to be the same size in pixels
    if (i1.size[0] != i2.size[0]) or (i1.size[1] != i2.size[1]):
        return 0 #if not, we return 0
    size = i1.size

    imgArr1 = list(i1.getdata())
    imgArr2 = list(i2.getdata())

    t = threshold
    motionarray = [] #2D array to store motion areas

    i=0
    while i < len(imgArr1): #scan through the images
            p1 = imgArr1[i]
            p2 = imgArr2[i]

            if (fabs(p1[0]-p2[0]) > t) or (fabs(p1[1]-p2[1]) > t) or (fabs(p1[2]-p2[2]) > t): #compare each pixel in R,G,B channel
                    y = i/size[0]
                    x = i - y*size[0]
                    motionarray.append((x,y))

            i = i+1
 
    return motionarray

def getMotionArrayRGB(image1, image2, threshold = 10):
    i1 = image1
    i2 = image2
    #both images need to be the same size in pixels
    if (i1.size[0] != i2.size[0]) or (i1.size[1] != i2.size[1]):
        return 0 #if not, we return 0
    size = i1.size

    imgArr1 = list(i1.getdata())
    imgArr2 = list(i2.getdata())

    t = threshold
    motionarray = [] #2D array to store motion areas

    i=0
    while i < len(imgArr1): #scan through the images
            p1 = imgArr1[i]
            p2 = imgArr2[i]

            if (fabs(p1[0]-p2[0]) > t) or (fabs(p1[1]-p2[1]) > t) or (fabs(p1[2]-p2[2]) > t): #compare each pixel in R,G,B channel
                    y = i/size[0]
                    x = i - y*size[0]
                    motionarray.append((x,y,p2))

            i = i+1
 
    return motionarray

"""
getMotionPoint returns the avarage point of all the motion.
It does this by calculating the medial point for a motion array from getMotionArray
To normalise this point divide pX/imageSizeX and pY/imageSizeY
"""
def getMotionPoint(array):
    area = array
    i=0
    pX = 0
    pY = 0
    point=(-1,-1)
    while i < len(area):    
        pX = pX+area[i][0]
        pY = pY+area[i][1]
        i = i+1
    if i > 0:
        point = (float(pX)/i,float(pY)/i)
    return point

def getAvgColor(array):
    area = array
    i=0
    R = 0
    G = 0
    B = 0
    while i < len(area):    
        R = R+area[i][2][0]
        G = G+area[i][2][1]
        B = B+area[i][2][2]
        i = i+1
    if i > 0:
        color = (int(R/i),int(G/i),int(B/i))
    return color
"""
By examining motion points from two consecutive frames we can detect swing motions.
Swing motions occur when there is enough distance between points
"""
def getSwingMotion(point1, point2, treshold=2):
    p1 = point1
    p2 = point2
    #PYTHAGORAS :) A² = B²+C²
    B = p1[0] - p2[0]
    C = p1[1] - p2[1]
    A = sqrt((B*B)+(C*C))

    if A > treshold:
        magnitude = A
        vector = (B,C) #vector
        heading = atan2(B,C)*180/pi
        return (magnitude,vector,heading)
    else:
        return 0
"""
Splits coordinates into groups, where each group consists of adjecent coordinates
Receives an array of coordinates ([(x,y),(x,y)]) and retuns an array of array of coordinates ([[(x,y),(x,y)],[(x,y),(x,y)]])
"""
def splitGroups(arr):
    arrGroups= []
    while len(arr) > 1:
        temparr=[arr[0]]
        i = 0
        arr.remove(temparr[0]) #bite off the head of the array ^^
        while i < len(temparr):
            t = checkNeighbours(temparr[i], arr)
            if t:
                for co in t:
                    temparr.append(co)
                    arr.remove(co)
            i=i+1
        arrGroups.append(temparr)
    return arrGroups

"""
takes a coordinate and an array of coordinates. If any neighbouring coordinates of the given coordinate are found in the array, they are returned 
"""
def checkNeighbours(co,arr):
    temp = []
    x = co[0]
    y = co[1]
    neighbours = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)]
    for i in arr:
        if (i[0],i[1]) in neighbours:
            temp.append(i)
            
    if len(temp) > 0:
        return temp
    else:
        return 0
    
    
#DEPRECATED

def getMotionArrayOLD(image1, image2, threshold = 10):
    i1 = image1
    i2 = image2
    #both images need to be the same size in pixels
    if (i1.size[0] != i2.size[0]) or (i1.size[1] != i2.size[1]):
        return 0 #if not, we return 0
    size = i1.size

    t = threshold
    motionarray = [] #2D array to store motion areas

    i=0
    while i in range(size[1]): #scan through the images
        j=0
        while j in range(size[0]):
            p1 = i1.getpixel((j,i))
            p2 = i2.getpixel((j,i))

            if (fabs(p1[0]-p2[0]) > t) or (fabs(p1[1]-p2[1]) > t) or (fabs(p1[2]-p2[2]) > t): #compare each pixel in R,G,B channel
                    motionarray.append((j,i))

            j = j+1
        i = i+1
 
    return motionarray



def getMotionArrayRGBOLD(image1, image2, treshold = 10):
    i1 = image1
    i2 = image2
    #both images need to be the same size in pixels
    if (i1.size[0] != i2.size[0]) or (i1.size[1] != i2.size[1]):
        return 0 #if not, we return 0
    size = i1.size

    t = treshold
    motionarray = [] #2D array to store motion areas

    i=0
    while i in range(size[1]): #scan through the images
        j=0
        while j in range(size[0]):
            p1 = i1.getpixel((j,i))
            p2 = i2.getpixel((j,i))

            if (fabs(p1[0]-p2[0]) > t) or (fabs(p1[1]-p2[1]) > t) or (fabs(p1[2]-p2[2]) > t): #compare each pixel in R,G,B channel
                    motionarray.append((j,i,p2))#by deducting these values we mirror the coordinates to mimick a mirror-image
                                          #also return p2; the RGB value for the pixel from the second (newer) image
            j = j+1
        i = i+1
 
    return motionarray

def compare(image1, image2, treshold = 10, showPixels=0):

    #showPixels
    #   if 0: returns bunding box ((x1,y1),(x2,y2)) encompassing all motion
    #   if 1: returns motion mask:
    #       white image with same dimensions of supplied images, where motion areas are marked with a color
    #   if 2: returns motion mask:
    #       white image with same dimensions as supplied images, where motion areas are real pixels of supplied images
    #   if 3: returns motion array:
    #       an array of points, each representing an area of motion on the images
    #images need to have same dimensions
    i1 = image1
    i2 = image2
    #if not, we return 0
    if (i1.size[0] != i2.size[0]) or (i1.size[1] != i2.size[1]):
        return 0
    size = i1.size

    t = treshold

    #2D array to store motion areas
    motionarray = []
    
    #new empty image for motionmask, only create if motion mask is needed
    if (showPixels == 1) or (showPixels == 2):
        ni = Image.new("RGB",i1.size,(0,0,0))
        draw = ImageDraw.Draw(ni)
    
    i=0

    #variables for second boundingbox system
    first = 1
    lX = 0
    hX = 0
    lY = 0
    hY = 0
    while i in range(size[1]):
        j=0
        while j in range(size[0]):
            p1 = i1.getpixel((j,i))
            p2 = i2.getpixel((j,i))

            if (fabs(p1[0]-p2[0]) > t) or (fabs(p1[1]-p2[1]) > t) or (fabs(p1[2]-p2[2]) > t):
                if showPixels == 1:              
                    ni.putpixel((j,i),(255,0,0))
                elif showPixels == 2:
                    ni.putpixel((j,i),p2)
                elif showPixels == 3:
                    motionarray.append((j,i))
                else:
                    if first:
                        lX = j
                        lY = i
                        first = 0
                    if j < lX:
                        lX = j
                    if j > hX:
                        hX = j
                    if i < lY:
                        lY = i
                    if i > hY:
                        hY = i
            j = j+1
        i = i+1
 
    area =  ((lX,lY),(hX,hY))

    if showPixels == 1:
        del draw
        return ni
    elif showPixels == 2:
        del draw
        return ni
    elif showPixels == 3:
        return motionarray
    else:
        return area

#######
#FILE 2: BASIC IR-DEMO (hack an IR-webcam and IR emitter for optimal experience)
#######
##################################
#BASIC DEMO:
#Demonstrates basic ability of IRM: get motion data and translate it into motion point coordinates
##################################
# Copyright (C) 2007 Erol Baykal
# License: GPL
#ONLY WORKS ON WINDOWS, this is due to videocapture being windows 32 only
#NEEDS:
#   PIL (python image library http://www.pythonware.com/products/pil/)
#   Pygame (http://www.pygame.org/)
#   Videocapture (http://videocapture.sourceforge.net/)
#   Psyco (http://psyco.sourceforge.net/)
#AUTHOR:
#   Baykal Erol (erol@baykal.be)
#LAST UPDATE: 6 SEP 07
##################################
#
#MODULES
########
import Image, ImageDraw, motion, time, pygame, sys, random, psyco, performance
from VideoCapture import Device

#GLOBAL VARIABLES
#################
#options
########
FULLSCREEN = 1
COLORTHRESHOLD = 60 #color threshold for motion detection, the higher the more strict (avg. 50 is ok)
SIZE = 320,240 # resolution of the screen (and camera, but can be seperated), needs to be 4/3 (I think)
CSIZE = 160,120 #compressed size, needs to be 4/3 (widescreen hack?)

#init vars
##########
psyco.full() #PSYCO speeds up python
pygame.init() #We need to initialize pygame early on, so that certain stuff works (loading sound..)
ratio = SIZE[0]/CSIZE[0] #ratio of compression
fps = performance.FpsMeter() #an FPS meter
font = pygame.font.Font(None, 36) #a font for writing :)

#select cam and set resolution
cam = Device(devnum=0)
cam.setResolution(SIZE[0],SIZE[1])

#the pygame screen
if FULLSCREEN:
    screen = pygame.display.set_mode(SIZE, pygame.FULLSCREEN)
else:
    screen = pygame.display.set_mode(SIZE)
    
#new empty images, we will be using them in the main loop
#ni = newest image
#nci = newest compressed image
#oci = older compressed image
cci = Image.new("RGB",CSIZE,(255,255,255))
ni = Image.new("RGB",SIZE,(255,255,255))
oci = cci

tracklist = [(10,10)]

#a new surface the size of our window, will serve as a bg
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))


#################################################
#MAIN LOOP
##########
do = 1
while do:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           do = 0
           del cam
           sys.exit()
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
           do = 0
           del cam
           sys.exit()
    #Get the images
    ###############
    #oci and nci are used for motion detection, they don't show up on screen
    #if you want to show something use ni
    oci = cci #make the current compressed image the old one
    ni = cam.getImage() #get new image for compression
    ni = ni.transpose(Image.FLIP_LEFT_RIGHT) #Flip image for mirror movement, this way topleft == (0,0)
    cci = ni.resize(CSIZE,Image.BILINEAR) #compress the new image and make it the current one

    #Get motion from images
    #######################
    motionArray = motion.getMotionArray(oci,cci,COLORTHRESHOLD) #compare the images and get the array of pixels with difference
    motionPoint = motion.getMotionPoint(motionArray) #calculate the avarage point
    if motionPoint[0] > 0 and motionPoint[1] > 0: #chek X and Y values
        #if a real avarage point of motion has been returned
        wp = motionPoint
        px = wp[0]*ratio #multiply by compression ratio to get the position
        py = wp[1]*ratio #of the coordinate on the uncompressed image
        wp = (px,py)

        if len(tracklist) < 240: #we keep track of some frames' avarage points
           tracklist.append(wp)
        else:
           tracklist.pop(0)
           tracklist.append(wp)

    #Draw everything
    #################
    background.fill((255,255,255)) #clear the background
    pygame.draw.lines(background, (0,255,0), 0, tracklist)
    screen.blit(background,(0,0))
    txtFPS = font.render(str(fps.go()), 1, (100, 100, 100))
    screen.blit(txtFPS, (10,10))
    pygame.display.flip()

del screen # delete the screen
pygame.quit()
del cam #delete the cam on exit of loop


#######
#FILE 3: performance.py
#######
import time

class FpsMeter:
    def __init__(self):
        self.boundary = time.time()
        self.count = 0;
        self.returned = 0
        
    def go(self):
        self.count = self.count + 1
        if time.time() - self.boundary > 1:
            self.boundary = time.time()
            self.returned = self.count
            self.count = 0
            
        return self.returned
    
        This file provides a read-wite handling for ini files. The data of a ini file is represented by a object which is populated with strings.

#
# ini.rb - read and write ini files
#
# Copyright (C) 2007 Jeena Paradies
# License: GPL
# Author: Jeena Paradies (info@jeenaparadies.net)
#
# == Overview
#
# This file provides a read-wite handling for ini files.
# The data of a ini file is represented by a object which
# is populated with strings.

class Ini
  
  # Class with methods to read from and write into ini files.
  #
  # A ini file is a text file in a specific format,
  # it may include several fields which are sparated by
  # field headlines which are enclosured by "[]".
  # Each field may include several key-value pairs.
  #
  # Each key-value pair is represented by one line and
  # the value is sparated from the key by a "=".
  #
  # == Examples
  #
  # === Example ini file
  #
  #   # this is the first comment which will be saved in the comment attribute
  #   mail=info@example.com
  #   domain=example.com # this is a comment which will not be saved
  #   [database]
  #   db=example
  #   user=john
  #   passwd=very-secure
  #   host=localhost
  #   # this is another comment
  #   [filepaths]
  #   tmp=/tmp/example
  #   lib=/home/john/projects/example/lib
  #   htdocs=/home/john/projects/example/htdocs
  #   [ texts ]
  #   wellcome=Wellcome on my new website!
  #   Website description = This is only a example. # and another comment
  #
  # === Example object
  #
  #   A Ini#comment stores:
  #   "this is the first comment which will be saved in the comment attribute"
  #
  #   A Ini object stores:
  #
  #   {
  #    "mail" => "info@example.com",
  #    "domain" => "example.com",
  #    "database" => {
  #     "db" => "example",
  #     "user" => "john",
  #     "passwd" => "very-secure",
  #     "host" => "localhost"
  #    },
  #    "filepaths" => {
  #     "tmp" => "/tmp/example",
  #     "lib" => "/home/john/projects/example/lib",
  #     "htdocs" => "/home/john/projects/example/htdocs"
  #    }
  #    "texts" => {
  #     "wellcome" => "Wellcome on my new website!",
  #     "Website description" => "This is only a example."
  #    }
  #   }
  #
  # As you can see this module gets rid of all comments, linebreaks
  # and unnecessary spaces at the beginning and the end of each
  # field headline, key or value.
  #
  # === Using the object
  #
  # Using the object is stright forward:
  #
  #   ini = Ini.new("path/settings.ini")
  #   ini["mail"] = "info@example.com"
  #   ini["filepaths"] = { "tmp" => "/tmp/example" }
  #   ini.comment = "This is\na comment"
  #   puts ini["filepaths"]["tmp"]
  #   # => /tmp/example
  #   ini.write()
  # 
  
  #
  # :inihash is a hash which holds all ini data
  # :comment is a string which holds the comments on the top of the file
  #
  attr_accessor :inihash, :comment

  #
  # Creating a new Ini object
  #
  # +path+ is a path to the ini file
  # +load+ if nil restores the data if possible
  #        if true restores the data, if not possible raises an error
  #        if false does not resotre the data
  #
  def initialize(path, load=nil)
    @path = path
    @inihash = {}
    
    if load or ( load.nil? and FileTest.readable_real? @path )
      restore()
    end
  end
  
  #
  # Retrive the ini data for the key +key+
  #
  def [](key)
    @inihash[key]
  end
  
  #
  # Set the ini data for the key +key+
  #
  def []=(key, value)
    raise TypeError, "String expected" unless key.is_a? String
    raise TypeError, "String or Hash expected" unless value.is_a? String or value.is_a? Hash
    
    @inihash[key] = value
  end
  
  #
  # Restores the data from file into the object
  #
  def restore()
    @inihash = Ini.read_from_file(@path)
    @comment = Ini.read_comment_from_file(@path)
  end
  
  #
  # Store data from the object in the file
  #
  def update()
    Ini.write_to_file(@path, @inihash, @comment)
  end

  #
  # Reading data from file
  #
  # +path+ is a path to the ini file
  #
  # returns a hash which represents the data from the file
  #
  def Ini.read_from_file(path)
        
    inihash = {}
    headline = nil
    
    IO.foreach(path) do |line|

      line = line.strip.split(/#/)[0]
      
      # read it only if the line doesn't begin with a "=" and is long enough
      unless line.length < 2 and line[0,1] == "="
        
        # it's a headline if the line begins with a "[" and ends with a "]"
        if line[0,1] == "[" and line[line.length - 1, line.length] == "]"
          
          # get rid of the [] and unnecessary spaces
          headline = line[1, line.length - 2 ].strip
          inihash[headline] = {}
        else
        
          key, value = line.split(/=/, 2)
          
          key = key.strip unless key.nil?
          value = value.strip unless value.nil?
          
          unless headline.nil?
            inihash[headline][key] = value
          else
            inihash[key] = value unless key.nil?
          end
        end        
      end
    end
    
    inihash
  end
  
  #
  # Reading comments from file
  #
  # +path+ is a path to the ini file
  #
  # Returns a string with comments from the beginning of the
  # ini file.
  #
  def Ini.read_comment_from_file(path)
    comment = ""
    
    IO.foreach(path) do |line|
      line.strip!
      break unless line[0,1] == "#" or line == ""
      
      comment << "#{line[1, line.length ].strip}\n"
    end
    
    comment
  end
  
  #
  # Writing a ini hash into a file
  #
  # +path+ is a path to the ini file
  # +inihash+ is a hash representing the ini File. Default is a empty hash.
  # +comment+ is a string with comments which appear on the
  #           top of the file. Each line will get a "#" before.
  #           Default is no comment.
  #
  def Ini.write_to_file(path, inihash={}, comment=nil)
    raise TypeError, "String expected" unless comment.is_a? String or comment.nil?
    
    raise TypeError, "Hash expected" unless inihash.is_a? Hash
    File.open(path, "w") { |file|
      
      unless comment.nil?
        comment.each do |line|
          file << "# #{line}"
        end
      end
      
      file << Ini.to_s(inihash)
    }
  end
  
  #
  # Turn a hash (up to 2 levels deepness) into a ini string
  #
  # +inihash+ is a hash representing the ini File. Default is a empty hash.
  #
  # Returns a string in the ini file format.
  #
  def Ini.to_s(inihash={})
    str = ""
    
    inihash.each do |key, value|

      if value.is_a? Hash
        str << "[#{key.to_s}]\n"
        
        value.each do |under_key, under_value|
          str << "#{under_key.to_s}=#{under_value.to_s unless under_value.nil?}\n"
        end

      else
        str << "#{key.to_s}=#{value.to_s unless value2.nil?}\n"
      end
    end
    
    str
  end
  
end
    
        Array of country list in PHP with Zend Framework, ordered by country name

<?php
header('Content-Type: text/html; charset=utf-8');
require_once 'Zend/Locale.php';

$locale = new Zend_Locale('en_US');

$countries = ($locale->getTranslationList('country', 'en'));
asort($countries, SORT_LOCALE_STRING);

echo "<pre>";
print_r($countries);
echo "</pre>";
    
        Array of countries in Turkish

$countries = Array
(
    [VI] => ABD Virgin Adaları
    [AF] => Afganistan
    [AX] => Aland Adaları
    [DE] => Almanya
    [US] => Amerika BirleÅŸik Devletleri
    [UM] => Amerika Birleşik Devletleri Küçük Dış Adaları
    [AS] => Amerikan Samoası
    [AD] => Andora
    [AO] => Angola
    [AI] => Anguilla
    [AQ] => Antarktika
    [AG] => Antigua ve Barbuda
    [AR] => Arjantin
    [AL] => Arnavutluk
    [AW] => Aruba
    [QU] => Avrupa BirliÄŸi
    [AU] => Avustralya
    [AT] => Avusturya
    [AZ] => Azerbaycan
    [BS] => Bahamalar
    [BH] => Bahreyn
    [BD] => BangladeÅŸ
    [BB] => Barbados
    [EH] => Batı Sahara
    [BZ] => Belize
    [BE] => Belçika
    [BJ] => Benin
    [BM] => Bermuda
    [BY] => Beyaz Rusya
    [BT] => Bhutan
    [ZZ] => Bilinmeyen veya Geçersiz Bölge
    [AE] => BirleÅŸik Arap Emirlikleri
    [GB] => Birleşik Krallık
    [BO] => Bolivya
    [BA] => Bosna Hersek
    [BW] => Botsvana
    [BV] => Bouvet Adası
    [BR] => Brezilya
    [BN] => Brunei
    [BG] => Bulgaristan
    [BF] => Burkina Faso
    [BI] => Burundi
    [CV] => Cape Verde
    [GI] => Cebelitarık
    [DZ] => Cezayir
    [CX] => Christmas Adası
    [DJ] => Cibuti
    [CC] => Cocos Adaları
    [CK] => Cook Adaları
    [TD] => Çad
    [CZ] => Çek Cumhuriyeti
    [CN] => Çin
    [DK] => Danimarka
    [DM] => Dominik
    [DO] => Dominik Cumhuriyeti
    [TL] => DoÄŸu Timor
    [EC] => Ekvator
    [GQ] => Ekvator Ginesi
    [SV] => El Salvador
    [ID] => Endonezya
    [ER] => Eritre
    [AM] => Ermenistan
    [EE] => Estonya
    [ET] => Etiyopya
    [FK] => Falkland Adaları (Malvinalar)
    [FO] => Faroe Adaları
    [MA] => Fas
    [FJ] => Fiji
    [CI] => FildiÅŸi Sahilleri
    [PH] => Filipinler
    [PS] => Filistin Bölgesi
    [FI] => Finlandiya
    [FR] => Fransa
    [GF] => Fransız Guyanası
    [TF] => Fransız Güney Bölgeleri
    [PF] => Fransız Polinezyası
    [GA] => Gabon
    [GM] => Gambia
    [GH] => Gana
    [GN] => Gine
    [GW] => Gine-Bissau
    [GD] => Granada
    [GL] => Grönland
    [GP] => Guadeloupe
    [GU] => Guam
    [GT] => Guatemala
    [GG] => Guernsey
    [GY] => Guyana
    [ZA] => Güney Afrika
    [GS] => Güney Georgia ve Güney Sandwich Adaları
    [KR] => Güney Kore
    [CY] => Güney Kıbrıs Rum Kesimi
    [GE] => Gürcistan
    [HT] => Haiti
    [HM] => Heard Adası ve McDonald Adaları
    [IN] => Hindistan
    [IO] => Hint Okyanusu İngiliz Bölgesi
    [NL] => Hollanda
    [AN] => Hollanda Antilleri
    [HN] => Honduras
    [HK] => Hong Kong SAR - Çin
    [HR] => Hırvatistan
    [IQ] => Irak
    [VG] => İngiliz Virgin Adaları
    [IR] => Ä°ran
    [IE] => Ä°rlanda
    [ES] => Ä°spanya
    [IL] => Ä°srail
    [SE] => İsveç
    [CH] => İsviçre
    [IT] => Ä°talya
    [IS] => Ä°zlanda
    [JM] => Jamaika
    [JP] => Japonya
    [JE] => Jersey
    [KH] => Kamboçya
    [CM] => Kamerun
    [CA] => Kanada
    [ME] => KaradaÄŸ
    [QA] => Katar
    [KY] => Kayman Adaları
    [KZ] => Kazakistan
    [KE] => Kenya
    [KI] => Kiribati
    [CO] => Kolombiya
    [KM] => Komorlar
    [CG] => Kongo
    [CD] => Kongo Demokratik Cumhuriyeti
    [CR] => Kosta Rika
    [KW] => Kuveyt
    [KP] => Kuzey Kore
    [MP] => Kuzey Mariana Adaları
    [CU] => Küba
    [KG] => Kırgızistan
    [LA] => Laos
    [LS] => Lesotho
    [LV] => Letonya
    [LR] => Liberya
    [LY] => Libya
    [LI] => Liechtenstein
    [LT] => Litvanya
    [LB] => Lübnan
    [LU] => Lüksemburg
    [HU] => Macaristan
    [MG] => Madagaskar
    [MO] => Makao S.A.R. Çin
    [MK] => Makedonya
    [MW] => Malavi
    [MV] => Maldivler
    [MY] => Malezya
    [ML] => Mali
    [MT] => Malta
    [IM] => Man Adası
    [MH] => Marshall Adaları
    [MQ] => Martinik
    [MU] => Mauritius
    [YT] => Mayotte
    [MX] => Meksika
    [FM] => Mikronezya Federal Eyaletleri
    [MD] => Moldovya Cumhuriyeti
    [MC] => Monako
    [MS] => Montserrat
    [MR] => Moritanya
    [MZ] => Mozambik
    [MN] => MoÄŸolistan
    [MM] => Myanmar
    [EG] => Mısır
    [NA] => Namibya
    [NR] => Nauru
    [NP] => Nepal
    [NE] => Nijer
    [NG] => Nijerya
    [NI] => Nikaragua
    [NU] => Niue
    [NF] => Norfolk Adası
    [NO] => Norveç
    [CF] => Orta Afrika Cumhuriyeti
    [UZ] => Özbekistan
    [PK] => Pakistan
    [PW] => Palau
    [PA] => Panama
    [PG] => Papua Yeni Gine
    [PY] => Paraguay
    [PE] => Peru
    [PN] => Pitcairn
    [PL] => Polonya
    [PT] => Portekiz
    [PR] => Porto Riko
    [RE] => Reunion
    [RO] => Romanya
    [RW] => Ruanda
    [RU] => Rusya Federasyonu
    [SH] => Saint Helena
    [KN] => Saint Kitts ve Nevis
    [LC] => Saint Lucia
    [PM] => Saint Pierre ve Miquelon
    [VC] => Saint Vincent ve Grenadinler
    [WS] => Samoa
    [SM] => San Marino
    [ST] => Sao Tome ve Principe
    [SN] => Senegal
    [SC] => SeyÅŸeller
    [SL] => Sierra Leone
    [SG] => Singapur
    [SK] => Slovakya
    [SI] => Slovenya
    [SB] => Solomon Adaları
    [SO] => Somali
    [LK] => Sri Lanka
    [SD] => Sudan
    [SR] => Surinam
    [SY] => Suriye
    [SA] => Suudi Arabistan
    [SJ] => Svalbard ve Jan Mayen
    [SZ] => Svaziland
    [RS] => Sırbistan
    [CS] => Sırbistan-Karadağ
    [CL] => Åžili
    [TJ] => Tacikistan
    [TZ] => Tanzanya
    [TH] => Tayland
    [TW] => Tayvan
    [TG] => Togo
    [TK] => Tokelau
    [TO] => Tonga
    [TT] => Trinidad ve Tobago
    [TN] => Tunus
    [TC] => Turks ve Caicos Adaları
    [TV] => Tuvalu
    [TR] => Türkiye
    [TM] => Türkmenistan
    [UG] => Uganda
    [UA] => Ukrayna
    [OM] => Umman
    [UY] => Uruguay
    [QO] => Uzak Okyanusya
    [JO] => Ürdün
    [VU] => Vanuatu
    [VA] => Vatikan
    [VE] => Venezuela
    [VN] => Vietnam
    [WF] => Wallis ve Futuna
    [YE] => Yemen
    [NC] => Yeni Kaledonya
    [NZ] => Yeni Zelanda
    [GR] => Yunanistan
    [ZM] => Zambiya
    [ZW] => Zimbabve
)
    
        // calculate the Pearson's correlation in JAVA

public class Correlation {
    public static double getPearsonCorrelation(double[] scores1,double[] scores2){
        double result = 0;
        double sum_sq_x = 0;
        double sum_sq_y = 0;
        double sum_coproduct = 0;
        double mean_x = scores1[0];
        double mean_y = scores2[0];
        for(int i=2;i<scores1.length+1;i+=1){
            double sweep =Double.valueOf(i-1)/i;
            double delta_x = scores1[i-1]-mean_x;
            double delta_y = scores2[i-1]-mean_y;
            sum_sq_x += delta_x * delta_x * sweep;
            sum_sq_y += delta_y * delta_y * sweep;
            sum_coproduct += delta_x * delta_y * sweep;
            mean_x += delta_x / i;
            mean_y += delta_y / i;
        }
        double pop_sd_x = (double) Math.sqrt(sum_sq_x/scores1.length);
        double pop_sd_y = (double) Math.sqrt(sum_sq_y/scores1.length);
        double cov_x_y = sum_coproduct / scores1.length;
        result = cov_x_y / (pop_sd_x*pop_sd_y);
        return result;
    }
}
    
        // the configure file format is key=value

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

/**
 *
 * @author mingzhi
 */
public class Configure extends Properties{
    public Configure(){
        
    }
    
    public Configure(File configFile) throws IOException{
        load(configFile);
    }
    
    public Configure(InputStream inputStream) throws IOException{
        load(inputStream);
    }
    
    public Configure(Properties props) throws IOException{
        load(props);
    }

    public void load(Properties props) {
        Enumeration<String> names = (Enumeration<String>) props.propertyNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            String value = props.getProperty(name);
            setProperty(name,value);
        }
    }
    
    public void load(File configFile) throws IOException{
        load(new FileInputStream(configFile));
    }
    
}

    
        // description of your code here

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++)
                        != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                 break test;
        }
        System.out.println(foundIt ? "Found it" :
                                     "Didn't find it");
    }
}
    
        ใช้คำสั่ง gunzip แตกไฟล์ที่ชื่อไฟล์มี space ใน perl
 
my @get_files;
push (@get_files,"\"test file.txt.gz\"");
system("gunzip -f $get_files[0]");
    
        When a latest RubyGems is released (e.g. 0.9.5 recently) or Rails (e.g. 2.0.2) you might want to push those upgrades to all your production machines.

Add these two tasks to your deploy.rb capistrano file (add namespaces for cap2.0 if you like)

  desc "Updates RubyGems version"
  task :gem_update_system do
    sudo "gem update --system"
  end

    
  desc "Install a RubyGem from remote source"
  task :gem_install do
    puts "USAGE: GEM=gemname cap gems_install" and next unless ENV['GEM']
    sudo "gem install #{ENV['GEM']} --no-ri --no-rdoc"
  end

To upgrade rubygems and rails, for example:

cap gem_update_system
GEM=rails cap gem_install
    
        Pass all requests for non-existing files or directories to index.php
RewriteCond        %{REQUEST_FILENAME}        !-f                
RewriteCond        %{REQUEST_FILENAME}        !-d
RewriteRule        ^(.*)$                    index.php        [L]
    
        
require "rubygems"
require "active_record"
require "active_support"

ActiveRecord::Base.establish_connection(
	:adapter => "sqlite3",
	:database => "places.sqlite"
)

class MozHistoryvisit < ActiveRecord::Base
	belongs_to :place, :class_name => "MozPlaces", :foreign_key => "place_id"
end

class MozPlaces < ActiveRecord::Base
end

p Time.now.yesterday
from = Time.now.yesterday.to_i * 1000000

MozHistoryvisit.find(:all, :conditions => ["visit_date > ?", from]).each do |h|
	place = h.place
	puts place.title
	puts place.url
	puts place.visit_count
	puts
end