Posts

Showing posts from 2012

[Level 2] Python abstract method testing

#!/bin/env python import os, sys from abc import * # ================================================= class ToolCmd(object): __metaclass__ = ABCMeta def __init__(self): pass @abstractmethod def doLocalAction(self): pass class DoAction(ToolCmd): def __init__(self): pass def doLocalAction(self): print 'doLocalAction()' # ================================================= class Test1(DoAction, ToolCmd): def __init__(self): pass class Test2(ToolCmd): def __init__(self): pass #class Test3(ToolCmd, DoAction): # def __init__(self): # pass # ================================================= t1 = Test1() t1.doLocalAction() t2 = Test2() t2.doLocalAction() #t3 = Test3() #t3.doLocalAction() # ================================================= Test Run: (Run-time error) $ ./c.py doLocalAction() Traceback (most recent call last): File "./c.py", line 42, in t2 =

[Level 2] Scan wifi channel in Ubuntu.

#!/bin/bash iwlist wlan0 scanning | grep Channel: | grep -v grep | cut -d: -f2 | sort Wish this helps. regards, Stanley Huang

[Level 1] How to mount exFAT filesystem in Ubuntu 10.04

You could install fuse-exfat to mount exFAT file system. e.g. $ sudo add-apt-repository ppa:relan/exfat $ sudo apt-get update $ sudo apt-get -y install fuse fuse-exfat exfat-utils Wish this helps. regards, Stanley Huang

[Level 1] Install Everpad (Evernote) on Ubuntu.

If you want to use evernote on Ubuntu, you could try everpad. $ sudo add-apt-repository ppa:nvbn-rm/ppa $ sudo apt-get update && sudo apt-get install everpad Wish this helps. regards, Stanley Huang

[ Level One ] Watch mp4 video on Google Chrome on Ubuntu 12.04

When you install Google Chrome on Ubuntu 12.04, you might not watch mp4 video by Chrome, that's because you didn't install mpeg codec. (Ex. The online courses of Coursera) You could install ffmpeg-extra for chromium by apt-get command like below: $ sudo apt-get -y install chromium-codecs-ffmpeg-extra $ Wish this helps. regards, Stanley Huang

[ Level 2 ] Share terminal in Ubuntu

How to share terminal in Ubuntu terminal 1: $ id uid=1000(stanley) ... $ sudo chmod u+s /usr/bin/screen $ sudo chmod 755 /var/run/screen $ screen -S screen-share $ [ctrl + a] :multiuser on $ [ctrl + a] :acladd joseph terminal 2: $ ssh joseph@localhost $ screen -x stanley/screen-share Ref: http://blog.bodhizazen.net/linux/shared-ssh-sessions-update-for-jaunty-ubuntu-904/ http://www.pixelbeat.org/docs/screen/ #!/bin/bash -vx showUsage() { cat <<EOF Usage: $0 [session name] [multi user] Ex. $0 session guest HowTO connect from guest: \$ ssh guest@remote_host \$ guest> screen -x [session holder]/[session name] \$ guest> screen -x stanley/screen-share EOF } main () { if [ $# -lt 2 ] then showUsage exit 1 else pgName="`basename $0 | cut -d. -f1`" session="$1" user="$2" cfFile="/tmp/$pgName.cnf" cat /dev/null > $cfFile echo "multiuser on" >> $cfFile echo &

[ Level 3 ] Python config factory with __subclasses__.

It's a sample code for use __subclasses__ to validate the type. I write a config factory utility #!/bin/env python import os, sys if './' not in sys.path: sys.path.append('./') if './lib' not in sys.path: sys.path.append('./lib') if '../lib' not in sys.path: sys.path.append('../lib') if os.getcwd()+'/lib' not in sys.path: sys.path.append(os.getcwd()+'/lib') import yaml, json from libproperty import * from StringIO import StringIO from abc import * ## Property Abstract Class ## Subclass naming rule: xxxProperty. (e.g. JavaProperty, YamlProperty) class CommonProperty(object): __metaclass__ = ABCMeta def __init__(self, FILE=None): self._prop_file_output = self._prop_file = FILE self._prop = None pass @staticmethod def isValidType(type): return '%sProperty' % type in [ c.__name__ for c in CommonProperty.__subclasses__() ] @abstractmethod def save(self, FI

[ Level 2 ] Color for man page.

I forget where to get this information, just try it. export PAGER="`which less` -s" export BROWSER="$PAGER" export LESS_TERMCAP_mb=$'\E[38;5;167m' export LESS_TERMCAP_md=$'\E[38;5;39m' export LESS_TERMCAP_me=$'\E[38;5;231m' export LESS_TERMCAP_se=$'\E[38;5;231m' export LESS_TERMCAP_so=$'\E[38;5;167m' export LESS_TERMCAP_ue=$'\E[38;5;231m' export LESS_TERMCAP_us=$'\E[38;5;167m' Wish this helps. regards, Stanley Huang

[ Level 3 ] Bash auto completion

Bash auto complete Wish this helps. regards, Stanley Huang

[ Level 1] The most popular benchmark tools for MySQL

The most popular benchmark tools are: In MySQL official release: sql-bench mysqlslap Developed by community: DBT-2 SysBench Wish this helps. regards, Stanley Huang

[ Level 1 ] Utilities for MySQL.

Some body asked me any good utilities for MySQL, therefore, I listed several good utilities here and you could try to google it for detail information. Included: dim_STAT Maatkit mysqlreport mysqlresources mytop Wish this helps. regards, Stanley Huang

[ Level 2 ] Install Redmine on Ubuntu.

If you want to install Redmine on Ubuntu, please follow the following steps. Ref: Redmine Wiki The steps are as the following: 1. Download Redmine by subversion. 1-a. Install subversion by apt-get: # apt-get -y install subversion 1-b. Download Redmine by subversion: # svn co http://redmine.rubyforge.org/svn/branches/2.0-stable redmine-2.0 2. Install gem by apt-get. # apt-get -y install rubygems 3. Install Redmine by bundler. 3-a. Pre-install MySQL5.5, bundler and rmagick # apt-get -y install mysql-server-5.5 # gem install bundler # gem install rmagick 3-b. Setup Redmine by bundler # cd ./redmine-2.0 # bundle install --without development test mysql postgresql sqlite rmagick 4. Create database on MySQL. # mysql mysql> create database redmine character set utf8; mysql> create user 'redmine'@'localhost' identified by 'my_password'; mysql> grant all privileges on redmine.* to 'redmine'@'localhost

[Level 2] How to get root permission to write file.

If you want to get root permission when you launch vim with normal user. You could try the following command in vim. 1. to write to file. 2. reload the file. :w !sudo tee [file_name] :e! Wish this helps. regards, Stanley Huang

[Level 2] How to know python module come from.

python> print sys.modules {'copy_reg': <module 'copy_reg' from '/usr/lib/python2.6/copy_reg.pyc'>, 'encodings': <module 'encodings' from '/usr/lib/python2.6/encodings/__init__.pyc'>, 'site': <module 'site' from '/usr/lib/python2.6/site.pyc'>, '__builtin__': <module '__builtin__' (built-in)>, '__main__': <module '__main__' (built-in)>, 'encodings.encodings': None, 'abc': <module 'abc' from '/usr/lib/python2.6/abc.pyc'>, 'posixpath': <module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>, 'errno': <module 'errno' (built-in)>, 'encodings.codecs': None, '_abcoll': <module '_abcoll' from '/usr/lib/python2.6/_abcoll.pyc'>, 'types': <module 'types' from '/usr/lib/python2.6/types.pyc'>, '_code

[Level 1] get ssh finger print

$ ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub 2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /etc/ssh/ssh_host_rsa_key.pub Wish this helps. regards, Stanley Huang

[Level 1] autocomplete in shell script

#!/bin/bash read -e -p 'input file name ( for auto complete): ' input_file echo $input_file $ ./autocomplete.sh input file name ( for auto complete): /etc/ho<tab> input file name ( for auto complete): /etc/host<enter> /etc/host $ Wish this helps. regards, Stanley Huang

[Level 2] How to fork in Python.

#!/usr/bin/env python import os import time def my_fork(): child_pid = os.fork() if child_pid == 0: print "Child Process: PID# %s" % os.getpid() time.sleep(10) else: print "Parent Process: PID# %s" % os.getpid() time.sleep(1) if __name__ == "__main__": my_fork() $ python /testFork.py Parent Process: PID# 2292 Child Process: PID# 2293 $ Wish this helps. regards, Stanley Huang

[Level 2] Python unit test samples.

#!/usr/bin/env python import os,sys import unittest class C(object): def __init__(self): self.name = 'stanley' self.age = 24 class TS(unittest.TestCase): ## set up def setUp(self): self.c = C() pass ## clean up def tearDown(self): pass def test_getName(self): print self.c.name def test_getAge(self): print self.c.age def test_getNameAge(self): c = C() print c.name print c.age def runTest(self): print self.test_getName() print self.test_getAge() #def myTestModule(): # tests = ['test_getName', 'test_getAge'] # suite = unittest.TestSuite(map(TS, tests)) # unittest.TextTestRunner(verbosity=2).run(suite) class TS1(unittest.TestCase): def setUp(self): self.c = C() pass def tearDown(self): pass def test_name1(self): print self.c.name def test_age1(self):

[Level 2] Replace doc by variable name in Python.

#!/bin/env python doc = ''' a: %(a)s b: %(b)s c: %(c)s d: %(d)s ''' dict = { 'a': 'a1', 'b': 'b1', 'c': 'c1', 'd': 'd1', } print doc % dict $ /tmp/t.py a: a1 b: b1 c: c1 d: d1 $ Wish this helps. regards, Stanley Huang

[Level 2] Use taglist for python in vi.

You could add taglist in vi for python developing. The setup process as the following: 1. install ctags http://ctags.sourceforge.net/ 2. install taglist http://www.vim.org/scripts/script.php?script_id=273 After install both component, re-run vim and use command :TlistToggle to show taglist. Wish this helps. regards, Stanley Huang

[Level 1] Nice python shell bpython.

If you though default python shell is not good for use, you replace python with bpython. You could get it with apt-get # apt-get -y install bpython Wish this helps. regards, Stanley Huang

[Level 2] How to enable VNC server in Ubuntu 10.04

How to enable VNC server in Ubuntu 10.04, please refer here . Wish this helps. regards, Stanley Huang

[Level 1] How to get ram spec in Ubuntu

If you want to get the ram module information from Ubuntu. Please use command dmidecode with type 17. ex. $ sudo dmidecode --type 17 | more Wish this helps. regards, Stanley Huang

[Level 1] Install maven in Ubuntu

In Ubuntu, you could use apt-get to install maven. # apt-get -y install maven2 Wish this helps. regards, Stanley Huang

[Level 1] Install git in Ubuntu

If you want to install git in Ubuntu, you could use apt-get command: # apt-get -y install git-core git-doc git-gui gitk Wish this helps. regards, Stanley Huang

[Level 3] Cassandra stress tool from git in Ubuntu.

If you want to do the stress test for Cassandra. You could try an open source project call cassandra-stress of zznate. First you must to have git client and maven. Please reference here: git installation , maven installation Clone the src from git. # git clone https://github.com/zznate/cassandra-stress.git Then you would find a folder named "cassandra-stress", cd it and build the binary. # cd ./cassandra-stress # mvn install and mvn would create a sub folder "target", cd it and run the stress script. # cd ./target/appassembler/ # sh ./bin/stress -o insert -b 1000 -n 2000000 localhost:9160 Wish this helps. regards, Stanley Huang

[Level 3] Run python in shell script.

If you want to wrap python script into shell script. You could use the following sample code. #!/bin/sh # -*- mode: Python -*- """:" # bash code here; finds a suitable python interpreter and execs this file. # prefer unqualified "python" if suitable: python -c 'import sys; sys.exit(sys.hexversion < 0x020500b0)' 2>/dev/null \ && exec python "$0" "$@" for pyver in 2.6 2.7 2.5; do which python$pyver > /dev/null 2>&1 && exec python$pyver "$0" "$@" done echo "No appropriate python interpreter found." >&2 exit 1 ":""" import os, sys print os.path.dirname('/Hello/World/c.txt') $ ./test.sh /Hello/World Wish this helps. regards, Stanley Huang

[Level 2] Cassandra token generation tool by Python.

#!/bin/env python import sys if (len(sys.argv) > 1): num=int(sys.argv[1]) else: num=int(raw_input("How many nodes are in your cluster? ")) for i in range(0, num): print 'node %d: %d' % (i, (i*(2**127)/num)) $ ./cassandraTokenGenTools.py How many nodes are in your cluster? 5 node 0: 0 node 1: 34028236692093846346337460743176821145 node 2: 68056473384187692692674921486353642291 node 3: 102084710076281539039012382229530463436 node 4: 136112946768375385385349842972707284582 Wish this helps. regards, Stanley Huang

[Level 2] JSON module in Python.

#!/bin/env python import json import random data = {} for i in range(0,2): key = 'i%s' % i data[key] = {} for j in range(0,3): subkey = 'j%s' % j data[key][subkey] = {} for k in range(0,4): item = 'k%s' % k value = int(random.random() * 100) data[key][subkey][item] = value print json.dumps(data) $ ./testPython.py {"i1": {"j0": {"k3": 93, "k2": 98, "k1": 0, "k0": 3}, "j1": {"k3": 53, "k2": 28, "k1": 99, "k0": 69}, "j2": {"k3": 3, "k2": 93, "k1": 74, "k0": 28}}, "i0": {"j0": {"k3": 67, "k2": 98, "k1": 15, "k0": 92}, "j1": {"k3": 70, "k2": 22, "k1": 63, "k0": 3}, "j2": {"k3": 88, "k2": 28, "

[Level 3] Add row count in select of MySQL.

mysql> set @row_count; mysql> select *, @row_count := @row_count + 1 as row_count from test; +------+---------+-----------+ | id | product | row_count | +------+---------+-----------+ | 1 | cloth | 1 | | 2 | shoes | 2 | | 3 | paints | 3 | +------+---------+-----------+ 10 rows in set (0.00 sec) Wish this helps. regards, Stanley Huang

[Level 3] rw_ether_atob, rw_ether_btoa stored function in MySQL.

delimiter // drop function if exists rw_ether_atob// create function rw_ether_atob(sAscii char(17)) returns bit(48) deterministic begin declare bReturn bit(48); ##set bReturn=conv(replace(sAscii,':',''),16,2); ## string output not bit ##set bReturn=conv(replace(sAscii,':',''),16,10); ## not work ##set bReturn=cast(replace(sAscii,':','') as bit(48)); ## syntax error ##set bReturn=bin(replace(sAscii,':','')); ## syntax error set bReturn=unhex(replace(sAscii,':','')); return bReturn; end// drop function if exists rw_ether_btoa// create function rw_ether_btoa(sBit bit(48)) returns char(17) deterministic begin declare sReturn char(17); set sReturn=lpad(hex(sBit),12,'0'); set sReturn=concat_ws(':', substr(sReturn,1,2), substr(sReturn,3,2), substr(sReturn,5,2), substr(sReturn,7,2), substr(sReturn,9,2), substr(sReturn,11,2)); return sReturn; end// delimiter ; /* mysql> c

[Level 1] Notes for MySQL. (config)

## take care with signature '???' [mysql] user=root password database=mysql #!include /etc/my.inc #prompt=\R:\m \d> #prompt=\u:\h \d> [mysqldump] [client] ## new cert #ssl-key=/usr/local/mysql/newcerts/client-key.pem #ssl-cert=/usr/local/mysql/newcerts/client-cert.pem #ssl-ca=/usr/local/mysql/newcerts/ca-cert.pem user=root host=localhost protocol=tcp compress password ######################################################[mysqld_multi] [mysqld_multi] server-id = 0 mysqld = /usr/local/mysql/bin/mysqld_safe mysqladmin = /usr/local/mysql/bin/mysqladmin user = multi_admin password = my_password [mysqld2] socket = /tmp/mysql.sock2 port = 3307 pid-file = /usr/local/mysql/data2/hostname.pid2 datadir = /usr/local/mysql/data2 language = /usr/local/mysql/share/mysql/english user = unix_user1 [mysqld3] mysqld = /path/to/safe_mysqld/safe_mysqld ledir = /path/to/mysqld-binary/ mysqladmin = /path/to/mysqladmin/mysqladmin socket = /

[Level 1] Testing notes for MySQL. (mysql commands)

#!/usr/bin/bash #ln -s /dev/null .mysql_history ## in my.cnf MYSQL_HISTFILE=/dev/null #export MYSQL_PS1="(\u@\h) [\d]> " ## mysql --prompt="(\u@\h) [\d]> " #mysql -u mysql mysql < ./test_mysql.sql #mysql -u root mysql < ./test_mysql.sql #mysql -u root --defaults-file=/etc/my.ini ## mysqlslap, benchmark test # mysqlslap -auto-generate-sql # use default script mysqlslap -a -c100 i10 -u root -p --engine=InnoDB,MyISAM,MEMORY,ARCHIVE ## mysqlcheck, for MyISAM, InnoDB, CSV and Archive. #mysqlcheck world; #mysqlcheck world City Country; #mysqlcheck --databases world test; #mysqlcheck --all-databases; ## bin-log #mysqlbinlog bin.000001 bin.000002 | more #mysqlbinlog bin.000001 bin.000002 | mysql #mysqlbinlog --start-datetime="2009-01-01 00:00:00" --stop-datetime="2009-01-01 23:59:59" bin.000001 bin.000002 | mysql #mysqlbinlog --start-position=1001 --stop-position=1999 bin.000001 bin.000002 | mysql ## purge binary logs #mysql> purge bin

[Level 1] Testing notes for MySQL. (sql commands)

The following commands are my testing notes for MySQL. set sql_mode:=''; -- set sql_mode='only_full_group_by'; -- with group by syntax, select columns must be included in group by list. set sql_mode='traditional'; -- a set of modes, fail sql transaction while datatype error or out of range. -- set sql_mode='pipes_as_concat'; -- set || from logic 'or' to string concatenation (standard sql). -- set sql_mode='ansi_quote'; -- ' for string, " for column name select @@sql_mode; -- set sql_mode='no_auto_create_user'; -- for not auto create user when grant, except grant with identified by. ######################################### notes ## select @@query_cache_type ## @@query_cache_size ## show variable like 'query%'; ## show status like 'qcache%'; ## select sql_no_cache ... /* mysql client */ /* \c to cancle mysql statement. */ /* command */ /* show processlist; show full processlist; show