yunshichen

我相信人生是值得活的,尽管人在一生中必须遭受痛苦,卑劣,残酷,不幸和死亡的折磨,我依然深信如此.但我认为人生不一定要有意义,只是对一些人而言,他们可以使人生有意义. ---J 赫胥黎

2011年4月28日

Python 应用X: 工具集合

     摘要: 简介 记录自己做的一些稀奇古怪的程序. 工具一: 查找单词解释 原理: http://dict.cn/ 提供了查词的引擎, 输入单词即可以得到解释. 所以这个程序只是做一些体力活. 代码如下: (有朋友反映复制之后出错. 若如此请移步到这里下载这个脚本: http://www.uudisc.com/user/diegoyun/file/4131948Code highlig...  阅读全文

posted @ 2011-04-28 02:08 Chenyunshi 阅读(1629) | 评论 (5)编辑 收藏

Subprocess 操作, 如 Linux 下的shell 和 Windows 下的批处理


基本命令

东拼西凑查了好久, 才总算把这个命令补完全. 不废话, 直接上代码.

def exec_command(cmdlist,working_dir,view_result=False):
    
if isinstance(cmdlist, str):
        cmdlist 
= [cmdlist]
        
    cmd_seperator 
= ";"
    
import platform
    
if platform.system() == "Windows":
        cmd_seperator 
= "&&"
    
    runCmd
=""    
    
for cmd in cmdlist:
        
if runCmd=="":
            runCmd 
= runCmd + cmd
        
else:
            runCmd 
= runCmd + cmd_seperator + cmd
    
    p
=subprocess.Popen(runCmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE,cwd=working_dir)
    out,err 
= p.communicate()
    result 
= {'out':out,'err':err,'returncode':str(p.returncode),'pid':str(p.pid)}
    
if view_result:
        
print "===== Printed result: "
        
print "--> Run cmd: " + runCmd
        
print "--> returncode: " + result["returncode"]
        
print "--> out: " + result["out"]
        
print "--> err: " + result["err"]
        
    
return result

exec_command(["ls -l","uname -a"],".",True)


扩展功能1: CVS 操作

这个功能无甚神秘. 首先要安装有cvs, 其次要设置cvsroot. 最后, 你要时不时查查cvs的命令.

我承认拼凑这个程序还是费了不少时间, 所以有记下来的必要.

#!/usr/bin/python
#
 -*- coding: utf-8 -*- 
'''
Created on Apr 28, 2011

@author: yunshichen@gmail.com
'''
import string
import subprocess
import platform

def exec_command(cmdlist,working_dir,view_result=False):
    
if isinstance(cmdlist, str):
        cmdlist 
= [cmdlist]
        
    cmd_seperator 
= ";"
    
if platform.system() == "Windows":
        cmd_seperator 
= "&&"
    
    runCmd
=""    
    
for cmd in cmdlist:
        
if runCmd=="":
            runCmd 
= runCmd + cmd
        
else:
            runCmd 
= runCmd + cmd_seperator + cmd
    
    p
=subprocess.Popen(runCmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE,cwd=working_dir)
    out,err 
= p.communicate()
    result 
= {'out':out,'err':err,'returncode':str(p.returncode),'pid':str(p.pid)}
    
if view_result:
        
print "===== Printed result: "
        
print "--> Run cmd: " + runCmd
        
print "--> returncode: " + result["returncode"]
        
print "--> out: " + result["out"]
        
print "--> err: " + result["err"]
        
    
return result

class DPY_CVS():
    
def __init__(self,cvs_cmd,cvs_root,is_debug=True):
        self.cvs_cmd 
= cvs_cmd
        self.cvs_root 
= cvs_root
    
    
def checkout(self,working_dir,proj,opts=None):
        
'''
        opts holds optional for checkout command. For example:
        
        {'r': diego_test_tag,'d':my_local_path}
        
'''
        cmd_set_cvs_root 
= "set CVSROOT=" + self.cvs_root
        cmd_checkout 
= self.cvs_cmd + ' -q checkout ${optional_str} -P '+proj
        
        str
=""
        
if(opts <> None):
            
for key in opts:
                str 
= str + " -"+key + " " + opts[key]
        
        cmd_checkout 
= string.Template(cmd_checkout).substitute({'optional_str':str})
        
        self.result 
= exec_command([cmd_set_cvs_root,cmd_checkout],working_dir)
        
    
def tagFiles(self,working_dir,tagName,pathlist):
        
        cmd_set_cvs_root 
= "set CVSROOT=" + self.cvs_root
        cmd_tag_a_file 
= self.cvs_cmd + ' tag '+tagName+' ${cvs_file}'
        
        
if isinstance(pathlist, str):
            pathlist 
= [pathlist]
            
        cmdlist 
= [cmd_set_cvs_root]
        
for fpath in pathlist:
            
if fpath.startswith("/"):
                fpath 
= fpath[1:]
            cmd_tag 
= string.Template(cmd_tag_a_file).substitute({'cvs_file':fpath})
            cmdlist.append(cmd_tag)
        
        self.result 
= exec_command(cmdlist,working_dir)
        
    
def viewResult(self):
        r 
= self.result
        
print "\n\n\n------------------ CVS run result: -----------"
        
print "--->returncode: " + r["returncode"]
        
print "out:\n" + r["out"]
        
print "err:\n" + r["err"]
        





posted @ 2011-04-28 00:24 Chenyunshi 阅读(773) | 评论 (1)编辑 收藏

2011年2月14日

Python 数据库操作


打算把python连接db的例子都总结下来.

python连接sqllite

#!/usr/bin/python
#
 -*- coding: utf-8 -*- 
'''
Created on 2/13/2011

@author: yunshichen@gmail.com
'''

'''

tutorial link: http://docs.python.org/py3k/library/sqlite3.html

SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.

sqlite3 was written by Gerhard Häring and provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249.

To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the /tmp/example file:

'''

import sqlite3

DB_FILE 
= '/tmp/example'

def listData():
    conn 
= sqlite3.connect(DB_FILE)
    c 
= conn.cursor()
    
    
print "Lists data.\n"
    sql 
= "select * from stocks order by price"
    c.execute(sql)
    
for row in c:
        
print(row)
        
    conn.commit()
    c.close()
    

def clearTableData():
    conn 
= sqlite3.connect(DB_FILE)
    c 
= conn.cursor()
    
    sql 
= "delete from stocks"
    c.execute(sql)
    
    
print "All data are deleted.\n"
    conn.commit()
    c.close()

def insertData():
    conn 
= sqlite3.connect(DB_FILE)
    c 
= conn.cursor()
    
    insertData 
= "insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)"
    c.execute(insertData)
    
    
# Never do this -- insecure!
    #    symbol = 'IBM'
    #    c.execute(" where symbol = '%s'" % symbol)
    # Do this instead
    #    t = (symbol,)
    #    c.execute('select * from stocks where symbol=?', t)

    insertSql 
= 'insert into stocks values (?,?,?,?,?)'
    
for t in [('2006-03-28''BUY''IBM'100045.00),
              (
'2006-04-05''BUY''MSOFT'100072.00),
              (
'2006-04-06''SELL''IBM'50053.00),
             ]:
        c.execute(insertSql, t)

    
print "Set data into table stocks.\n"
    conn.commit()
    c.close()    

def initTable():
    conn 
= sqlite3.connect(DB_FILE)
    c 
= conn.cursor()
    
    createTable 
= "create table stocks (date text, trans text, symbol text, qty real, price real)"
    c.execute(createTable)
    
print "Created table stocks.\n"
    
    conn.commit()
    c.close()
    

'''
    运行例子:   ./sqllitetest.py -c init
'''
if __name__ =="__main__":
    
    
from optparse import OptionParser
    parser 
= OptionParser()
    
    parser.add_option(
"-c""--command", action="store",
                  dest
="cmd",
                  default
="init",
                  type
="string",
                  help
="Runs functions based on commands. Available commands are init,list,data,deleteAll "
    
    options, args 
= parser.parse_args()
    
    cmd 
= options.cmd
    
    
if(cmd=="init"):
        initTable()
        
    
if(cmd=="deleteAll"):
        clearTableData()
        
    
if(cmd=="data"):
        insertData()
        
    
if(cmd=="list"):
        listData()
        
    
    
    
    
    
    

posted @ 2011-02-14 00:02 Chenyunshi 阅读(902) | 评论 (0)编辑 收藏

2011年2月6日

python 小程序, 查找todo选项, 促进自己更好的管理时间

想法&需求

1>在看代码的时候, 总会想: 这个api很好, 这段代码用法很好. 总结下来. 但当看完书的时候就忘了.
2>有时候会无聊, 无所事事. 浪费了一段时间后才想起, 其实可以做XX, YY.

解决办法

1>在看代码的时候用注释方式做标记, 记录下来.
2>用小程序遍历这些代码, 找出这些标记.
3>将这些项记录到excel里. 无聊的时候就打开这个excel看看有什么东西做.

todo的例子(用一些ide可以方便生成大部分注释)

------------------------------
-------------------------- todo sample begin
#todo_begin:
#item: 配置一个方便的调试 spring3 + hibernate 3 的教程
#estimate: 4-8h
#file: /media/dev/utopism2008/projects/python/dpytools/src/findtodo/FindToDo.py
#todo_end:

#todo_begin:
#item: 总结xlrt 和 xlwt 用法. 特别是 nrows 和 写已有的excel
#estimate: 4h
#file: /media/dev/utopism2008/projects/python/dpytools/src/findtodo/FindToDo.py
#todo_end:
-------------------------------------------------------- todo sample end

程序源码:

  1 #! /usr/bin/python
  2 '''
  3 Created on Feb 6, 2011
  4 
  5 1>Find todo string in every file read. 
  6 2>Set this content into excel file. Every weekend I can check this file and make next plan based on these items. 
  7 
  8 @author: yunshichen@gamil.com
  9 '''
 10 # -*- coding: utf8 -*- 
 11 
 12 import os
 13 import ConfigParser
 14 
 15 import xlrd 
 16 import xlutils.copy
 17 import xlwt
 18 
 19 ITEM_KEY = "#item:"
 20 EST_KEY = "#estimate:"
 21 FILE_PATH_KEY = "#file:"
 22 
 23 '''
 24 A typical sample of todo item in file:
 25 
 26 #todo_begin:
 27 #item: To summarize usage of Qt4 widget
 28 #estimate: 5m
 29 #file: /media/dev/utopism2008/projects/python/dpytools/src/findtodo/FindToDo.py
 30 #todo_end:
 31 
 32 '''
 33 def findTodo(fpath,alist):
 34     todo_begin = "todo_begin"
 35     todo_end = "todo_end"
 36     isFinding = False
 37     fread = open(fpath,"r")
 38     aitem = None
 39     for line in fread:
 40         
 41         if todo_begin in line:
 42             isFinding = True
 43             aitem = {}
 44             continue
 45                 
 46         if todo_end in line:
 47             isFinding = False
 48             continue
 49         
 50         if( isFinding == False):
 51             continue
 52         
 53         if mapKeyValue(aitem,ITEM_KEY,line):
 54             continue
 55         
 56         if mapKeyValue(aitem,EST_KEY,line):
 57             continue
 58         
 59         if mapKeyValue(aitem,FILE_PATH_KEY,line):
 60             if FILE_PATH_KEY in line:
 61                 alist.append(aitem)
 62                 aitem = None
 63                 print "--Find todo item in " + fpath + "\n"
 64             continue
 65         
 66     
 67     fread.close()
 68     
 69         
 70 def mapKeyValue(item,key,line):
 71     if key in line:        
 72         #test
 73         print "key is:" + key + "\n"
 74         item[key] = line[len(key):]
 75         return True
 76     
 77     return False
 78     
 79 
 80 def findTodoFromFolder(alist,folder):
 81     for  parent, dirnames, filenames  in  os.walk(folder):
 82         for fname in filenames:
 83             findTodo(os.path.join(parent, fname),alist)
 84             
 85         
 86 def mainLogic():
 87     configFileName = "config.txt"
 88     cf = ConfigParser.ConfigParser();
 89     cf.read(configFileName)
 90     
 91     flist = cf.get("path""folder_list").split(",")
 92     itemlist = []
 93     for folder  in flist:
 94         findTodoFromFolder(itemlist,folder)
 95     
 96     excelPath = cf.get("path""excel_path")
 97     
 98     mapItemIntoExcel(itemlist,excelPath)
 99     
100     print "\n---- OK -------- \n"
101 
102 def createCellStype():
103     font = xlwt.Font()
104     font.wrap = xlwt.Alignment.WRAP_AT_RIGHT
105     style = xlwt.XFStyle()
106     style.font = font
107     return style
108     
109 
110 def mapItemIntoExcel(itemlist,excelPath):
111     try:
112                 
113         rb = xlrd.open_workbook(excelPath,formatting_info=True,on_demand=True)
114         wb = xlutils.copy.copy(rb)
115         sheet = wb.get_sheet(2)
116         
117         row_index = len(sheet.rows)
118         row_index += 1
119         
120         cellStyle = createCellStype()
121         for item in itemlist:
122             sheet.row(row_index).write(xlwt.Utils.col_by_name("A"),unicode(item[ITEM_KEY]),cellStyle )
123             sheet.row(row_index).write(xlwt.Utils.col_by_name("D"),item[EST_KEY] ,cellStyle)
124             sheet.row(row_index).write(xlwt.Utils.col_by_name("F"),"N"  ,cellStyle)
125             sheet.row(row_index).write(xlwt.Utils.col_by_name("H"),item[FILE_PATH_KEY]  ,cellStyle)
126             row_index += 1
127         
128         wb.save(excelPath)
129         
130     finally:
131         rb.release_resources    
132     
133 if __name__ =="__main__":
134     mainLogic();
135 
136 


程序和配置文件请在这里下载:  http://www.uudisc.com/user/diegoyun/file/3880743


如何运行
1> sudo apt-get install python-xlrt python-xlwt
2> 到这个页面下载 xlutis : http://pypi.python.org/pypi/xlutils#downloads   .
然后 sudo easy_install xlutils   该功能需要安装python 的 setuptools 功能. 如果没装,
ubuntu 会提示你安装.
3> 配置config.txt, 指定目录和excel路径
4> 运行 FindToDo.py




posted @ 2011-02-06 21:42 Chenyunshi 阅读(1280) | 评论 (3)编辑 收藏

2011年2月4日

ZT: Ubuntu find 命令

原帖地址: http://blog.csdn.net/evane1890/archive/2007/04/10/1559465.aspx

通用格式:find pathname -options [-print -exec -ok]
例子:
find / -name filename 再根目录里面搜索文件名为filename的文件
find /etc -name *s*在目录里面搜索带有s的文件
find /etc -name *S 在目录里面搜索以s结尾的文件
find /etc -name s*在目录里面搜索以s开头的文件
find / -amin -10在系统中搜索最后10分钟访问的文件
find / -atime -2查找在系统中最后48小时访问的文件
find / -empty 查找在系统中为空的文件或者是文件夹
find / -group groupname 查找在系统中属于groupname的文件
find / -mmin -5查找在系统中最后5分钟修改过的文件
find / -mtime -1查找在系统中最后24小时修改过的文件
find /-nouser查找在系统中属于费用户的文件
find / -user username 查找在系统中属于username的文件
find / -ctime -1查找在系统中最后24小时被改变状态的文件
find / -fstype type查找在系统中文件类型为?的文件
find / -user user1name -or -user user2name查找在系统中属于user1name或着属于user2name的文件
find / -user user1name -and -user2name在系统中查找既属于user1name又属于user2name用户的文件.

一、find 命令格式


1、find命令的一般形式为;

find pathname -options [-print -exec -ok ...]


2、find命令的参数;

pathname: find命令所查找的目录路径。例如用.来表示当前目录,用/来表示系统根目录。
-print: find命令将匹配的文件输出到标准输出。
-exec: find命令对匹配的文件执行该参数所给出的shell命令。相应命令的形式为'command' { } \;,注意{ }和\;之间的空格。
-ok: 和-exec的作用相同,只不过以一种更为安全的模式来执行该参数所给出的shell命令,在执行每一个命令之前,都会给出提示,让用户来确定是否执行。


3、find命令选项

-name
按照文件名查找文件。
-perm
按照文件权限来查找文件。
-prune
使用这一选项可以使find命令不在当前指定的目录中查找,如果同时使用-depth选项,那么-prune将被find命令忽略。
-user
按照文件属主来查找文件。
-group
按照文件所属的组来查找文件。
-mtime -n +n
按照文件的更改时间来查找文件, - n表示文件更改时间距现在n天以内,+ n表示文件更改时间距现在n天以前。find命令还有-atime和-ctime 选项,但它们都和-m time选项。
-nogroup
查找无有效所属组的文件,即该文件所属的组在/etc/groups中不存在。
-nouser
查找无有效属主的文件,即该文件的属主在/etc/passwd中不存在。
-newer file1 ! file2
查找更改时间比文件file1新但比文件file2旧的文件。
-type
查找某一类型的文件,诸如:
b - 块设备文件。
d - 目录。
c - 字符设备文件。
p - 管道文件。
l - 符号链接文件。
f - 普通文件。
-size n:[c] 查找文件长度为n块的文件,带有c时表示文件长度以字节计。
-depth:在查找文件时,首先查找当前目录中的文件,然后再在其子目录中查找。
-fstype:查找位于某一类型文件系统中的文件,这些文件系统类型通常可以在配置文件/etc/fstab中找到,该配置文件中包含了本系统中有关文件系统的信息。
-mount:在查找文件时不跨越文件系统mount点。
-follow:如果find命令遇到符号链接文件,就跟踪至链接所指向的文件。
-cpio:对匹配的文件使用cpio命令,将这些文件备份到磁带设备中。

另外,下面三个的区别:
  -amin n
  查找系统中最后N分钟访问的文件
  -atime n
  查找系统中最后n*24小时访问的文件
  -cmin n
  查找系统中最后N分钟被改变文件状态的文件
  -ctime n
  查找系统中最后n*24小时被改变文件状态的文件
   -mmin n
  查找系统中最后N分钟被改变文件数据的文件
  -mtime n
  查找系统中最后n*24小时被改变文件数据的文件


4、使用exec或ok来执行shell命令

使用find时,只要把想要的操作写在一个文件里,就可以用exec来配合find查找,很方便的

在有些操作系统中只允许-exec选项执行诸如l s或ls -l这样的命令。大多数用户使用这一选项是为了查找旧文件并删除它们。建议在真正执行rm命令删除文件之前,最好先用ls命令看一下,确认它们是所要删除的文件。

exec选项后面跟随着所要执行的命令或脚本,然后是一对儿{ },一个空格和一个\,最后是一个分号。为了使用exec选项,必须要同时使用print选项。如果验证一下find命令,会发现该命令只输出从当前路径起的相对路径及文件名。

例如:为了用ls -l命令列出所匹配到的文件,可以把ls -l命令放在find命令的-exec选项中

# find . -type f -exec ls -l { } \;
-rw-r--r-- 1 root root 34928 2003-02-25 ./conf/httpd.conf
-rw-r--r-- 1 root root 12959 2003-02-25 ./conf/magic
-rw-r--r-- 1 root root 180 2003-02-25 ./conf.d/README

上面的例子中,find命令匹配到了当前目录下的所有普通文件,并在-exec选项中使用ls -l命令将它们列出。
在/logs目录中查找更改时间在5日以前的文件并删除它们:

$ find logs -type f -mtime +5 -exec rm { } \;

记住:在shell中用任何方式删除文件之前,应当先查看相应的文件,一定要小心!当使用诸如mv或rm命令时,可以使用-exec选项的安全模式。它将在对每个匹配到的文件进行操作之前提示你。

在下面的例子中, find命令在当前目录中查找所有文件名以.LOG结尾、更改时间在5日以上的文件,并删除它们,只不过在删除之前先给出提示。

$ find . -name "*.conf" -mtime +5 -ok rm { } \;
< rm ... ./conf/httpd.conf > ? n

按y键删除文件,按n键不删除。

任何形式的命令都可以在-exec选项中使用。

在下面的例子中我们使用grep命令。find命令首先匹配所有文件名为“ passwd*”的文件,例如passwd、passwd.old、passwd.bak,然后执行grep命令看看在这些文件中是否存在一个sam用户。

# find /etc -name "passwd*" -exec grep "sam" { } \;
sam:x:501:501::/usr/sam:/bin/bash

find . -name   "*.svn" -atime -7 -ok rm -rf { } \;
在当前文件夹下查找以.svn的文件(7天以内访问过的)
- ok 表示询问


find /home/log/ -ctime 3-name bbslog\* -exec rm {} \; ##查找前第三天的bbslog文件,并删除
find /tmp/log/ -ctime +4 -name mail\* -exec rm {} \;        ##查找4天前的所有mail日志文件,并全部删除


原文地址:http://www.zhenyusc.cn/

posted @ 2011-02-04 18:21 Chenyunshi 阅读(626) | 评论 (0)编辑 收藏

2010年6月5日

Groovy 教程: 入门

     摘要: 前言 某年某月某日,正式从python转移到groovy.关于python和groovy的比较,网上已经有许多文章了.我的理由是, 作为一个上了年纪的java程序员,groovy的学习曲线要比python低.毕竟,我只是想用groovy写一些小程序.而这些小程序用java做又太耗时间.希望这篇文章能够帮助java程序员尽快进入groovy世界.预备知识,安装学习groovy最好能熟练用jav...  阅读全文

posted @ 2010-06-05 15:03 Chenyunshi 阅读(17257) | 评论 (3)编辑 收藏

2010年5月2日

Ubuntu 10.04 基本安装配置


前言

如果你是单硬盘光盘引导安装, 那就好了, 什么麻烦事都没有, 装完就行. (建议你刻盘安装, 不建议硬盘安装). 你可以忽略下面的文字.

ubuntu 10.04 正式版终于发布了, 我第一时间下载,刻盘, 安装, 却遇到了一点小麻烦. 简言之, 我pc有两块硬盘, 一块装windows一块装ubuntu, ubuntu的引导程序不装在mbr.  这样在安装完10.04之后, 麻烦来了. 即使我在grub4dos的menu.list里正确指定了ubuntu的分区, 启动仍然失败, log的信息说我root的分区不对. 但我明明是设对的啊. 尝试找10.04的grub menu.lst, 找不到. 查了官方的release note, 原来从ubuntu910开始都使用grub2 而不是以前的grub, 所以没有了menu.lst. 那就好办, 肯定有个地方放置启动信息. 继续看文档, 原来是 /boot/grub/grub.cfg 文件. 里面的root信息不对. 修改之, 经grub4dos引导之后, 正确进入ubuntu.

(如果你不明白上面说的信息, 你可以参考这篇文章: 双硬盘安装ubuntu和windows互不影响 )



选择cn99源

以前在804就一直用cn99, 现在依然用. 我是电信的宽带, 用cn99下载均速250k/s, 平时下载一些软件才不到200k. 用cn99真可谓感情深,速度快.

打开administration-->software source, 在download from下拉列表,选择 china, 选择ubuntu.cn99.com.  然后点close, 提示是否reload文件列表, 点之.



安装常用工具


打开accessories--> terminal, 敲入:

sudo apt-get install  python-mutagen mplayer  libxine1-ffmpeg libxine1-all-plugins libxine1-plugins    gstreamer0.10-ffmpeg  gstreamer0.10-plugins-bad gstreamer0.10-plugins-bad-multiverse gstreamer0.10-plugins-ugly gstreamer0.10-plugins-ugly-multiverse gstreamer0.10-esd   libdvdnav4  libdvdcss2 smplayer   recordmydesktop gtk-recordmydesktop filezilla  scrot  nautilus-open-terminal d4x amule  ntfs-config ibus ibus-table ibus-pinyin

这个命令包括了屏幕录像工具(recordmydesktop), ftp程序(filezilla), 截屏工具(scrot), 断点续传下载工具(d4x), emule类工具(amule), 配置ntfs分区工具(ntfs-config),中文输入法(如果你用中文语言安装系统,那么默认已经装上中文输入法) 和一些多媒体库,工具.

接下来做一些配置工作:

配置ntfs共享分区

多数人都是用win和ubuntu双系统。如我 的设置如下: c:安装windows 。 e安装ubuntu,d作为共享盘。放置两个系统共用的文件。例如,我的程序代码就放在d盘。

但 实践中发现,如果d盘采用fat32分区,那么ubuntu创建大写文件夹的时候会出现问题。例如将我某个java应用程序的WEB-INF目录自动更改 为web-inf,害我为这个问题烦恼许久,并且该问题在ubuntu社区暂时没有解决办法。所以建议你的共享分区采用ntfs分区。

sudo  ntfs-config

然后选择你的ntfs分区挂载即可。

有时候你会发现当你选择某个分区之后勾选框处于disable状态,很 简单,在选分区之后,在后面的"mount point" 输入栏随便输个名字即可。例如 mywin ,那么这个分区就会挂载到 /media/mywin 下。

解决Gedit乱码问题

如 果不作设置,gedit修改过的文本文件在windows系统里是乱码,反之亦然.

修改办法如下:

gconf-editor

在 左边的树里,找到apps/gedit-2/preferences/encodings   ,在右侧可以看到两个项,分别是 auto_detected 和 shown_in_menu,双击之,添加GBK 的值并将之遇到最上方,点击ok确认即可.

配置截图软件scrot

用"Add to panel" 添加一个新程序, 并将命令设置为 scrot -s -b

以后每次截图时只需要鼠标点这个程序,并 拖动鼠标截取所需区域即可.

默认截取的图片位于用户的home目录.




安装开发工具

这是给程序员用的, 包括了java,python和qt4

sudo apt-get install build-essential autoconf  subversion sun-java6-jdk sun-java6-source ant idle  qt4-dev-tools qt4-doc qt4-qtconfig qt4-designer ctags 



安装QQ

到这个页面: http://im.qq.com/qq/linux/download.shtml  选择下载deb 包, 然后双击之. qq安装完成.



还有什么?

现在你的ubuntu已经能像windows一样满足日常大部分工作了. 当然, 你或许想上网上银行, 但很遗憾, 国内银行的网银都不支持linux系统. 所以你有两个办法继续使用网银, 一是用手机付款, 二是安装虚拟机用windows上网银. 安装虚拟机这个主题可以见我的这篇帖子:

http://www.cnitblog.com/yunshichen/archive/2008/09/02/48644.html

就这些了. ubuntu10.04 是目前为止我见到的用户体验最好的linux os. 遥想两年前装804, 虽然也号称LTS版本, 但装上后麻烦一直不断: 找不到显卡驱动, 分辨率不对, 中文输入法配置有问题... 两年过去了, ubuntu也成长了很多.衷心祝愿ubuntu能越来越强大.





posted @ 2010-05-02 14:16 Chenyunshi 阅读(2421) | 评论 (4)编辑 收藏

2010年3月26日

官方Hibernate tutorial 修正版


官方版教程的问题

    公司新同事比较多,为了让他们尽快熟悉Hibernate, 我打算做个系列教程. 于是边看官方教程边总结, 这样跟着做下来, 问题来了.

    我看的是这个教程:  http://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/tutorial.html#tutorial-firstapp  边看边发疑问: 有人成功跑过这个教程不? 我估计是没有. 因为该教程的maven配置有问题,而且文中漏了一些方法说明.如果你真的完完全全照着官方教程跑, 是跑不出来的.

    而且, 该教程用maven来打包. 对做了多年J2EE 开发的人来说, Maven和Ivy自然不是什么问题. 但指望刚走出学校的小伙子去了解它们,无疑不切实际. 培训有所谓"台阶式"教育一说, 这个台阶, 定得太高了. 或者Hibernate的作者都长于技术, 而不太关注教程这些东西吧.

    我的这个程序包其实没什么技术含量, 就是把官方教程的文件都做好, 配置好, 写好测试类, 用ant来编译. 指望新手熟悉maven不现实, 但做java的人, ant是必须掌握的.

    下载地址: http://www.uushare.com/user/diegoyun/file/2781837


如何运行

    假设你已经配置好了ant,java

    1> 解压,然后用 ant compile-src 来编译程序
    2> 将工程导入到Eclipse
    3> 在文件夹里有个database目录, cd 到这个目录, 然后双击 start_server.bat . 这样, hsqldb 就启动起来了.
    4> 在Eclipse里打开 EventManager.java, 在main方法里, 改变cmd的值, 即可以测试hibernate的多个方法.

    Good luck.


已解决的问题

    这是我跑官网例子时遇到的错误, 一并记下, 希望可以帮助到你.

    在Configuration().configure().buildSessionFactory() 时遇到:Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.

    导致这个错误的两个原因:
    1>你的xml声明是utf-8字符集, 但实际上你用其他文本编辑器存xml的时候, 不是存成utf-8. 解决办法是把 <?xml version='1.0' encoding='utf-8'?> 改为 <?xml version='1.0'?>
   
    2>你的hibernate.cfg.xml 路径不对. 很显然, hibernate的error信息误导了你. (不知道这算不算hibernate的一个bug)



posted @ 2010-03-26 17:39 Chenyunshi 阅读(625) | 评论 (0)编辑 收藏

2010年3月16日

Python 读写 Excel


基本上, 这个网页已经说明一切了: http://pypi.python.org/pypi/xlrd

等有时间再把这个页面写漂亮,现在先记一些代码.

读Excel

先建个simple.xls

from xlrd import open_workbook

wb 
= open_workbook('simple.xls','rb')
for s in wb.sheets():
    
print 'Sheet:',s.name
    
for row in range(s.nrows):
        values
=[]
        
for col in range(s.ncols):
            values.append(s.cell(row,col).value)
        
print ",".join(values)
    
print

        


写Excel

from tempfile import TemporaryFile
from xlwt import Workbook

book 
= Workbook()
sheet1 
= book.add_sheet('Sheet 1')
book.add_sheet(
'Sheet 2')
sheet1.write(0,0,
'A1')
sheet1.write(0,
1,'B1')

row1 
= sheet1.row(1)
row1.write(0,
'A2')
row1.write(
1,'B2')

sheet1.col(0).width 
= 10000

sheet2 
= book.get_sheet(1)
sheet2.row(0).write(0,
'Sheet 2 A1')
sheet2.row(0).write(
1,'Sheet 2 B1')
sheet2.flush_row_data()

sheet2.write(
1,0,'Sheet 2 A3')
sheet2.col(0).width 
= 5000
sheet2.col(0).hidden 
= True

book.save(
'simple2.xls')
book.save(TemporaryFile())



posted @ 2010-03-16 01:20 Chenyunshi 阅读(8314) | 评论 (2)编辑 收藏

2010年3月7日

python实用技巧 : Filtering os.walk


'''
Created on Mar 7, 2010

@author: Diego

需求: 得到某个目录下, 符合过滤条件的文件夹/文件.
实现: 将os.walk再次包装.

TODO: 不知道本程序的做法, 和传统的逐个目录列举的方法, 哪个效率更高. 待测试.

'''
import  os
import  os.path

os.path.sep
= " / "
path 
=   " /media/dev/project/google_codes/srgjs "
EXCLUDE_DIR_LIST 
=  [ " .SVN " , " CVS " ]
EXCLUDE_FILE_LIST 
=  [ " .CVSIGNORE " ]


def  is_parent_exclude(parentPath,excludeDirList):
    ss
= parentPath.split( " / " );
    
for  s  in  ss:
        
if (s.upper()  in  excludeDirList):
            
return  True
    
    
return  False

def  filter_walk(targetDirectory,excludeDirList,excludeFileExtList):
    dirList
= []
    fileList
= []
    
for  (parent, dirs, files)  in  os.walk(targetDirectory):
        
        
for  d  in  dirs:
            
if (d.upper()  in  excludeDirList):
                
continue
            
            
# To check if one of the parent dir should be excluded.
             if (is_parent_exclude(parent,excludeDirList)):
                
continue
            
            dirList.append(parent
+ " / " + d)
            
        
        
for  f  in  files:
            
if (f.upper()  in  excludeFileExtList):
                
continue
            
# To check if one of the parent dir should be excluded.
             if (is_parent_exclude(parent,excludeDirList)):
                
continue
            
            fileList.append(parent
+ " / " + f)
    
    
return  (dirList,fileList)            

# test
dirs,files  =  filter_walk(path,EXCLUDE_DIR_LIST,EXCLUDE_FILE_LIST)

for  d  in  dirs:
    
print  d

for  f  in  files:
    
print  f



posted @ 2010-03-07 16:42 Chenyunshi 阅读(1083) | 评论 (0)编辑 收藏

仅列出标题  下一页
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

相册

搜索

最新评论

阅读排行榜

评论排行榜