Showing posts with label Usage. Show all posts
Showing posts with label Usage. Show all posts

Monday, December 08, 2008

usage of call_user_func_array function in php


<?php

class Foo {
static public function test($name) {
print "Hello {$name}!\n";
}

public function bar($name){
print "Hello {$name}\n";
}
}

// call static Class methods.
call_user_func_array('Foo::test', array('Hannes'));
// Hello Hannes!
call_user_func_array(array('Foo', 'test'), array('Philip'));
// Hello Philip!


$foo = new Foo();
// call object instance methods.
call_user_func_array(array($foo, 'bar'), array('World!'));
call_user_func_array(array($foo, 'bar'), 'World!');
// Hello World!

?>

参考php手册:
callback
有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。
一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了 array(),echo(),empty(),eval(),exit(),isset(),list(),print() 和 unset()。
一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。
对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。
Reference:
http://cn.php.net/manual/en/function.call-user-func-array.php

Friday, May 30, 2008

json for ruby [jruby] install and usage

$> sudo gem install json
$> sudo jruby -S gem install json_pure

require 'rubygems'
require 'json'

class Range
def to_json(*a)
{
'json_class' => self.class.name,
'data' => [ first, last, exclude_end? ]
}.to_json(*a)
end

def self.json_create(o)
new(*o['data'])
end
end

puts (1..10).to_json
p JSON.parse((1..10).to_json)
puts JSON.parse((1..10).to_json) == (1..10)

json =<<-"JSON"
{
"hasItems": true,
"totalItems": 5,
"orderId": "xxx-xxxxx-xxx",
"hasDetails": true,
"details": [{"item": "2323-2323", "number": 2, "price": 2.00}, {"item": "2323-2324", "number": 3, "price": 3.00}]
}
JSON
p JSON.parse(json)["hasItems"] # => true
p JSON.parse(json)["totalItems"] # => 5

notice: keys and values in json string must be quoted.

Sunday, January 20, 2008

usage of cut [awk] and xargs of linux commands

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'

在dzone.com上看到这个命令alias用以杀掉ruby rails server进程,其中的cut结合xargs或者是awk结合xargs使用相当便捷。

Wednesday, December 05, 2007

Ruby Faker install and usage

$ wget http://gems.rubyforge.org/gems/faker-0.2.0.gem
--11:33:09-- http://gems.rubyforge.org/gems/faker-0.2.0.gem
=> `faker-0.2.0.gem'
Resolving gems.rubyforge.org... 205.234.109.19
Connecting to gems.rubyforge.org|205.234.109.19|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://rubyforge.iasi.roedu.net/gems/faker-0.2.0.gem [following]
--11:33:10-- http://rubyforge.iasi.roedu.net/gems/faker-0.2.0.gem
=> `faker-0.2.0.gem'
Resolving rubyforge.iasi.roedu.net... 192.129.4.120
Connecting to rubyforge.iasi.roedu.net|192.129.4.120|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 43,520 (42K) [application/octet-stream]

100%[====================================>] 43,520 5.05K/s ETA 00:00

11:33:25 (5.04 KB/s) - `faker-0.2.0.gem' saved [43520/43520]

$ gem install faker
Successfully installed faker, version 0.2.0
Installing ri documentation for faker-0.2.0-...
Installing RDoc documentation for faker-0.2.0-...

$ irb
irb(main):002:0> require 'rubygems'
=> true
irb(main):003:0> require 'faker'
=> true
irb(main):005:0> Faker::Name.name
=> "Lauriane Stanton"
irb(main):006:0>
irb(main):007:0* Faker::Name.name
=> "Sallie Rippin"
irb(main):008:0> Faker::Name.name
=> "Selina Jerde"
irb(main):010:0> Faker::Internet.email
=> "elda.friesen@cassin.co.uk"
irb(main):011:0> Faker::Internet.email
=> "ervin@parkerblock.us"
irb(main):012:0> Faker::Internet.email
=> "jaron.bailey@abbotthintz.co.uk"
irb(main):013:0> Faker::Internet.email
=> "stan@torp.us"
irb(main):014:0> Faker::Internet.free_email
=> "yasmeen@yahoo.com"
irb(main):015:0> Faker::Internet.free_email
=> "ona@hotmail.com"
irb(main):016:0> Faker::Internet.free_email
=> "naomi@hotmail.com"
irb(main):017:0> Faker::Internet.free_email
=> "alisha@hotmail.com"
irb(main):018:0> Faker::Internet.user_name

Thursday, October 18, 2007

Usage of Ruby parseexcel lib

gem包安装后的README文件有个实例简单说明了这个lib的使用方法,gem包没有安装doc


#!/usr/bin/env ruby

require 'parseexcel'

# your first step is always reading in the file.
# that gives you a workbook-object, which has one or more worksheets,
# just like in Excel you have the possibility of multiple worksheets.
workbook = Spreadsheet::ParseExcel.parse(path_to_file)

# usually, you want the first worksheet:
worksheet = workbook.worksheet(0)

# now you can either iterate over all rows, skipping the first number of
# rows (in case you know they just contain column headers)
skip = 2
worksheet.each(skip) { |row|
# a row is actually just an Array of Cells..
first_cell = row.at(0)

# how you get data out of the cell depends on what datatype you
# expect:

# if you expect a String, you can pass an encoding and (iconv
# required) the content of the cell will be converted.
str = row.at(1).to_s('latin1')

# if you expect a Float:
float = row.at(2).to_f

# if you expect an Integer:
int = row.at(3).to_i

# if you expect a Date:
date = row.at(4).date

# ParseExcel makes a guess at what Datatype a cell has. At the moment,
# possible values are: :date, :numeric, :text
celltype = first_cell.type
}

# if you know exactly which row your data resides in, you may just
# retrieve that row, which is again simply an Array of Cells
row = worksheet.row(26)

Sunday, August 26, 2007

Rails Routes 详解

$>cd RubyOnRails/app/path
$>cd script/console
>>rs = ActionController::Routing::Routes
>>puts rs.routes
ANY /:controller/service.wsdl/ {:action=>"wsdl"}
ANY /:controller/:action/:id.:format/ {}
ANY /:controller/:action/:id/ {}
=>nil

修改config/routes.rb文件,添加一行
map.connect 'modules/controller/:action/*other', :controller => 'modules/controller'
回到console
>>rs.reload
>>puts rs.routes
ANY /:controller/service.wsdl/ {:action=>"wsdl"}
ANY /:controller/:action/:id.:format/ {}
ANY /:controller/:action/:id/ {}
ANY /modules/controller/:action/:other/ {:controller=>"modules/controller"}
=>nil
>>rs.recognize_path '/modules/controller/test/2?x=1'
=>{:action=>"test", :other=>["2?x=1"], :controller=>"modules/controller"}
>>rs.recognize_path '/test/action/1'
=>{:action=>"action", :id=>"1", :controller=>"test"}
>> rs.add_route('/x/y/z', {:controller => 'test', :action => 'index', :id => 0})=> #>>puts rs.routes
ANY /:controller/service.wsdl/ {:action=>"wsdl"}
ANY /:controller/:action/:id.:format/ {}
ANY /:controller/:action/:id/ {}
ANY /modules/controller/:action/:other/ {:controller=>"modules/controller"}
ANY /x/y/z/ {:action=>"index", :id=>0, :controller=>"test"}
=> nil
>> rs.draw do |map|
?> map.connect '/blog/:id', :controller => 'blog', :action => 'list'
>> end
=> [ActionController::Base, ActionView::Base]
>> puts rs.routes
ANY /blog/:id/ {:action=>"list", :controller=>"blog"}
=> nil
>> rs.recognize_path '/blog/1'
=> {:action=>"list", :id=>"1", :controller=>"blog"}
这里发现原来的routes全部不见了,只有这个新建的routes了,因为draw方法内部实现为:


def draw
clear!
yield Mapper.new(self)
named_routes.install
end

draw方法块里的map对象里method_missing方法就是用来实现具名路由named routes的。先看下源码如下:

def method_missing(route_name, *args, &proc)
super unless args.length >= 1 && proc.nil?
@set.add_named_route(route_name, *args)
end

上面对实例变量@set就是前面的rs对象,那么就看一下rs.add_named_route方法吧
>>rs.clear!
>>rs.add_named_route('index', 'user/index', :controller => 'user', :action => 'index')
puts rs.named_routes
#
=> nil
>> puts rs.routes
ANY /user/index/ {:action=>"index", :controller=>"user"}
=> nil
>> puts rs.named_routes.routes
indexANY /user/index/ {:action=>"index", :controller=>"user"}
=> nil
定义了具名路后就可以在controller/view中像url_for一样调用,只要在route name后面加上_url就可以,url_for在console里不能调试,可以用rs.generate(request)方法测试。
# In addition to providing url_for, named routes are also accessible after including UrlWriter.
url_for(:controller => 'signup', action => 'index', :token => token)
index_url(:id => 1)
#=> http://localhost/user/index?id=1
>> rs.generate(:controller => 'test', :action => 'index', :id => 3)
=> "/test/index/3"
另外在map这个对象里有个方法root可以给根目录定义路径,用法如下:

>> rs.draw do |map|
?> map.root :controller => 'test', :action => 'list'
>> end
ArgumentError: Illegal route: the :controller must be specified!
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:965:in `build'
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:1172:in `add_route'
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:1178:in `add_named_route'
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:997:in `root_without_deprecation'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/deprecation.rb:94:in `root'
from (irb):60
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/routing.rb:1139:in `draw'
from (irb):59


# Added deprecation notice for anyone who already added a named route called "root".
# It'll be used as a shortcut for map.connect '' in Rails 2.0.
# def root(*args, &proc)
# super unless args.length >= 1 && proc.nil?
# @set.add_named_route("root", *args)
# end
# deprecate :root => "(as the the label for a named route) will become a shortcut for map.connect '', so find another name"

Rails2.0才会引进此方法,所以Rails建议用户不要使用此具名路由,如下:
>> rs.draw do |map|
?> map.root '', :controller => 'test', :action => 'list'
>> end
=> [ActionController::Base, ActionView::Base]
>> puts rs.routes
ANY / {:action=>"list", :controller=>"test"}
=> nil
>> puts rs.named_routes.routes
rootANY / {:action=>"list", :controller=>"test"}
=> nil
这个写法其实就是做了个具名路由,而不是调用map.root方法,调用的是method_missing方法。

Saturday, July 14, 2007

Javascript tips of functions usage

These tips are suggested as good programming practices and should lead to easier-to-maintain code.
Define All Functions for a Script First The reason for this tip should be obvious: we need to make sure a function is defined and read by a browser before we can invoke it. Secondarily, if we define all the functions that our code will use in one place, it makes functions easier to find.
Name Functions Well When naming functions and variables, you need to be a little careful. Because functions and variables share the same namespace, you shouldn’t be declaring variables and functions with the same name. It might be a good idea to precede function names with “func” or some other string or letter of your own choosing. So, using such a scheme, if we had a variable named hello and wanted to define a function also called hello, we would use funcHello.
Note
Some developers prefer different casing to distinguish between variables and functions, but this may not be obvious enough. The choice is a matter of style and we leave it open for readers to decide for themselves.
Besides the obvious collision of names, very subtle bugs may slip in when we have similar names, particularly when you consider that functions are created when the document is parsed, while variables are created when the script is run. Notice in the following script how there is a variable as well as a function called x.
var x = 5;
function x()
{
alert("I'm a function!");
}
alert(typeof x);

You might expect the alert to show x to be a function or, more appropriately, an object because it appears to be defined second. However, as you can see here, it is a number.
The output makes sense if you consider when the function and variables are actually created. The function is created as the script is parsed, while the variable gets created as the script runs. While this was a contrived example, it illustrates the importance of understanding how things are created in JavaScript.
Consider Using Linked .js Files for Functions, But Be Cautious While many JavaScript programmers like to put functions in external files, we need to make sure that a function is available before calling it. For example, if we have two .js files (lib1.js and lib2.js), each of which calls functions found in the other, we may have to check to make sure the function is available before calling it because the browser might finish loading one script before the other. In the main document, we would define variables showing the files being loaded as false:
var lib1Loaded = false;
var lib2Loaded = false;

Then, in each of the loaded documents the last line would set the corresponding variables to true. Using this scheme, we would then make sure to look at the value of the variables lib1Loaded or lib2Loaded before any functions that are contained in the files are called. For example:
if (lib1Loaded)
doSomething(x,y,z)

Most of the time such efforts aren’t required, but JavaScript designers should be careful to consider the load order of documents and what happens if certain parts of a script are invoked before an entire document has loaded.
Use Explicit Return Statements Even if your function will not return any values, insert a return statement anyway. JavaScript being an interpreted language, keeping the interpreter from having to do any extra work or make any assumptions should produce better running scripts.
Write Stand-Alone Functions As always, you should practice modular design and pass data into and out from functions using only function arguments, the return statement, and data values that are passed by reference. We should avoid side-effects such as changing global values from within functions. Local variables should always be used to perform calculations that are unique to a function, and hidden functions can be used in the same manner to create special-purpose functions that are not needed anywhere else. The value of going through the trouble to create stand-alone functions in this fashion is that such functions can be reused without worry in a variety of situations.

Friday, July 06, 2007

install ruby gc patch and usage of railsbench

use one of: base, comp, comp_gc, convert_raw_data_files, diff, diff_gc, generate
_benchmarks, help, html, install, path, perf_comp, perf_comp_gc, perf_diff, perf
_diff_gc, perf_html, perf_plot, perf_plot_gc, perf_prof, perf_run, perf_run_gc,
perf_table, perf_tex, perf_times, perf_times_gc, plot, plot_gc, postinstall, pro
f, readme, run, run_gc, run_urls, table, tex, times, times_gc
'railsbench help' displays README
'railsbench cmd help' displays help for given command

==================================================
RAILSBENCH INSTALLATION
==================================================

STEP 1: installing railsbench and PATH modification
---------------------------------------------------

If you obtained and installed railsbench as a gem, a script called
railsbench is available in your Ruby bin directory. railsbench is a
simple driver for the railsbench scripts, which are located in the gem
installation directory. Example:

railsbench perf_run 100 -bm=all

Alternatively, add the railsbench script directory to your search
path. The exact place can be found running

railsbench base

which prints the script directory path. Another option is to run

eval `railsbench path`

Since gem packages don't support running postinstall scripts, you will
need to make the scripts executable by running

sudo railsbench postinstall

After performing these steps, individual commands can be run directly:

perf_run 100 -bm=all

# benchmark.yml
# default:
# uri: /
#
# all:
# uri: /admin

The environment variable RAILS_ROOT must be set and point to your apps
base directory, in order for railsbench to work properly.

If you obtained railsbench as a svn checkout, add the railsbench
script directory to your search path.


STEP 2: prepare your application for benchmarking
-------------------------------------------------

Manual installation:

Copy benchmarks.rb and benchmarks.yml into $RAILS_ROOT/config and
edit them to suit your needs. The provided default benchmark.yml
will run the root URL of your app.

Copy benchmarking.rb to $RAILS_ROOT/config/environments and add a
corresponding section to database.yml.

Automatic installation:

Run 'railsbench install'. This will perform all of the above steps
and create a configuration named 'benchmarking' in database.yml
pointing to your development database. In case you are worrying
about possible results, you can call railsbench install --dry-run
first.

In either case, run `railsbench generate_benchmarks'. This will create
a benchmarks.yml file with a benchmark for each controller and action.


STEP 3: optional (but highly recommended)
-----------------------------------------

Patch the ruby garbage collector using rubygc18{45}.patch, depending
on your ruby version. Recompile ruby and copy the ruby binary and
shared libs to where they were previously installed. See GCPATCH for
details on how to influence the patched ruby gc.

[root@localhost soft]$ sudo gem install railsbench
Bulk updating Gem source index for: http://gems.rubyforge.org
Successfully installed railsbench-0.9.2
[root@localhost soft]$ cd ruby-1.8.5
[root@localhost ruby-1.8.5]$ pa
pal2rgb pango-querymodules-32 passwd patch pax
pand paps paste pathchk
[root@localhost ruby-1.8.5]$ pat
patch pathchk
[root@localhost ruby-1.8.5]$ patch -p0 < /usr/local/ruby/
bin/ lib/ share/
[root@localhost ruby-1.8.5]$ patch -p0 < /usr/local/ruby/lib/
libruby-static.a ruby/
[root@localhost ruby-1.8.5]$ patch -p0 < /usr/local/ruby/lib/ruby/
1.8/ gems/ site_ruby/
[root@localhost ruby-1.8.5]$ patch -p0 < /usr/local/ruby/lib/ruby/gems/1.8/gems/railsbench-0.9.2/
bin/ config/ lib/ postinstall.rb README script/
BUGS INSTALL LICENSE PROBLEMS ruby184gc.patch setup.rb
CHANGELOG install.rb Manifest.txt Rakefile ruby185gc.patch test/
[root@localhost ruby-1.8.5]$ patch -p0 < /usr/local/ruby/lib/ruby/gems/1.8/gems/railsbench-0.9.2/ruby185gc.patch
patching file gc.c
Hunk #2 succeeded at 62 (offset 14 lines).
Hunk #4 succeeded at 225 (offset 14 lines).
Hunk #6 succeeded at 428 (offset 14 lines).
Hunk #8 succeeded at 582 (offset 14 lines).
Hunk #10 succeeded at 618 (offset 14 lines).
Hunk #11 succeeded at 1254 (offset -3 lines).
Hunk #12 succeeded at 1334 (offset 14 lines).
Hunk #13 succeeded at 1364 (offset -3 lines).
Hunk #14 succeeded at 1391 (offset 14 lines).
Hunk #15 succeeded at 1393 (offset -3 lines).
Hunk #16 succeeded at 1431 (offset 14 lines).
Hunk #17 succeeded at 1422 (offset -3 lines).
Hunk #18 succeeded at 1647 (offset 14 lines).
Hunk #19 succeeded at 1647 (offset -3 lines).
Hunk #20 succeeded at 1760 (offset 27 lines).
Hunk #21 succeeded at 1854 (offset -58 lines).
Hunk #22 succeeded at 2409 (offset 27 lines).