Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, January 29, 2010

Injecting one module into another in Python

Here is a simple code snippet to do that. Saving it to an individual file and import it in other module to use it.



Using exec statement is also good, but need to pass globals() or locals() dictionary to the function executing exec statement.

Doing dirty things in Python is really not easy...:/

 

Wednesday, December 30, 2009

Assign initial value to a pointer

Today I suddenly got an idea. Most of time when we use pointer, we create a variable, and assign initial value to it, and then take its address become the value of a new pointer for succeeding use. But we create a redundant identifier here.

In fact, we could always create a fundamental type pointer and assign initial value to it through dereference operator like this snippet.



and no redundant variable here.

But when we define a simple struct like this.



We should assign initial value through arrow operator like third and fourth line in below snippet. Using brace to assign value as the same as first snippet is wrong syntax.



With a complex struct definition, this way increases many redundant code. Using brace to assignment initial value without creating redundant identifier could be done like this.



But I consider writing (*aPtr) = { 1, 2 }; may be the most intuitive way and it doesn't conflict with other syntax in C.

 

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.

 

Sunday, August 23, 2009

LWP, cURL, OpenSSL and Posterous

The fun of programming is there is always subtle mechanism in implementation. It costs time to discover but sometime is deserving. for example.

$ curl --basic -u <user> http://example.com/api/

$ echo -n "user:pass" | openssl base64 -e

and



to



 

Monday, August 17, 2009

Posterous API in Perl

Posterous.com is a new (micro)-blog mesh-up system.

You can use it mesh up almost all your (micro)-blog. Post once, Publish Everywhere. And there is still many funny features.

It looks pretty good, so I translated its API to Perl. You can get it from CPAN. Still work in progress, but would be productive soon.

 

Monday, June 8, 2009

Pseudo-OO syntax in C

總是會忘記的 syntax



 

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

 

Thursday, November 6, 2008

perl work with growl

Excerpt from
http://oreilly.com/catalog/9780596526740/toc.html
and
http://search.cpan.org/~cnandor/Mac-Growl-0.67/lib/Mac/Growl.pm

A quick method to post notification to Growl.


#!/usr/bin/env perl

use warnings;
use strict;

use Mac::Growl qw(:all);

Mac::Growl::RegisterNotifications(
# register your application in Growl before posting.
# just one time enough.
'growlalert', # app name
['alert'], # all notification
['alert'], # default notification
);

Mac::Growl::PostNotification(
# post notification to Growl
"growlalert", # app name
"alert", # notification type
"this is a title", # alert title
"this is a description", # alert content
);


 

Monday, October 13, 2008

push in scheme


01 (define push
02 (lambda (element stack)
03 (append stack (cons element '()))))
04
05 (push 'd '(a b c)) ; => (a b c d)


Though putting element before stack is a little weird XD.

 

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]


 

Wednesday, July 30, 2008

basic gnuplot script

for plotting band data generated by mit photonics band

01 set title "band of te mode"
02 set term png
03 set output "te.png"
04
05 plot \
06 "te" using 2:7 title "band 1" with linespoints, \
07 "te" using 2:8 title "band 2" with linespoints, \
08 "te" using 2:9 title "band 3" with linespoints, \
09 "te" using 2:10 title "band 4" with linespoints, \
10 "te" using 2:11 title "band 5" with linespoints, \
11 "te" using 2:12 title "band 6" with linespoints, \
12 "te" using 2:13 title "band 7" with linespoints, \
13 "te" using 2:14 title "band 8" with linespoints


 

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.

 
 

Saturday, May 17, 2008

sample scheme

hello, world! here
#!/usr/bin/guile -s
!#
(write "hello, world!")


define function
(define square (lambda (n) (* n n) ) )
(write (square 3) ) ; output 9


link1: The Scheme Programming Language 3/e
link2: Scheme Tutorial
 
 

Monday, May 12, 2008

self.pm

some convenient usage I prefer. :p
package PackageName;
use self;
use strict;

my @args;

sub new {
@args = args;
for (@args) {
blah~!
}
bless {}, self;
}

1;

self.pm++
 
 

Saturday, April 26, 2008

learning perl review ch2


scalar:
    1.233, 2E-3, 3e45
# exponential float
123_123_234
# integer with underscore
0377, 0xff, 0b1111
# octal => 0, hexadecimal => 0x, binary => 0b
"hello,"."world!"
# concatenate with .
"hello" x 3
# repeat 3 time with x
"20fred" * 3
# ignore string when transform
$str = $str . "blah"; === $str .= "blah";
$int = $int ** 3; === $int **= 3;
# binary assignment operator
${word}blah~
# insert variable with dereference brace
eq == | ne != | < lt | > gt | <= le | >= ge
# string comparison operator

# return with \n at line end
defined($var)
# return true or false

initial parameters (perl -M)
    use warnings;
use diagnostics;