Archive for June, 2009

Basic OO in Java

OO特性:封裝、繼承、多態
高級特性:static, final, abstract, interface
Class: 具有相同屬性和行為的抽象集合
Object: an instance of a class
[modified] class class_name{
type attribute_name // attribute
return_type method_name (parameters)[{method}] // method
}
parameter可省,但括號必須保留
method實做可省
Constructor method:對obj初始化
沒有return_type,與class_name相同,new時用
Local variable: in method
membership varaible: in class
  • OO特性:封裝、繼承、多型
  • 高級特性:static, final, abstract, interface
  • Class: 具有相同state和behavior的抽象集合
  • Object: an instance of a class

Syntax

  • method的parameter可省,但括號必須保留; method的實做可省
  • member variable (in class) & local variable (in method), no global varaible

[modified] class class_name{

type attribute_name // member variable declaration

return_type method_name (parameters)[{method}] // method declaration

}

  • 賦值或相等
    • “=”:  (primitive) assignment / (obj) reference to the same obj
    • “==”: (primitive) equal / (obj) reference to the same obj?
  • equals method
    • Wrapper Class: equals () // the same value?
    • Class: equals (==) // reference to the same obj?
    • primitive: equals (x) // 不能使用method
  • Initialization種類:
  1. constructor method: 沒有return_type,與class_name相同,new時才能使用
  2. default: 定義class時直接指定,固定
  3. lazy init (empty): setter/getter
  • Initialization順序 (important):
  1. member variable // it can be used in all method(include constructor method)
  2. constrictor method
  3. general method在使用時才會初始化
  • Method Overload: the same method_name, different parameters (e.g. multiple constructors)
  • Object
    • toString : override
    • equals :
      1. primitive 跟 == 一樣
      2. obj
  • casting:
    • upcasting時,不可訪問子類新增加的成員屬性/方法

Animal a = new Cat(“Garfi”); // upcasting

    • downcasting時(特化),需要強制轉型
  • polymorphism/dynamic binding (execution time)

根據實際類型調用方法

    1. inherit
    2. override
    3. super reference to sub object

雷電範例

  • abstract:
    • 有abstract method,此class也必須定義為abstract
    • 不能實體化
  • final:  不能改變/重寫/繼承
  • interface:
    • 一種特殊的抽象類:
      1. 只有public final static常數 (不寫修飾也是)
      2. public方法定義(沒有實現)
    • 一樣可以使用多型
    • 可以實做多個介面
    • 不同類可以實做單一介面
    • 介面可以繼承介面

Primitive Data Type of python

Dictionary # 並沒有順序的概念,事實上是hash table的一個實例
d = {“server”:”mpilgrim”, “database”:”master”, 3: 500}
# key and value, 可用key取值,卻不能用value取key
# 可用數字,字串跟tuple為key,但不能用list,因為list可以改變
調用: d[“server”] # Key是大小寫敏感的
修改: d[“server”] = “mac” # 可以隨時加入新的kv, 但如果使用同key,會蓋掉value
刪除: del d[“database”]
清空: d.clear()
dictionary如何排序?
List # 有序元素,可以”重複”,類比Java的Arraylist
li = [“a”, “b”, “mpilgrim”, “z”, “example”]
調用: li[0], li[-1] # 最後一個元素等於li[len(li)-1]
切片: li[0:3] # 只有三個元素,並不含li[3],切出第一個想要跟第一個不想要
切片簡寫: li[:3], li[3:], li[:] # 拷貝一個新的list
加入元素: li.append(“apple”), li.append(2,”mac”) # 將mac加到li[2]的位置, 無傳回
連接串列: li.extend(li), li.extend([a,b]) # 無傳回值
# extend只接受一個參數list,將裡面的元素加入,但append會將整個list當成一個元素
搜尋: li.index(“mac”) # 傳回位置,如果沒找到會傳回異常
存在: “apple” in li # 傳回布林值,此例是False
刪除: li.remove(“mac”) # 刪除第一次出現的mac,如果有兩個mac,無此值會異常
pop: out = li.pop() # 會刪除li[-1]並回傳它,可以指定位置
運算: newl = li + li; new1 = li * 2 # 效果等於extend,但會傳回新字串,較extend慢

Tuple # 是不可變的 list。一旦創建了一個 tuple,就不能以任何方式改變它。
tupe用小括號,但沒有method,如remove, pop,append 也不能更改它
但是tuple速度比list快
如何tuple跟list互轉
類似enum的作法
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
布林值 # 注意是大寫
0, “”, [], (), {} 都是False
任意value, list, tuple, dictionary都是True
待續

Multiple arguments(keyword assignment) and factory method

class Cheese():
def __init__(self, *args, **kwargs):
#args — tuple of anonymous arguments
#kwargs — dictionary of named arguments
self.num_holes = kwargs.get(‘num_holes’,random_holes())
to explain better concept of *args and **kwargs (you can actually change these names):
def f(*args, **kwargs):
print ‘args: ‘, args, ‘ kwargs: ‘, kwargs
>>> f(‘a’)
args: (‘a’,) kwargs: {}
>>> f(ar=’a’)
args: () kwargs: {‘ar’: ‘a’}
>>> f(1,2,param=3)
args: (1, 2) kwargs: {‘param’: 3}
Source Factory Class Also, Learning python adv OO

Return sorted indices

Input:

spam = [2,3,1,4,5]
Output:
list(index for index, item in sorted(enumerate(spam), key=lambda item:item[1]))
list(index for index, item in sorted(enumerate(spam), key=lambda item:item[1], reverse=True))
Hint:
Using the new key = parameter.
sorted(d.items(), key=lambda (k,v): (v,k))
key returns the “sort key” that sort will do the comparison on.

A byte of python (Quick note)


Executable python
#!/usr/bin/env python
$ chmod a+x filename.py
String
raw string ignore the escape symbol
r”This is raw \n”
unicode string
u”いい天氣です”
Long String
“””something new
today
“””
Explicit line join
print \
i
equivalent to
print i
Operator
// (floor division, return the floor)
% (modulo, return the remainder)
&|^~ (and, or, xor, not) bit operator
!= (not equal to)
and (short-circuit evaluation, boolean AND)
or (short-circuit evaluation, boolean OR)
Control Flow
  • if(elif,else)
  • for (else optional)
  • while (else optional)
  • break (also break the else clause, can be used with if, for and while)
  • continue ( skip the rest of the statements in the current loop block and to continue to the next iteration of the loop, can be used with for and while)
Some built-in function
int(raw_input(“prompt you like : “))
len()
range()

for i in range(1,5) #1,2,3,4 (5 is not included)
which is equivalent to c syntax
for (int i= 1; i < 5; i++)

for i in range(1,5,2) # 1, 3
Function
def func(): # no parameters function
def func(a, b=5, c=10): # default argument values
Calling as follow:
func(3,7)
func(25, c = 24)
func(c = 40, a = 100) # use keyword arguments
Note the terminology: argument and parameter
Global variables
global x
x = 2
Return statement
Every function implicitly contains a return None statement at the end unless you have written your own return statement.
The pass statement is used in Python to indicate an empty block of statements.

DocString
First line: sentense; Second line: blank; The others: detailed explanation
We can access it using the dot attribute such as print printMax.__doc__
others

XRDP on ubuntu

$ sudo apt-get install libpam0g-dev
$ sudo apt-get install libcurl4-openssl-dev

$ tar -zxvf xrdp-0.4.1.tar.gz
$ cd xrdp-0.4.1
$ make
$ sudo make install

$ sudo apt-get install tightvncserver # don’t use vino
$ gconftool-2 –type list –list-type=string –set /desktop/gnome/peripherals/keyboard/kbd/layouts [damnlayouts] # map keyboard layout
OR disable the keyboard plugin of the gnome-settings-daemon using gconf-editor:
/apps/gnome_settings_daemon/plugins/keyboard set active to False.
$ sudo nano /etc/xrdp/sesman.ini
change 127.0.0.1 to 0.0.0.0
$ sudo /usr/local/xrdp/xrdp_control.sh start # after reboot

Now, you can remote control your ubuntu via RDC from windows

python interface for libsvm on Leopard with default python

/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python <==origin python

modified Makefile
============================
CXX? = g++
SWIG ?= swig
#Windows: see ../README ../Makefile.win
PYTHON_INCLUDEDIR ?= /System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/
CFLAGS = -O3 -I$(PYTHON_INCLUDEDIR) -I..
#LDFLAGS = -shared
# Mac OS
LDFLAGS = -framework Python -bundle
all: svmc.so
svmc.so: svmc_wrap.o svm.o
$(CXX) $(LDFLAGS) -o svmc.so svmc_wrap.o svm.o
svmc_wrap.o: svmc_wrap.c ../svm.h
$(CXX) $(CFLAGS) -fPIC -c svmc_wrap.c
svmc_wrap.c: svmc.i
$(SWIG) -python -noproxy svmc.i
svm.o: ../svm.cpp ../svm.h
$(CXX) $(CFLAGS) -fPIC -c ../svm.cpp
clean:
rm -f *~ *.o *.so *.pyc *.pyo svm.o
moreclean: clean
rm -f svmc_wrap.c