you can check if MySQL data streams are encrypted or not by the following command: # tcpdump -l -i eth0 -w - src or dst port 3306 | strings Wish this helps. regards, Stanley Huang
In Java, we have javadoc to generate the document, in Python, we have pydoc. More info, please click here . The sample of pydoc as the following: The source code of testPyDoc.py #!/usr/bin/python """ This is a sample module to generate pydoc """ __author__ = 'Stanley Huang' __version__= '1.0' class PyDoc: """class docstrings""" def __init__ (self, user='guest', addr='Taipei'): """Set default attribute values only Keyword arguments: user -- name of user addr -- addr of user """ self.user = user self.addr = addr $ pydoc testPydoc Help on module testPyDoc: NAME testPyDoc - This is a sample module to generate pydoc FILE /tmp/testPyDoc.py CLASSES PyDoc class PyDoc | class docstrings | | Methods defined here: | | __init__(self, user='gues...
If you want to modify grub menu of Ubuntu, you have following steps to do: 1. Modify default grub configuration file. # vi /etc/default/grub 2. Update grub configuration. # update-grub Generating grub.cfg ... Found linux image: /boot/vmlinuz-2.6.38-12-generic Found initrd image: /boot/initrd.img-2.6.38-12-generic Found linux image: /boot/vmlinuz-2.6.38-8-generic Found initrd image: /boot/initrd.img-2.6.38-8-generic Found memtest86+ image: /boot/memtest86+.bin Found Windows Recovery Environment (loader) on /dev/sda1 Found Windows 7 (loader) on /dev/sda2 done # More info. please refer to here . Wish this helps. regards, Stanley Huang
If you want to use console to login server on Ubuntu laptop, you could try a useful app named "minicom". And you could download in by apt-get. # apt-get -y install minicom Wish this helps. regards, Stanley Huang
#!/bin/env python import functools try: print int('10') ## equiv: print int('10', base=10) print int('10', 2) ## equiv: print int('10', base=2) int2 = functools.partial(int, 2) ## no default bonding parameter. print int2('10') ## fail, must assign the value of base int2 = functools.partial(int, base=2) ## set default base to 2 print int2('10') ## equiv: print int2('10', base=2) print int2('10', 10) ## fail, TypeError: keyword parameter 'base' was given by position and by name print int2('10', base=10) Wish this helps. regards, Stanley Huang
You can use AllowUsers/AllowGroups/DenyUsers/DenyGroups in sshd_config to limit user login. e.g. # cat /etc/ssh/sshd_config AllowUsers user1 AllowGroups group1 DenyUsers user2 DenyGroups group2 Wish this helps. regards, Stanley Huang
If you want to use parent method in Python, you could use 'super()' method. But it only support new style class, therefore, you need to inherit 'object' class when you create your own class. e.g. #!/bin/env python import os, sys def new_style(): class NewSystemTools(object): def __init__(self): pass def runCmd(self, sCmd): return os.popen(sCmd).read() class MyNewSystemTools(NewSystemTools): def __init__(self): pass def runCmd(self, sCmd): return super(MyNewSystemTools, self).runCmd(sCmd) print '-- new style --' mnst = MyNewSystemTools() print mnst.runCmd('ls /') def old_style(): class SystemTools: def __init__(self): pass def runCmd(self, sCmd): return os.popen(sCmd).read() class MySystemTools(SystemTools): def __init__(self): pass ...
#!/bin/env python import os, sys import marshal a = [1,2,3] fd = open('/tmp/t.log', 'wb') marshal.dump(a, fd) fd.close() fd = open('/tmp/t.log', 'rb') b = marshal.load(fd) for i in b: print i fd.close() Wish this helps. regards, Stanley Huang
If you want to use vim to writing python script. You could download vim autocomplete for python from here And then, you could put pythoncomplete.vim in ~/.vim/autoload/ When you writing python, you could use ctrl+p to autocomplete python syntax. Wish this helps. regards, Stanley Huang
My current vim settings are below. You could get more sample in here . set nu set ic :au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif set nosmartindent set tabstop=4 set shiftwidth=4 set expandtab set hlsearch syntax on " filetype indent plugin on set background=dark set modeline " filetype indent on " au FileType python setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4 " au FileType python setlocal ts=8 et sw=4 sts=4 set nobackup set noswapfile set showmode set ruler map j gj map k gk :w !python % autocmd FileType java map :!javac "%:p" && java -cp "%:p:h" "%:t:r" autocmd FileType c map :!gcc --o "%:p:r.out "%:p" && "%:p:r.out" autocmd FileType php noremap :w! :!/usr/bin/php % autocmd BufRead *.py nmap :w !sh % Wish this helps. regards, Stanley H...
If there are some wording not for ascii, you should add # -*- coding: (encoding) -*- to prevent compile error. example error message: File "./testEncoding.py", line 21 SyntaxError: Non-ASCII character '\xe6' in file ./testForLoop_2.6.py on line 21, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details e.g. #!/usr/bin/python2.6 # -*- coding: utf8 -*- ### chinese testing slang="有嘴說別人無嘴說自己" sword="嘴" ## error with encoding #for i in slang: # print i # use python shell to display encoding # ex. # >>> "有嘴說別人無嘴說自己" # '\xe6\x9c\x89\xe5\x98\xb4\xe8\xaa\xaa\xe5\x88\xa5\xe4\xba\xba\xef\xbc\x8c\xe7\x84\xa1\xe5\x98\xb4\xe8\xaa\xaa\xe8\x87\xaa\xe5\xb7\xb1\xe3\x80\x82' # >>> "嘴" # '\xe5\x98\xb4' l=len(sword) h=0 k=0 count=0 for item in slang: k=0 f=1 while k<l: if slang[h+k]==sword[k]: k+=1 continue else: f=0 break if f==1: ...
There is a good website to demo decorator sample codes. here ''' Usage: @deprecated def func(): ... ''' class deprecated: def __init__(self, func): self.func = func self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ self.__dict__.update(self.func.__dict__) pass """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def __call__(self, *args, **kwargs): msg = "Call to deprecated function %s()." % self.func.__name__ ## Suppressing Warnings warnings.simplefilter("ignore") warnings.warn(msg, category=DeprecationWarning) ## Delete ignore filter del warnings.filters[0] (tmpDebug2Console, libcommon.bDebug2Console) = (libcommon.bDebug2Console, False) libcommon.debug(msg, logfile='de...
If you want to compile python script manually, you could use following command. $ python -c "import compileall; compileall.compile_dir('./', force=1)" Wish this helps. regards, Stanley Huang
#!/bin/env python aWeek = ['Sun', 'Mon','Tue','Wed', 'Thu', 'Fri', 'Sat'] ## without enumerate() print 'without enumerate()...' index = 0 for day in aWeek: print index, day index += 1 ## without enumerate() print 'without enumerate()...' for index in range(len(aWeek)): print index, aWeek[index] ## with enumerate() print 'with enumerate()...' for (index, day) in enumerate(aWeek): print index, day without enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat without enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat with enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat Use enumerate() would make code easier to read. Wish this helps. regards, Stanley Huang
If you want to join lines in shell script, you could use sed command. #!/bin/bash cat > /tmp/t.txt <<EOF eth0 eth1 eth2 eth3 eth4 eth5 eth6 lo0 EOF sed -e :a -e '$!N; s/\n/,/; ta' /tmp/t.txt $ ./joinLinesBySed.sh eth0,eth1,eth2,eth3,eth4,eth5,eth6,lo0 Wish this helps. regards, Stanley Huang
Months ago, I wrote a simple decorator, without decorator parameters, implement in Python. [Level 2] How to implement decorator in Python (I). Now, I'll show you how to implement decorator with parameter. The sample of Python decorator (1, by class): #!/bin/env python class Decorator: def __init__(self, man, woman): self.man = man self.woman = woman pass def __call__(self, f): def wrapped_f(*args, **kargs): print 'hello %s' % self.man f(*args, **kargs) print 'world %s' % self.woman return wrapped_f @Decorator('stanley', 'christy') def test(who): print 'test(%s)' % who test('joseph') $ ./test.py hello stanley test(joseph) world christy The sample of Python decorator (2, by wrap function): #!/bin/env python def Decorator(man, woman): def wrap(f): def wrapped_f(*args, **kargs): print 'hello %s' % man ...
Sample code and test result are as the following: #!/bin/env python class e(Exception): def __init__(self): pass server_list = [1,2,3,4,5] for server in server_list: try: sReturn = server print 's:%s' % sReturn if sReturn $ ./t.py s:1 finally:1 s:2 finally:2 s:3 except1:3 finally:3 s:4 try:4 else:4 finally:4 Wish this helps. regards, Stanley Huang
$ autoexpect -f ./auto.exp autoexpect started, file is ./auto.exp $ ssh stanley@localhost The authenticity of host 'localhost (127.0.0.1)' can't be established. RSA key fingerprint is 36:12:a4:49:26:fe:18:0d:77:bf:c7:e8:36:86:b7:f2. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'localhost' (RSA) to the list of known hosts. stanley@localhost's password: Welcome to Ubuntu 11.04 (GNU/Linux 2.6.38-10-generic x86_64) * Documentation: https://help.ubuntu.com/ *** /dev/sda5 will be checked for errors at next reboot *** Last login: Thu Jul 28 12:17:50 2011 from stanley-ubuntu $ ls apache-cassandra-0.8.1-SNAPSHOT.jar Public auto.exp Rock Desktop script.exp Documents scripts Downloads scripts_20110302.tgz eclipse Self_assesment_201103.pdf English_Survey.pdf SUR-1-Vesu_Pi...
When you try to use command udevinfo in Ubuntu 11.04, you would get the response "udevinfo: command not found". How to simulate the command udevinfo? Use command udevinfo with info option. Ex. # udevadm info -q all -n /dev/video0 You could also create a function named udevinfo as you like Ex. # udevinfo () { udevadm info -a -p `udevadm info -q path -n "$1"`; }
# udevinfo /dev/video0
...
Wish this helps. regards, Stanley Huang
If you want to ignore strict host key checking, even skip saving the host key info, you could use option UserKnownHostsFile, StrictHostKeyChecking. Ex. ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no stanley@192.168.1.1 or modify /etc/ssh/ssh_config for global settings. # cat /etc/ssh/ssh_config ... UserKnownHostsFile /dev/null StrictHostKeyChecking no ... Wish this helps. regards, Stanley Huang
Days ago, I discussed the coding style of python, and I use one example to present what I want you to know. The most 2 ways to use of renaming a file are: 1. Use rename method os moudle [ os.rename(f1, f2) ], 2. Use external command by popen method[ os.popen('mv f1 f2') ]. Some people might think there are not much different between these two ways. But after a stress test, you will realize it did has different between these two ways. The sample code and test run are as the following. #!/bin/env python import os, sys from time import gmtime, strftime n = 10000 f1 = '/1' f2 = '/2' os.popen('touch %s' % f1).read() print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) for i in range(n): if os.path.exists(f1): os.rename(f1, f2) else: os.rename(f2, f1) print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) for i in range(n): if os.path.exists(f1): os.popen('mv %s %s' % (f1, f2))...
If you want to allow using symbolic link in tomcat, you could add and attribute called "context" with an key "allowLinking" eg. <Context path="/myapp" allowLinking="true"/> and I wrote a sample python code to do this. #!/bin/env python import os,sys from xml.dom import minidom def getXMLDom(FILE): return minidom.parse(open(FILE,'r')) def saveXML(FILE, dom): fd = open(FILE, 'w') fd.write(dom.toxml()) fd.close() def appendElement(FILE, base_element_name, element_name, attr_key_val, element_index=0, backup_flag='y'): if backup_flag == 'y': backupConfigFile(FILE) dom = getXMLDom(FILE) e = dom.createElement(element_name) for attr, val in attr_key_val: e.setAttribute(attr, val) dom.getElementsByTagName(base_element_name)[element_index].appendChild(e) saveXML(FILE, dom) xmlFile = prefix+'/opt/ruckuswireless/3rdparty/tomcat/conf/server.xml' base_element_...
You have two way to install jython on Ubuntu: 1. Use apt-get: # sudo apt-get -y install jython # jython --version 2. Download source: # cd /tmp # wget http://sourceforge.net/projects/jython/files/jython/2.5.2/jython_installer-2.5.2.jar/download # mv ./download ./jython.jar # java -jar ./jython.jar ... following the wizard. # export PATH=$PATH:/opt/jython/bin # (if you installed Jython in /opt/jython) # jython --version Wish this helps. regards, Stanley Huang
You have two way to install it. 1. Use apt-get: # sudo apt-get -y install scala 2. Download source: (browse http://www.scala-lang.org/downloads first) # cd /opt # wget http://www.scala-lang.org/downloads/distrib/files/scala-2.9.0.1.tgz # tar -C /opt zxf ./scala-2.9.0.1.tgz # export PATH=$PATH:/opt/scala-2.9.0.1/bin # scala -version Wish this helps. regards, Stanley Huang
Once you upgrade Ubuntu from 10.04 to 11.04, and you will find out the network-manager won't manage wireless any more. But you still could change NetworkManager.conf to enable it. # sudo vi /etc/NetworkManager/NetworkManager.conf and change "managed" attribute from "false" to “true“ and restart it. # sudo /etc/init.d/network-manager restart Wish this helps. regards, Stanley Huang
If you want to sync time with time server in Ubuntu, you could use command ntpdate + time_server. And don't forget write date into bios too. ntpdate time.stdtime.gov.tw && hwclock -w Wish this helps. regards, Stanley Huang
If you want to modify mp3 in Ubuntu, you could use "audacity". And you could download it from reposity. The commands as the following. # apt-cache search audacity create-resources - shared resources for use by creative applications audacity - fast, cross-platform audio editor audacity-data - fast, cross-platform audio editor (data) audacity-dbg - fast, cross-platform audio editor (debug) vamp-plugin-sdk - audio analysis and feature extraction plugins (SDK) # apt-get -y install audacity After for a while, I heard a good tool to convert mp4 to mp3 call avidemux # apt-cache search avidemux libavidemux0 - a free video editor - shared libraries avidemux - a free video editor - GTK version avidemux-cli - a free video editor - command line version avidemux-common - a free video editor - Internationalization files avidemux-plugins-cli - a free video editor - CLI plugins avidemux-plugins-common - a free video editor - common files for plugins avidemux-plugins-gtk - a free video ...
How to check the resource limitation of specific process in Ubuntu. You can follow the below steps: # ps -ef | grep nfsd4 root 1098 2 0 May13 ? 00:00:00 [nfsd4] root 18674 18607 0 20:32 pts/15 00:00:00 grep --color=auto nfsd4 # cat /proc/1098/limits Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 10485760 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 47490 47490 processes Max open files 1024 1024 files Max locked m...
If you want to create multi Cassandra instances and only use one copy of binary. You need to setup CASSANDRA_HOME environment variable. If you only use symbolic link to link binary file, Cassandra will search the real binary directory and set its parent directory as the home, if you don't setup the CASSANDRA_HOME environment variable. # export CASSANDRA_HOME=[new directory you want] # cd [new directory you want] # ./bin/cassandra Wish this helps. regards, Stanley Huang
A good artical for convert keys between openssh and openssl. http://sysmic.org/dotclear/index.php?post/2010/03/24/Convert-keys-betweens-GnuPG,-OpenSsh-and-OpenSSL Wish this helps. regards, Stanley Huang
If you want to create multi instances of tomcat, you can follow the below steps: 1. Copy logs, conf and webapps from origianl tomcat foler to a new location. # mkdir -p [a new folder you like] # cd [original tomcat folder] # cp ./logs ./conf ./webapps [a new folder you like] 2. Set environment variables "CATALINA_BASE" to the above path. # export CATALINA_BASE=[a new folder you like] 3. Startup tomcat. # [original tomcat folder]/bin/startup.sh And what's the difference between CATALINA_BASE and CATALINA_HOME, the decision path is as below: 1. Decide CATALINA_BASE: If you have CATALINA_BASE, the base directory is CATALINA_BASE, if not, the real path of binary would be the CATALINA_BASE. 2. Decide CATALINA_HOME: If you have CATALINA_HOME, the webapps base directory is in CATALINA_HOME, if not, the CATALINA_BASE would be the CATALINA_HOME. Wish this helps. regards, Stanley Huang
If you want to display current line number for debug info. You can import inspect to do that. #!/bin/env python import inspect from inspect import currentframe, getframeinfo def getFilenameLineno(): frameinfo = getframeinfo(currentframe().f_back) return (frameinfo.filename, frameinfo.lineno) def lineno(): return inspect.currentframe().f_back.f_lineno def curr_filename_lineno(): return inspect.currentframe().f_back.f_code if __name__ == '__main__': print lineno() # skip line with comment print curr_filename_lineno() print '%s(#%s)' % getFilenameLineno() print lineno() $ ./testLineno.py 16 <code object <module> at 0xb7509f50, file "/tmp/t.py", line 2> /tmp/testLineno.py(#20) 22 Another way is to parse inspect.stack() e.g. #!/bin/env python import inspect def t(): tt() def tt(): ttt() def ttt(): tttt() def tttt(): print inspect.stack() if __name__ == '__main__': t() ...
yield in python just pass the control to the parent. if a() call b(), in b and execute yield, the control would back to a() util a call generator.next() e.g. #!/bin/env python def foo(): print 'start foo()' ## only pass here when first time call .next() n = 3 for i in range(1,n+1): print 'in for()' print 'yield %s' % i yield i ## return i when call .next() print 'back to for()' ## start from here when call .next() again if __name__ == '__main__': print 'start main' print 'init main vars' f = foo() i = 0 n = 10 print 'f: %s' % f print 'i: %s' % i print 'n: %s' % n for x in range(0,n): print 'f.next()' i = f.next() print 'print i' print i print 'in main' print 'call again f.next()' print f.next() print 'ex...
If you got an error message like "SyntaxError: Non-ASCII character '\xe4' in file" That means you have non-ascii character in your script. And if you want to support utf-8, you could add the comment in your script. e.g. #!/bin/env python # -*- coding: utf8 -*- Wish this helps. regards, Stanley Huang
In previous, I wrote a paper for python variable scope . This time, I try to use python native decorator to implement the same idea. #!/usr/bin/env python class C(object): def __init__(self): self._name = None self.__age = None @property def name(self): """I'm the 'name' propertage.""" return self._name @name.setter def name(self, value): self._name = value @name.deleter def name(self): del self._name @property def age(self): pass @age.getter def age(self): return self.__age @age.setter def age(self, value): self.__age = value if __name__ == '__main__': c = C() c.name = 1 print c.name print c._name del c.name try: print c.name except AttributeError, e: #print "'C' object has no attribute '_name'" print e c.age = 2 ...
install gui tool for ufw # apt-get -y install gufw # gufw use command(ufw) to setting firewall, and the config file in in /lib/ufw/user.rules # ufw deny from any to any port 22 # ls -al /lib/ufw/user.rules -rw-r----- 1 root root 1405 2011-04-01 17:36 /lib/ufw/user.rules # ufw delete deny from any to any port 22 # ls -al /lib/ufw/user.rules -rw-r----- 1 root root 1263 2011-04-01 17:36 /lib/ufw/user.rules my setting history (reference only): ufw disable ufw default deny ufw logging ON ufw enable ufw allow 22/tcp ufw allow proto tcp from 192.168.1.0/24 to 192.168.1.101 port 80 use iptables command: #!/bin/bash MY_IP=192.168.100.101 # Flushing all rules and chains iptables -F iptables -X # Setting default policy iptables -P INPUT DROP iptables -P OUTPUT ACCEPT iptables -P FORWARD DROP # Allow traffic on loopback iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Allow ssh for in/out iptables -A INPUT -p tcp -s 0/0 -d $MY_IP --sport 513:65535 --dport 22 -m state...
I wrote a python script to get broadcast by giving ip and netmask. And I use "lambda" and "map" function to shorten my code, so it's also a good sample for you to study map function. More information please refer here . The sample code is as the following: #!/bin/env python def getBroadcast(self, ip=None, netmask=None): if not ip or not netmask: return None ip = ip.split('.') netmask = netmask.split('.') for n in range(0,4): if netmask[n] == '0': break bc = (map(lambda a, b: str(int(a, 10)&int(b,10)), ip[0:n]+['255']*(4-n), netmask[0:n]+['255']*(4-n))) if n > 1: bc[n-1] = str(int(bc[n-1]) + (255 - int(netmask[n-1]))) return '.'.join(bc) print getBroadcast('192.168.10.1','255.255.254.0') Result: 192.168.11.255 Wish this helps. regards, Stanley Huang
#!/bin/env python def getEtherList(): return [x.strip() for x in \ os.popen("ifconfig -a | \ grep Link | grep '^[^ ]' | \ grep -v lo | awk '{print($1)}'")\ .readlines()] print getEtherList() Wish this helps. regards, Stanley Huang
If you want to implement iif in Python, please refer to the following sample code: #!/bin/env python def iif(b): return 'It\'s True' if b else 'It\'s False' print iif(True) print iif(False) And the following sample, guess what will you get! #!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % 'Ture' if b else 'False' Result: $ ./iif.py b: Ture False The second result is "False", not "b: False". Why??? Because the prededence of string concatenation is higher than if. Therefore you need to use () to make it correct. #!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % ('Ture' if b else 'False') Wish this helps. regards, Stanley Huang
Sometimes, you want to transfer between netmask and prefix setting. You can use the following sample script which is written by Python. #!/bin/env python def transferPrefix2Netmask(self, prefix): netmask = '' nLeadingFF = prefix / 8 netmask += '.'.join(['255']*nLeadingFF) if nLeadingFF != 4: netmask += '.' + str(256-2**(8-prefix%8)) nSuffix00 = 3 - nLeadingFF if nLeadingFF < 3: netmask += '.' + '.'.join(['00']*nSuffix00) return netmask def transferNetmask2Prefix(self, netmask): prefix = 0 left = 0 for i in netmask.split('.'): if i == '255': prefix += 8 else: left = int(i) break if left != 0: for n in range(7, 0, -1): prefix += 1 if left - 2 ** n == 0: break ...
If you want to reset the seq. no of interface. You can remove the record in /etc/udev/rules.d/70-persistent-net.rules. Wish this helps. regards, Stanley Huang
If your company give you the key and cert for openvpn, but somehow you want to change the passphrase that you easy to remember. You can use openssl to modify the passphrase. The sample as below: Step 1, Remove the password: # openssl rsa -in client.key -out client2.key (It will prompt you for the current password, and write the decrypted key to client2.key) Step 2, Add or change the password: # openssl rsa -in client.key -out client2.key -des3 (It will prompt you for the current password (if any), then for the new password, and then write the encrypted key to client2.key) Wish this helps. regards, Stanley Huang
When you develop a terminal program, you always need a function to "Press any key to continue", but how to implement it in Python script. I found out a sample on here: http://code.activestate.com/recipes/134892/ Wish this helps. regards, Stanley Huang
The Python Code: #!/bin/env python def f1(): exec 'a=1' def f2(): exec 'global a; a=2' def f3(): print a global a a=0 f1() f3() f2() f3() The output is: # /tmp/t.py 0 2 As you can see, The f1() function cannot modify global variable "a" successfully, we can say that, exec is a fact function, and unless you declare a variable as a global variable, or you just deal with a local variable. Like f1() So if you want to deal with global variable, please remember to declare it as the global variable first. Like f2() Wish this helps. regards, Stanley Huang
If you want to reserve ip (query only) from dhcp server by dhclient in Ubuntu, you can use the following command to do so. # dhclient -q -sf /dev/null -lf /tmp/dhclient.lease -pf /tmp/dhclient.pid Then you can see the lease file (/tmp/dhclient.lease) to get more information. PS. In my test, dhclient 3.1 ( in Ubuntu 10.04 ) will have an error with no permission. Therefore, I download the latest version of dhclient (4.1) from isc . you can get more information from here . Wish this helps. regards, Stanley Huang
You can use pdb module to debug your python program in run-time environment in two ways. 1. import pdb module and set trace. e.g. #!/bin/env python import os, sys ... import pdb; pdb.set_trace() ... 2. use python command and import pdb module. $ python -m pdb ./myapp.py And about pdb useful commands: l: list source code b: break point r: run s: step: into function n: next: run next line c: : continue next loop where: where is the break point now ? help Ex. $ python -m pdb ./myapp.py (Pdb) l 1 #!/bin/env python 2 -> import os, sys 3 #print os.environ['PATH'] 4 os.environ['PATH']='/usr/bin:'+os.environ['PATH'] 5 #if './' not in sys.path: sys.path.append('./') 6 #if './lib' not in sys.path: sys.path.append('./lib') 7 #if '../lib' not in sys.path: sys.path.append('../lib') 8 exec_file = sys.argv[0] 9 os.chdir(os.path.dirname(sys.argv[0])) 10 ru...
There is a article to introduce Open HA Cluster with OpenSolaris in VirtualBox. Please refer to Open HA Cluster On OpenSolaris . Wish this helps. regards, Stanley Huang
I saw a good artical about ZFS tuning , the link as following: http://www.solarisinternals.com/wiki/index.php/ZFS_Evil_Tuning_Guide Wish this helps. regards, Stanley Huang
If you want to let your CentOS 5.3 support ntfs, you should install ntfs-3g package # yum install fuse fuse-ntfs-3g # modprobe fuse Wish this helps. regards, Stanley Huang
Install LVM (Logical Volume Management) in Ubuntu. 1. Install LVM with apt-get # apt-get -y install lvm2 [Ref: http://www.debuntu.org/how-to-install-ubuntu-over-lvm-filesystem ] $ sudo mke2fs -j /dev/sda2 $ sudo pvcreate /dev/sda3 #create a physical volume on /dev/sda3 Physical volume "/dev/sda3" successfully created $ sudo vgcreate lvmvolume /dev/sda3 #create a volume group named lvmvolume using /dev/sda3 physical volume Volume group "lvmvolume" successfully created $ sudo lvcreate -n root -L 5G lvmvolume #create a logical volume of 5G named "root" in lvmvolume Logical volume "root" created $ sudo lvcreate -n home -L 10G lvmvolume #create a logical volume of 10G named "home" in lvmvolume Logical volume "home" created $ sudo lvcreate -n swap -L 2G lvmvolume #create a logical volume of 2G named "swap" in lvmvolume Logical volume "swap" created $ sudo mkfs -j /dev/lvmvolume/root -L r...
One networking library for python called 'Scapy', is worth for you to try. http://www.secdev.org/projects/scapy/index.html Wish this helps. regards, Stanley Huang
If you want your vim support python syntax, you can do the following steps: 1. make directory. $ mkdir ~/.vim/syntax 2. Download python syntax profile from vim org. http://www.vim.org/scripts/script.php?script_id=790 3. enable syntax. $ cat ~/.vimrc syntax on Wish this helps. regards, Stanley Huang
If you want to search in vim, you can use the command '#' to select the word first. And if you want to hightlight it, you can set highlight search in ~/.vim.rc in ~/.vimrc set hlsearch Wish this helps. regards, Stanley Huang
Please refer to the following links: http://google-code-prettify.googlecode.com/svn/trunk/README.html http://stackoverflow.com/questions/1852537/how-to-use-prettify-with-blogger-blogspot example display for python code: #!/bin/env python class MyClass: def __init__(self): self.name = 'stanley' self.age = 25 def getName(self): return self.name def getAge(self): return self.age if __name__ == '__main__': man = MyClass() print man.getName() print man.getAge() Wish this helps. regards, Stanley Huang
If you want to implement singleton in Python, you can refer the following sample code. #!/usr/bin/env python c lass SingleFactory: __single = None def __init__( self ): if not SingleFactory.__single: SingleFactory.__single = self def getInstance( self ): return SingleFactory.__single if __name__ == '__main__': f = SingleFactory() a = f.getInstance() b = f.getInstance() print a print b a.count = 1 print a.count print b.count Execute it. $ ./t.py <__main__.SingleFactory instance at 0x1004d1290> <__main__.SingleFactory instance at 0x1004d1290> 1 1 Wish this helps. regards, Stanley Huang
The sample of Python decorator (1, by class): #!/usr/bin/env python class my_de: def __init__(self, f): self.f = f def __call__(self, *args, **kargs): print 'Before you call the method (%s)' % self.f.__name__ self.f(*args, **kargs) print 'After you call the method (%s)' % self.f.__name__ @my_de def helloworld(who, are, you): print 'hello world! %s %s %s' % (who, are, you) if __name__ == '__main__': helloworld('I', 'am', 'Stanley') Execute it. $ ./t.py Before you call the method (helloworld) hello world! I am stanley After you call the method (helloworld) The sample of Python decorator (2, by wrap function): #!/usr/bin/env python def my_de(f): def new_f(*args, **kargs): print 'Before you call the method (%s)' % f.__name__ f(*args, **kargs) print 'After you call the method (%s)' % f.__name__ ...
How to create a Django project and apps by command mode, please follow the below commands: # django-admin.py startproject myProject # cd ./myProject # django-admin.py startapp myApp1 # cd ./myApp1 # python manage.py runserver [0.0.0.0:]8888 Wish this helps. regards, Stanley Huang
You can use @staticmethod (decorator) to implement static method in Python class. #!/usr/bin/env python class de: def __init__(self): self.a = 1 def getA(self): return self.a @staticmethod def getB(): return 2 @classmethod def getCN(): return cls.__name__ if __name__ == '__main__': d = de() print 'd.getA() = %s' % d.getA() print 'de.getB() = %s' % de.getB() print 'classname of de = %s' % de.getCN() print 'de.getA() = %s' % de.getA() Execute it. $ ./t.py de.getA() = 1 de.getB() = 2 classname of de = de Traceback (most recent call last): File "./t.py", line 15, in print 'de.getA() = %s' % de.getA() TypeError: unbound method getA() must be called with de instance as first argument (got nothing instead) Wish this helps. regards, Stanley Huang
How to setup your wireless interface to auto connect to ap in Ubuntu? You can set the config in /etc/network/interface like below: wlan0 auto iface wlan0 inet dhcp wireless-essid your_essid wireless-key your_essid_passphrase wireless-channel your_essid_channel Wish this helps. regards, Stanley Huang
If you want to detect port, you can use socket module to do it. #!/bin/env python import os, sys import socket def detectPort(PORT): # Echo server program import socket HOST = '' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((HOST, PORT)) return_code=1 except: return_code=0 s.close() return return_code if __name__ == '__main__': for PORT in [80,81,82,8000,8080,3306,3307]: if detectPort(PORT): print PORT Wish this helps. regards, Stanley Huang