Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Friday, November 13, 2009

Library for Numerical Computing

Briefly summarize some numerical library here. It looks there are too many useful tools. Either for parallel computing or for matrix, numerical calculating and plotting.

PLOT:

MatPlotLib: it seems to be the most awesome plotting tool among this list

PGPlot: C library, also have binding in Perl, Python,Ruby

PLPlot: cross-platform plot library, also have binding in Perl

Scientific Python

MRPlot


PARALLEL:

MPI Ruby: MPI Ruby binding

PyMPI: MPI integrated Python interpreter

MPI for Python Python MPI binding

Simple Remote Python : SrPy

Parallel Python


CALCULATION:

Perl Data Language: difficult to be categorized. Including calculating, plotting together. include FFTW, PGPlot, PLPlot, and many data processing tool such as HDF. Awesome Environment!

MPMath: Multi-Precision math functions collection.

RNUM

NArray

LibFFTW, also have binding in Perl, Ruby

Ruby DCL

LAPACK

SciPy

NumPy

GNU Scientific Library: C library, also have bindings in Ruby named Ruby/GSL and Ruby-GSL. and Python

RSRuby: bridge between Ruby and R

ARTICLES:

Ruby for Science

 

Sunday, August 30, 2009

Discussion about anonymous function in Perl and Ruby

Just for fun, tonight I write a methods invoking two anonymous functions to iterate a Range with specified condition in Ruby. It looks like
class Range
def each_satisfy()
end
end
And I want to invoke it as

(1..10).each_satisfy(condition_lambda, callback_lambda)

(1..10).each_satsify { |n| ...condition statment... } do |n|
...callback statement...
end
When I try to define its prototype as
def each_satisfy(&condition, &callback)
end
Ruby Interpreter broke with syntax error. So that, finally I write it as

def each_satisfy(condition, &callback)
self.each do |n|
yield n if condition.call n
end
end
and it should be used as

(1..10).each_satsify lambda { |n| ...condition statment... } do |n|
...callback statement...
end

It reminded me that Perl also has the same problem. Even when we declare

sub each_satisfy(&&) {

}

Still only first sub keyword could be omitted. That means we should invoke it as

each_satisfy { ... condition ... } sub {
my ($iter) = @_;
... callback ...
}

The only difference is Perl omitted the first (sub) and Ruby omitted the last (lambda).

I do want to figure out WHY they could not be designed to accept arbitrary quantity of anonymous functions.

 

Tuesday, April 28, 2009

some notes

1. do find => rescue

2. model operation more than 3 lines => define class method in model

3. def current_user

4. render_as_form

5. more than one relation in one table

6. composite primary key => hook

 

Wednesday, March 25, 2009

Rails on FreeBSD 7.1

Today I was first time trying to install rails on freebsd 7.1. Neither the ports version nor the gem file version, rails could not work, even only simply creating a new project. It returns message as following.

undefined method `camelize' for "app":String

I had try to reinstall ruby, rubygem, and try other version rails but a nonsense. And finally I forgot how did I discover it needs ruby-iconv ports in fact. It seems occurring at the time I was using rails 2.2.2, some keyword appeared in the error message.

One post on the mailing list [Ruby on Rails : Talk] show the same problem. If you also have the same problem, try it.

 

Sunday, August 31, 2008

Array.split


01 class Array
02 def split(part)
03 num = self.length/part.to_i
04 result = Array.new
05 for row in 0..(part-1)
06 result[row] = self[num*row...num*(row+1)]
07 end
08 result
09 end
10 end

a = [1,2,3,4,5,6,7,8,9]
a.split(3).inspect # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

 

Sunday, August 3, 2008

set volume in max os x terminal

Costing my much time to search, It seems no command for setting volume in Leopard. When I used AppleScript to do this, I didn't know why the executable file cause some problem in screen. But Ruby's applescript gem do this good. I saved below content as /usr/bin/volume, and then I could use $ volume [1-7 as volume] to set Leopard's Volume from remote.

01 #!/usr/bin/env ruby
02
03 require 'rubygems'
04 require 'applescript'
05
06 AppleScript.execute("set volume #{ARGV[0]}")


update 2008/8/3

the way using applescript interpreter is $ osascript -e "set volume [1-7]"
or call in script by shebang.

01 #!/usr/bin/osascript
02
03 set volume [1-7]


 

Monday, July 28, 2008

ruby readline


loop do
line = Readline::readline("app shell> ")
if line
Readline::HISTORY.push line
puts line
else
puts
break
end
end


This is a the most basic usage.
I want to find a way could act as irssi :/

 

Saturday, July 12, 2008

restful 與 form_for

不可以在 /news/new 的 view 裡面寫 form_for @news ~"~

 

Tuesday, June 3, 2008

operate existed tables in rails

Just need specify table name and primary key in Model. All attribution in tables will appear automatically.
class ModelName < ActiveRecord::Base
self.table_name = "table_name"
self.primary_key = "primary_key"
end


 

Saturday, May 24, 2008

tree implement in ruby

Just for fun, but it work well.

01 #!/usr/bin/env ruby
02 #
03 #
04
05
06 def tree(dirname, indent = " |")
07 puts dirname + "/" if indent == " |"
08 dir = Dir.open dirname
09 for f in dir
10 if f == "." || f == ".."
11 next
12 elsif File.directory? dirname+"/"+f
13 puts indent + "-" + f + "/"
14 tree( dirname+"/"+f, indent+" |")
15 else
16 puts indent + "-" + f
17 end
18 end
19 end
20
21 tree (ARGV[0]? ARGV[0] : ".")

 

Friday, May 23, 2008

closure tip

closure is so fun.
well design for meta programming.

note 1:

01 #!/usr/bin/env ruby
02
03 class Hash
04 def find_all
05 temp_hash = {}
06 each {|key,value| temp_hash[key] = value if yield(key,value) }
07 temp_hash
08 end
09 end
10
11 square = { 0 => 0, 1 => 1, 2 => 4, 3 => 9 }
12
13 new = square.find_all { |key,value| key > 1 }
14 puts new.inspect

pass yield values.

note 2:

01 #!/usr/bin/env ruby
02
03 class Person
04 attr_accessor :name
05 def initialize(name)
06 @name = name
07 end
08 end
09
10 def command(obj,method)
11 obj.each {|x| yield x.send(method)}
12 end
13
14 family = []
15
16 %w(shelling sherry appollo).each do |name|
17 family.push Person.new(name)
18 end
19
20 command family, :name do |x|
21 puts "hello, I am #{x}."
22 end

Every object in array call the same function.

 
 

Friday, April 25, 2008

boring comparison

show complex data structure in perl and ruby

perl
#!/usr/bin/env perl
use warnings;
use Data::Dumper;

$a = ["a", "b", "c", { "key" => "value" } ];
print Dumper $a;


ruby
#!/usr/bin/env ruby
a = ["a", "b", "c", { "key" => "value" } ]
puts a.inspect
 
 

Saturday, April 19, 2008

has_many() function note

if has_many :order
order.delete_all just set foreign key null
order.destroy_all clear all sub record
 
 

Friday, April 18, 2008

apache2 and mongrel cluster on debian

Enable apache2 proxy
$ sudo a2enmod proxy proxy_http proxy_balancer

Configure Proxy in a virtual host
/etc/apache2/site-enabled/default add
DocumentRoot "RailsApp/public"
    # even only RailsApp also work

ProxyPass / balancer://localhost/
ProxyPassReverse / balancer://localhost/
< proxy balancer://localhost/ >
    BalanceMember http://localhost:3000
    BalanceMember http://localhost:3001
    BalanceMember http://localhost:3002
< /proxy >


Then set mongrel cluster
$ sudo gem install mongrel_cluster
$ cd RailsApp
$ mongrel_rails cluster::configure -e development -p 3000 -N 3
    # write config/mongrel_cluster.yml

$ mongrel_rails cluster::start


Final, restart apache2 and it work.

 
 

Thursday, April 17, 2008

rss feed in rails

Note for the Way to create Atom and RSS 2.0 feed.

$ ./script/generate controller feed

Suppose that the model we want show in feed is Post

class FeedController < ApplicationController
    def rss
        @rss = @@post
    end

    def atom
        @atom = @@post
    end

  private
    @@post = Post.find :all,
        :order => "update_at", :limit => 10

end


Then write the view.

app/view/feed/rss.rxml

01 xml.instruct! :xml, :version=>"1.0"
02 xml.rss(:version=>"2.0"){
03     xml.channel{
04         xml.title("The site title")
05         xml.link(url_for("/"))
06         xml.description("The site description")
07         xml.language('en-us')
08
09         @rss.each do |rss|
10         xml.item {
11             xml.title rss.title
12             xml.link ""
13             xml.description rss.content
14             xml.pubDate rss.update_at
15             xml.guid ""
16             xml.author rss.declarer
17         }
18         end
19     }
20 }



app/view/feed/atom.rxml

01 xml.instruct! :xml, :version=>"1.0"
02 xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do
03     xml.title("The site title")
04     xml.link(url_for "/")
05     @atom.each do |atom|
06         xml.entry {
07             xml.title(atom.title)
08             xml.summary(atom.content)
09         }
10     end
11 end


app/view/layout/application.rhtml add

<%= auto_discovery_link_tag :rss, { :controller => '/rss', :action => 'rss' }, { :title => "RSS 2.0" } %>
<%= auto_discovery_link_tag :rss, { :controller => '/rss', :action => 'atom' }, { :title => "Atom" } %>


 
 

Tuesday, April 15, 2008

rails helper block

Write for memo.
To set a helper in the form

<% helper_name do %>
    <div>blah</div>
<% end %>
.

The definition is

def helper_name(&block)
    content = capture(&block)
    concat("what we want write before block".block.binding)
    concat(content,block.binding)
    concat("what we want write after block",block.binding)
end


By the way, partial is the way do the same thing once. if the outer html is used frequently, the way to define a helper as above will be better.
 
 

Sunday, April 13, 2008

spakit

The rails plugin spakit means Single Page Application KIT. It can transform rails app into single page app but not modify app structure in large scale by loading content of other controller into primary controller.

The installation step is from handlino.com
$ sudo gem install spakit
$ cd railsapp/vendor/plugins/
$ gem unpack spakit
$ mv spakit-version spakit

now installation finished.

Before using it, spakit need a layout railsapp/app/view/layout/spakit.rhtml<%= flash[:notice] %>
<%= yield %>

And the layout application.rhtml should contain
<%= javascript_include_tag :defaults %> to include default js file.

Now we can use it happy. Add <div id="content"></div> into the view of primary controller, and set a spakit link: <%= spakit_link_to 'new person', :url => new_person_path %>, the content of the url will appear in the div#content.

Also two other helpers contain in spakit, spakit_form_for and spakit_form_tag

link1: spakit at rubyforge
link2: spakit at github

annotate models

The plugin used for adding column annotate into model file is introduced in Ralls Bible. Write for note. the newer introduction at http://pragdave.pragprog.com/pragdave/2006/02/annotate_models.html. Just two step to use it.
1.script/plugin install http://repo.pragprog.com/svn/Public/plugins/annotate_models
2. rake annotate_models
And all model now with column annotate at file head.

Sunday, February 17, 2008

the end of winter recess

這個寒假比預期的廢了很多,預定的事項,想讀的書,沒一件做完的,再來,三月一日就是研究所考試了,看著別人即將踏入考場,自己摸著鼻子甸甸自己剩下不到一年的時間儲備,真是難以說話。雖然沒有完成預定的事項,不過練習 perl/ruby 之餘還是寫了些 bot,cwbbot 是個簡單的 ruby 天氣預報機器人,提供他 twitter 的帳號和密碼,丟進 crontab,就可以每天自動取得明日溫度。

Saturday, February 16, 2008

perl 和 ruby 的 twitter shell

twitter 最近紅透半邊天,perl 和 ruby 都有了 twitter api,現在還有 twitter shell,perl 的 twitter shell 利用 cpan 下 install Twitter::Shell 就可以得到 /usr/local/bin/twittershell, 使用方式為新增一個 yaml,如: touch ~/.twittershell.yml , 裡面填入
username: yourtwitteraccount
password: yourtwitterpassword
在 shell 下 twittershell -c ~/.twittershell.yml 就進入該 shell, help 可以得到幫助。

ruby 版本內建在 twitter 這個 gem 內, sudo gem install twitter 就可以得到 /usr/bin/twitter,直接在 shell 下 twitter 就可以得到幫助。不過 ruby 版本對 unicode 沒有支援,無法顯示中文,嘗試在 twitter gem 內的 twitter.rb 加入
require 'jcode'
$KCODE = 'u'
,不過沒有效果,作者也表示暫時不會加入 unicode 支援。