30 Apr 2009

Python Tips - python流程图生成

中文ubuntu论坛python社区anticlockwise的文章(原文)
转载请注明版权.

This is a python flow chart drawing implementation.





#!/usr/bin/env python
# -*- coding: utf-8 -*-

# flow_parser.py
# author: Rongzhou Shen
# date: 2009-02-11

from pyparsing import *

# PYPARSING DEFINITION =========================
LSQUARE, RSQUARE, SEMI, ASSIGN, QUOTE = map(Suppress, '[];="')
LBRACE, RBRACE, AT, LBRACK, RBRACK = map(Suppress, '{}@()')

# Definition part of the flow_def file
node_id = Word(alphanums + "_")("id")
node_type = Word(alphas)("type")
declaration = node_type + LSQUARE + node_id + RSQUARE
value = QuotedString('"')
definition = Group(declaration("declaration") + ASSIGN + value("value") + SEMI)

# Flow part of the flow_def file
flow = Group(node_id + OneOrMore(Group('=>' + node_id)) + SEMI)

# Grammar definition of the whole file
flow_impl = OneOrMore(definition)("definitions") + OneOrMore(flow)("flows")
flow_def = AT + LBRACK + QuotedString('"')("flow_name") + RBRACK + LBRACE +\
flow_impl("flow_impl") + RBRACE
# END PYPARSING DEFINITION ==============================

#sample = """
#@("A test flow_chart") {
#    process[node1] = "This is a test process";
#    process[node2] = "This is another test process";
#    a => b => c;
#    ffew => fweji;
#}"""

def test_parse():
expected = ['process', '[', 'node1', ']', '=', '"',
'This is a test process', '"', ';']
test_def = 'process[node1] = "This is a test process";'
data = definition.parseString(test_def)
assert len(data) == len(expected)
assert all([x == y for x, y in zip(expected, data)])

expected = ['a', '=>', 'b', '=>', 'c', ';']
test_flow = 'a => b => c;'
data = flow.parseString(test_flow)
assert len(data) == len(expected)
assert all([x == y for x, y in zip(expected, data)])


用法如下:

Usage:

@("This is a test graph") {
process[p1] = "This is a test process";
process[p2] = "This is another process";
condition[c1] = "This is a condition";

p1 => p2;
c1 => p1;
c1 => p2;
}


结果如下:

The flow chart generated is:


Python Tips - python IDLE自动补全

python 2.6.2在windows下好好的自动补全,
到了ubuntu下就没有了作用,但是ipython这个改进的交互式python解释器则可以.
方法如下:

If you want to use auto complete function in ubuntu, you need to install ipython like:



sudo apt-get install ipython


--------------------------------------
ubuntu904+VMware+python2.6,尚未测试成功下面这个方法.
另外一个方法就是麻烦点,每次开python之后输入:

Another method is a little bit complicated:
(This methods hasn't been tested)

>>>import readline, rlcompleter
>>>readline.parse_and_bind("tab: complete")


保存为~/.pythonstartup.py之后,加入~/.bashrc

Then add it to your ~/.bashrc file:

export PYTHONSTARTUP=~/.pythonstartup.py

29 Apr 2009

Ubuntu Tips:安装vm tools

vmware虚拟ubuntu9。04之后出现一些问题,
对vm tools不再支持,安装之后下次重启,依然要求你继续安装,
发现是安装有问题,google得到的解答,需要安装open-vm-tools
我是用的是源码安装方法:

There're some problem to install vm tools for ubuntu9.04, which it always require to be installed although you have done so. The answer from google is to install open-vm-tools. You can download it from sourceforge.

##CONTINUE##


tar -xzf open-vm-tools-*.tar.gz
sudo ./configure --without-x
sudo make
sudo make install


如果编译碰到没有gettext,glib版本过低问题,运行下面的命令应该会搞定:

If you meet any problem whilst compiling open-vm-tools, run the following command in terminal:


sudo apt-get install libproc-dev libdumbnet-dev libicu-dev libglib2.0-dev libglib1.2-dev


如果编译安装完全正确,打包文件拷贝到vm tools安装目录:

If you have done the compiling and installing procedures, tar the following files then put them into vm tools directory as:


cd modules/linux

for i in *; do mv ${i} ${i}-only; tar -cf ${i}.tar ${i}-only; done
cd ../../../
mv -f open-vm-tools-*/modules/linux/*.tar vmware-tools-distrib/lib/modules/source/


最后重新安装vm tools:

Finally, execute the install command as:


sudo ./vmware-install.pl

26 Apr 2009

Python Tips - 获得网页超链接

获得网页所有超级链接

get all hyperlinks



#!/usr/bin/env python
# get all hyperlinks

from re import compile as reComp
from urllib import urlopen, basejoin

def getURL(http, num=10):
""" get all hyperlinks and print the first num"""
data = urlopen(http).read()
regex = reComp(r'href="([^"]+)"')
urls = regex.findall(data)
for url in urls[:num]:
print basejoin(http, url)
#print url

def main():
getURL("http://52xenos.blogspot.com",5)

if __name__ == '__main__': main()


输出结果如下:

Results:
http://52xenos.blogspot.com/feeds/posts/default
http://52xenos.blogspot.com/feeds/posts/default?alt=rss
http://www.blogger.com/feeds/7524190211354587233/posts/default
http://www.blogger.com/rsd.g?blogID=7524190211354587233
http://www.blogger.com/profile/07043019578098595151

23 Apr 2009

Ubuntu Tips - 右键添加“打开终端“

Ubuntu默认右键不能打开终端,记得学校里redhat的kde环境下是可以的,
非常方便,google了下,方法如下:

Under the kde environment in RedHat, it's easy to open terminal everywhere by rightclick. Here is the method to add this feature to your ubuntu:

##CONTINUE##


sudo apt-get install nautilus-open-terminal

Ubuntu9.04发布

Ubuntu9.04今日正式发布

The new Ubuntu9.04 has been released today.

看官网介绍,904的新特性不少,具体请看:

Follow this link to see the new features of ubuntu 9.04:

http://www.ubuntu.com/

下载地址:

Download page:

http://releases.ubuntu.com/releases/9.04/

贴几个图:

Some screenshots of ubuntu 9.04:

##CONTINUE##
登陆界面:

Log in:



桌面:

Desktop:

20 Apr 2009

Python Tips - 日期字符串格式化

Python中的datetime和time模块用来处理日期格式,具体实现请看示例:

Using datetime and time modules in Python:



>>> import time
>>> t1 = time.localtime()
>>> t1
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=20, tm_hour=20, tm_min=8, tm_sec=47, tm_wday=0, tm_yday=110, tm_isdst=1)
>>> strFormat = "%Y-%m-%d %H:%M:%S"
>>> t2 = time.strftime(strFormat)
>>> t2
'2009-04-20 20:09:29'


所有格式化字符串意义如下:

All format strings are listed as following:
%a   Abbreviated weekday name
%A  Full weekday name
%b  Abbreviated month name
%B  Full month name
%c  Date and time representation appropriate for locale
%d  Day of month as decimal number (01 - 31)
%H  Hour in 24-hour format (00 - 23)
%I  Hour in 12-hour format (01 - 12)
%j  Day of year as decimal number (001 - 366)
%m  Month as decimal number (01 - 12)
%M  Minute as decimal number (00 - 59)
%p  Current locale's A.M./P.M. indicator for 12-hour clock
%S  Second as decimal number (00 - 59)
%U  Week of year as decimal number, with Sunday as first day of week (00 - 51)
%w  Weekday as decimal number (0 - 6; Sunday is 0)
%W  Week of year as decimal number, with Monday as first day of week (00 - 51)
%x  Date representation for current locale
%X  Time representation for current locale
%y  Year without century, as decimal number (00 - 99)
%Y  Year with century, as decimal number
%z, %Z  Time-zone name or abbreviation; no characters if time zone is unknown
%%  Percent sign


再附上一个网友收藏的日期处理及格式例子:

Another example from the internet:
#!/usr/bin/python
#coding:utf-8
import datetime
import time

format="%Y-%m-%d %H:%M:%S"
t1=time.strptime("2008-01-31 00:11:23",format)
t2=datetime.datetime(t1[0],t1[1],t1[2],t1[3],t1[4],t1[5],t1[6])
t3=t2-datetime.timedelta(minutes=30)
t3=str(t3)

b1=t3[0:4]
b2=t3[5:7]
b3=t3[8:10]
b4=t3[11:13]
b5=t3[14:16]
b6=t3[-2:]

print b1
print b2
print b3
print b4
print b5
print b6


另一种 时间格式化方法 xiaoyu9805119 提供

datetime formats method from xiaoyu9805119
a="2009-02-15 21:00:08"
import re
s=re.split("\D*",a)
print s


另一种 时间加减方法 3227049提供

datetime computes method from 3227049
import datetime,time
format="%Y-%m-%d %H:%M:%S"
result=datetime.datetime(*time.strptime("2008-01-31 00:11:23",format)[:6])-datetime.timedelta(minutes=30)
print result.strftime(format)

12 Apr 2009

Python学习笔记 - 6:元组,列表及字典

本文内容主要关于: Python中的三大类型 - 元组(tuple), 列表(list)和字典(dict)

This article would talk about the three important types in Python: tuple, list and dict.


======================================================
25.04.09更新:
今天看到以前写的一个python笔记,更新一下

tuple, list, dict的区别
1. 定义: tuple用()或者直接用分号间隔开一系列元素, list用[], dict用{}
例如: t1=’a’, ‘haha’, 1, 3 或者 t2=(‘a’, ‘haha’,1, 3)
lst1=[‘a’,’haha’, 1, 3], dict1 = {1:’a’, 2:’haha’, 3:1, 4:3}
dict有特殊的构建方法,例如:
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])或者
dict(sape=4139, guido=4127, jack=4098)
2. 操作: tuple一旦定义,不可改变其值; list和dict可以.list可以使用append方法添加元素, dict可直接添加,好像maping一样.
3. 引用: 都必须用[],但是tuple和list用id, dict则必须用键值/key才能索引.
4. 特殊的数据类型set: set([list])可以返回list中所有不重复元素


list当作queue和stack的区别
当queue使用时, 先入先出操作要用pop(0)这个方法; 
当stack使用时,后入先出操作直接使用pop(), 不用指定index会默认return最后一个element.

======================================================

1, 元组(tuple) - 不可改变的列表 ( un-changeable list)

任意对象的序列都可以组成元组,创建一个元组的方法是:用小括号()把这些对象括起来.例如:

Tuple could be constructed by any objects, just simply put all the objects into a brackets().
For example:

>>> t = (1, 2, 3, 'a')
>>> t
(1, 2, 3, 'a')
>>> for i in t:
print i

1
2
3
a
>>>


元组序列索引号从0开始,可以用t[i]来取得元组的第i+1个元素,可以用len()函数得到元组的长度.
元组最大的特点是值不可修改,如果试图修改一个元素的值,会返回错误TypeError,例子如下:

The index of tuple starts from 0, which means you could obtain the value of i+1 element by t[i].
The length of a tuple can be got by function len().
Tuple can be considered as a list, except you can not change the value of its elements. If you try to do so, there would be a TypeError. (See the example below)


>>> t=(1,2,3)
>>> len(t)
3
>>> t
(1, 2, 3)
>>> t[1]
2
>>> t[1] = 'a'

Traceback (most recent call last):
File "", line 1, in 
t[1] = 'a'
TypeError: 'tuple' object does not support item assignment


2, 列表(list) - Python中最常用的类型 (the most popular type in Python)

列表跟元组很相似,都可以由任意对象组成,索引都从0开始;最大(也可能是唯一)的区别是:列表元素的值可以被改变.
使用切片操作可以得到子序列,也可以对序列进行赋值,查找,增加,删除,逆转等操作

List has some properties as tuple, like can be composed by any objects, the index starts from 0.
The most important difference between list and tuple is: the values of lists' elements can be changed.
Some operations can be applied to list are: assign, search, delete, reverse, and so on.

>>> a = range(5)  # generate a list from 0 to 4
>>> a
[0, 1, 2, 3, 4]
>>> a[2]  # get the value of index 2
2
>>> a[3] = 'e'
>>> a
[0, 1, 2, 'e', 4]
>>> a[2:4]  # slice, from index 2 to 4, excluding 4, like[2,4)
[2, 'e']
>>> a[:3]   # slice, from start(0) to 3, excluding 3, like [0,3)
[0, 1, 2]
>>> a[2:]   # slice, from index 2 to the end, like [2,len(a)-1]
[2, 'e', 4]
>>> a[:]    # slice, whole list copy, this method does not return a new object
[0, 1, 2, 'e', 4]
>>> a.append('last')    # append element to the end
>>> a
[0, 1, 2, 'e', 4, 'last']
>>> a.index('e')    # return the index of 'e' of the first occurrence
3
>>> a.index('a')    # return ValueError if 'a' is not in the list

Traceback (most recent call last):
File "", line 1, in 
a.index('a')
ValueError: list.index(x): x not in list
>>> a.reverse()     # reverse the list
>>> a
['last', 4, 'e', 2, 1, 0]
>>> a.remove('e')   # remove the first element with specified value
>>> a
['last', 4, 2, 1, 0]
>>> del a[3]        # remove an element in the specify position
>>> a
['last', 4, 2, 0]
>>> b = ['a','b','c']
>>> a.extend(b)     # extend another list at the end of the current one
>>> a
['last', 4, 2, 0, 'a', 'b', 'c']
>>> a.insert(2,'new item')  # insert an element into the list at the specify position
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c']
>>> a+= [1,2]       # use + oeration to concatenate lists
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c', 1, 2]
>>> a.count(2)      # count the number of 2 in the list
2
>>> a.pop()         # return the last element and delete it from the list
2
>>> a.count(2)
1
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c', 1]
>>> a.sort()        # sort the list, there are some parameters can be found from the document
>>> a
[0, 1, 2, 4, 'a', 'b', 'c', 'last', 'new item']


3, 字典(dict) - Python中的哈希表 (Hash table in Python)

>>> a
{'username': 'xenos', 'blog': 'http://52xenos.blogspot.com/', 'uid': 1} # new dict object
>>> a['username']   # return value according to the key 'username'
'xenos'
>>> a['username'] = 'daniel'    # refine the value of the key 'username'
>>> if a.has_key('username'):   # find if there is a pair "key:value" in the dict, if no, return Wrong
print a['username']
else:
print 'Wrong'

daniel
>>> a.get('username','Wrong')   # same as the if...else... shown above
'daniel'
>>> a.keys()    # return all keys in a list
['username', 'blog', 'uid']
>>> a.values()  # return all values in a list
['daniel', 'http://52xenos.blogspot.com/', 1]

8 Apr 2009

DELL D630实现立体混音

DELL D630不支持声卡边录边放和立体混音,但是可以通过以下方法实现:

##CONTINUE##


其实最简单的方法:
安装公版的声卡驱动,下载地址:
http://www.lge.com/support/software.jsp

下载方法:
选择地区(Your location)
比如:asia,HongKong

然后选择搜索框中的
Product: NOTEBOOK
并在subject中填写: SIGMATEL
然后搜索,出的结果是3个,选择最大的哪个文件,文件名为:SIGMATEL.zip (大约92M)

下载完了解压缩,然后setup
到此已经完成全部操作。

注意:需要把原来装的驱动删了再装,,就没问题了
=================================

另外一种方法,修改注册表:



一、如何实现边录边听功能?(即启用“输入监视器”)。

1.单击“开始”菜单,选“运行”,在运行框里输入regedit,然后敲回车即可运行注册表编辑器

2.在注册表编辑器菜单中选择“编辑”-》“查找”,并且输入查找词“enableinputmonitor”,

3.查找到该项后,双击修改为01。
注意:操作上面步骤后,需点击“查找”下面“查找下一个”,发现还有另一个“enableinputmonitor”,也要修改过来,否则不能成功。

4.重启系统,将在音量控制窗口,出现“输入监视器”。如果第一次重启不成功,要确认是否已经修改过来,如没有,再执行一次。
注意:如果有内置麦克风,默认静音,如果没有外置麦克风接入,且不选静音,会产生强烈啸叫。

这样即可实现声卡的边录边放功能了。

二、如何实现可调整的“输入监视器”的音量?

方法:
请在注册表中搜索“DigitalInputMonitor”,并将其设置成01。Windows自带的音量控制程序中,输入监视器的音量已经可以调整了。

三、如何进一步修改注册表实现立体混音?

什么是混音?

混音器的作用是将来自音乐合成器、CD-ROM、话筒输入(MIC)等不同来源的声音组合在一起再输出,混音器是每种声音卡都有的。数字声音效果处理器是对数字化的声音信号进行处理以获得所需要的音响效果(混响、延时、合唱等),数字声音效果处理器是高档声卡具备的功能。

方法:
请在注册表中搜索“DigitalStereoMix”,并将其设置成01,(具体方法同“DigitalInputMonitor“。

4 Apr 2009

Python学习笔记 - 5:程序流程控制(循环和条件语句)

本文主要有:程序流程控制(循环和条件语句)

This article is mainly about programme flow control

Python中的程序逻辑控制与其他语言无二,主要是循环和条件.
(注意Python中并无switch语句,需要使用if...else...)

As same as the other popular programming languages, Python uses
Loop and Conditional statements for programme control.
(Note: There's no switch statement in python, you have to use
if...else... instead.)



记住: 对所有循环,如果需要用到range(),请永远用xrange()来代替,以便得到较高的效率.xrange()并不会立即返回一个列表对象,只有在需要的时候才会计算列表中的某个值.

Note: for all loops, NEVER use range(), but xrange() instead. xrange() has much better performance than range(), due to it does not return a list object immediately, the values would not be computed until they have to be.

循环结构:
2种循环分别是For循环和While循环.
格式如下:

Loop:
There are two types of loops: For loop and While loop.
Both of them can be used as Non-nested and Nested.

1. 非嵌套格式

1. Non-nested structure

for condition:
do something
...

while condition:
do something
...


2. 嵌套格式

2. Nested structure

for condition1:
do something1
...
for condition2:
do something2
...
for condition3:
do something3
...
...
...

while condition1:
do something1
...
while condition2:
do something2
...
while condition3:
do something3
...
...
...


下面是个例子:

An example:

>>> a = range(4)
>>> for i in a:
print 'i= %d.' % i

i= 0.
i= 1.
i= 2.
i= 3.
>>> i
3
>>> i=0
>>> while i in a:
print 'i=%d.' % i
i+=1

i=0.
i=1.
i=2.
i=3.
>>> j = 1000000
>>> j = 10000
>>> i = 1
>>> while i in xrange(j):
print 'i=%d.' % i
i+=1

i=1.
i=2.
i=3.
i=4.
i=5.
...
i=9999.


如果你想在循环过程中加以控制,需要使用break与continue.
break: 跳出循环/如果是嵌套循环,只能跳出break所在层
continue: 结束本次循环,继续执行下一次循环

You have to use break and continue to control the programme within loops.
break: break the loop/ONLY break the current layer loop if using in nested loops
continue: skip the current loop, go on to execute the next one

条件结构: if...else...,结构如下:

Conditional statement, if...else..., the structure is:

if condition:
do something1
else:
do something2


为了方便:

for short:

if condition: do something1
else: do something2


测试如下:

An example:

>>> a = [0,1,2,3]
>>> if i in a:
print 'i is in a.'
else:
print 'i is not in a.'

i is not in a.