Thursday, December 30, 2010

[Reference] From Perl 5 to Perl 6.

Good article for Perl programmer from 5 to 6.

http://perlgeek.de/en/article/5-to-6

Wish this helps.
regards,
Stanley Huang

Tuesday, December 28, 2010

[Level 1] Python int array join.

When you have a int array and you want to concatenate them into a string.
You might use this syntax, and python return you the TypeError.
>>> a=[1,2,3]
>>> print ' '.join(a)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sequence item 0: expected string, int found
How could we solve this problem?
1. Use a generator expression:
>>> print ' '.join(str(i) for i in a)
1 2 3
>>>

2. Use imap method from itertools
>>> from itertools import imap
>>> print ' '.join(imap(str, a))
1 2 3
>>>

Wish this helps.
regards,
Stanley Huang

Monday, December 27, 2010

[Level 3] Recovering an Innodb table from only an .ibd file.

Just got this information for the internet.
It's a good reference.

Recovering an InnoDB table from only an .ibd file.


Wish this helps.
regards,
Stanley Huang

Tuesday, December 21, 2010

[Level 3] Use cmd module to create python cli program.

How to use cmd module to create python cli program?
Please refer to the following sample:

$ cat ./cli.py
#!/usr/bin/python
import os, sys
from menu.CLI_main import CLI_main
###################################### main
if __name__ == '__main__':
    cli=main("user","host")
    cli.cmdloop()
$
$ cat ./main.py 
import cmd
class main(cmd.Cmd):
    def __init__(self, user, host):
        cmd.Cmd.__init__(self)
        self.user = user
        self.host = host
        self.prompt = "%s@%s:%s> " % (user, host, "main")

    def do_system(self, args):
        from system import system
        sub_cmd = system(self.user, host)
        sub_cmd.cmdloop()
    def help_system(self):
        print "system sub menu of cli"

    def do_show(self, args):
        print "show"

    def do_quit(self, args):
        return True
$
$ cat ./system.py
import cmd
class system(cmd.Cmd):
    def __init__(self, user, host):
        cmd.Cmd.__init__(self)
        self.user = user
        self.host = host
        self.prompt = "%s@%s:%s> " % (user, host, "system")

    def do_show(self, args):
        print "show"

    def do_quit(self, args):
        return True
$
$ ./cli.py

user@host:main> help

Documented commands (type help ):
========================================
system

Undocumented commands:
======================
help  show
quit
user@host:main> system
user@host:system> quit 
user@host:main> quit
$

Wish this helps.
regards,
Stanley Huang

Monday, December 20, 2010

[Level 2] Refactoring your single python file program into module files.

How to refactory your single pyhon file with multi module files?

1. create folder for modules.
2. create empty __init__.py in the folder.
3. move partial your code into the new folder.
4. add import syntax into your main program.
5. test it.
6. done.

e.g.
Before refactoring:
$ cat ./t.py
#!/usr/bin/python
class a():
  def a(self):
    print "call a()"

class b():
  def b(self):
    print "call b()"

if __name__ == '__main__':
  c=a()
  c.a()
  d=b()
  d.b()

After refactoring:
$ ls -al
total 8
drwxr-xr-x   5 root  root  170 Dec 20 23:14 .
drwxrwxrwt  16 root     root  544 Dec 20 23:17 ..
drwxr-xr-x   6 root  root  204 Dec 20 23:13 a
drwxr-xr-x   6 root  root  204 Dec 20 23:13 b
-rwxr--r--   1 root  root  119 Dec 20 23:14 t.py
$
$ ls a
__init__.py    __init__.pyc    a.py        a.pyc
$
$ ls b
__init__.py    __init__.pyc    b.py        b.pyc
$
$ cat ./t.py
#!/usr/bin/python
from a.a import a
from b.b import b
if __name__ == '__main__':
  c=a()
  c.a()
  d=b()
  d.b()
$
$ cat ./a/a.py
class a():
  def a(self):
    print "call a()"
$
$ cat ./b/b.py
class b():
  def b(self):
    print "call b()"
$


Wish this helps.
regards,
Stanley Huang

Monday, December 13, 2010

[Level 2] How to create logical interface in Ubuntu?

Just use ifconfig and assign a ip to logical interface name.
Ex.
# ifconfig eth0:1 192.168.1.101 netmask 255.255.255.0

Wish this helps.
regards,
Stanley Huang

Wednesday, December 8, 2010

[ Tools ] Mp3 editor tool in Ubuntu.

A good tool for mp3 editor called "audacity".
How to install it in Ubuntu?

# apt-get install audacity
# audacity

Wish this helps.
regards,
Stanley Huang

Friday, November 26, 2010

[Level 1] How to install acroread in Ubuntu 10.04

If you want to install acroread in Ubuntu 10.04,
please follow the steps below:
1. active package resource "lucid-partner".
2. reload it.
3. search key word "acroread" and install it.

Wish this helps.
regards,
Stanley Huang

[Level 1] A tip for MySQL option.

--defaults-file=/... must be the first option or will occur the following error.

unknown variable 'defaults-file=/...'

Wish this helps.
regards,
Stanley Huang

Wednesday, November 24, 2010

[Reference] What Is New in MySQL 5.5

What Is New in MySQL 5.5


Wish this helps.
regards,
Stanley Huang

[Reference] Performance-Guide-for-MySQL-Cluster-Presentation

http://assets.en.oreilly.com/1/event/2/Performance%20Guide%20for%20MySQL%20Cluster%20Presentation.pdf

Wish this helps.
regards,
Stanley Huang

[Level 2] How to get tables are in use or locked in MySQL?

How to get tables are in use or locked in MySQL?
mysql> show open tables where in_use <> 0 or name_locked <> 0;

Wish this helps.
regards,
Stanley Huang

Tuesday, November 16, 2010

[Level 2] Create loopback device file in Ubuntu.

Create loopback device file in Ubuntu as following steps:

1. Create  block file
# dd if=/dev/zero of=/file bs=1k count=500
2. Create loopback device
# losetup /dev/loop0 /file
# losetup -a

3. Create filesystem
# mkfs -t ext2 /dev/loop0
4. Mount loopback device
# mount -t ext2 /dev/loop0 /mnt 
5. Umount loopback device

# umount /dev/loop0
6. Delete loopback device
# losetup -d /dev/loop0

ref:
http://manpages.ubuntu.com/manpages/lucid/man8/losetup.8.html

Wish this helps.
regards,
Stanley Huang

Tuesday, October 26, 2010

[Level 3] Create bootable usb stick for Ubuntu.

If you want to create bootable usb stick to install Ubuntu,
please follow the steps below:
1. Download usb-creator package.
# apt-get -y install usb-creator
2. Run usb-creator.
# usb-creator-gtk
3. choose ISO image file.
4. create usb bootable stick.

Wish this helps.
regards,
Stanley Huang

Thursday, October 21, 2010

[Level 3] Method Resolution Order in Python

If you want to know the ordering of the method, you can check from __mro__.
Ex.
>>> class c11(object):
...   pass
...
>>> class c12(object):
...   pass
...
>>> class c21(object):
...   pass
...
>>> class c22(object):
...   pass
...
>>> class c1(c11,c12):
...   pass
...
>>> class c2(c21,c22):
...   pass
...
>>> class c(c1,c2):
...   pass
...
>>> c.__mro__
(, , , , , , , )
>>>

Wish this helps.
regards,
Stanley Huang

Tuesday, October 19, 2010

[Level 2] How to install nfs client/server on Ubuntu

NFS Server
1. apt-get install nfs-kernel-server
2. vi /etc/exports
ex.
/home/stanley *(rw,sync,no_root_squash)
3. /etc/init.d/nfs-kernel-server start


NFS Client
1. apt-get -y install nfs-common
2. vi /etc/vfstab
ex.
192.168.1.1:/home/stanley /mount/stanley nfs rw 0 0
3. mkdir -p /mount/stanley
4. mount /mount/stanley
5. mkdir -p /mount/stanley2
6. mount -t nfs 192.168.1.1:/home/stanley /mount/stanley2




Wish this helps.
regards,
Stanley Huang

Monday, October 11, 2010

[Level 1] How to change zone in Ubuntu?

How to change time zone in Ubuntu?
Just use the command dpgk-reconfigure

Ex.
#dpkg-reconfigure tzdata

Wish this helps.
regards,
Stanley Huang

Thursday, October 7, 2010

[Level 1] How to grant sudo without password in Ubuntu

If you want to grant root permission to user with sudo,
and also let user doesnot need to input his password while using sudo.
Just add pattern in your visudoers:
username host=NOPASSWD: commands/ALL
Ex.
# visudo 
[original contents]
...
%admin ALL=(ALL) ALL
...
[add new line]
stanley ALL=(ALL) NOPASSWD: ALL

PS. For above example, if user is inclued in admin group, please make sure new line is added at the below of group setting, or group setting will overwrite your setting and let use have to input his password while using sudo.

Wish this helps.
regards,
Stanley Huang

Monday, September 20, 2010

[Level 2] How to display GUI to remote host.

If you want to display GUI from remote host to local host.
You can enable it as following steps:
1. enable gdm tcp listener.

local# vi /etc/gdm/gdm.schemas
...
<schema>
<key>security/DisallowTCP <key>
<signature>b<signature>
<default>false<default>
<schema>
...  
PS. default is true.

2. restart local gdm.

local# pkill -HUP X


3. enable remote session.

local# xhost +


4. setting remote display

remote# export DISPLAY=local_ip:0.0
or login remote server with ssh -X
local# ssh -X remote-host

5. try with xclock

remote# xclock


Wish this helps.
regards,
Stanley Huang

Setting vim with press "tab" key as 4 spaces in VIM.

How to let vim to type "tab" as 4 spaces?
Add following setting in ~/.vimrc

set smartindent                                                                                           

set tabstop=4                                                                      

set shiftwidth=4                                                                                           
set expandtab                                                                                          


Wish this helps.
 regards,
Stanley Huang

Friday, September 10, 2010

[Level 2] Use ffmpeg to record desktop in Ubuntu.



You can use ffmpeg to record your desktop.

1. install ffmpeg first.
# atp-get install ffmpeg

2. use command to record.

# ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg

3. play it

# vlc /tmp/out.mpg

with this helps.


regards,

Stanley Huang

[Level 1] How to flush memory cache in Ubuntu?

How to use command to flush memory cache?

#echo 1 > /proc/sys/vm/drop_caches  ## flush by command
#echo 0 > /proc/sys/vm/drop_caches  ## restore to system default value

Wish this helps.

regards,
Stanley Huang

[Installation] Chrome auto reload extension.

If you need to refresh your chrome periodically,
you can install chrome reload extension.

https://chrome.google.com/extensions/detail/njoipeaphfnaplplihpbgndfojhdhmjo

Wish this helps.
regards,
Stanley Huang

Thursday, September 9, 2010

[Level 1] How to get the package file list which is installed by apt-get

If you want to get the file list of package which is installed by apt-get.
You can use "dpkg" command,
Ex.
# dpkg -L memcached
/.
/etc
/etc/default
/etc/default/memcached
/etc/init.d
/etc/init.d/memcached
/usr
/usr/share
/usr/share/doc
/usr/share/doc/memcached
/usr/share/doc/memcached/changelog.gz
/usr/share/doc/memcached/NEWS.gz
/usr/share/doc/memcached/README
/usr/share/doc/memcached/protocol.txt.gz
/usr/share/doc/memcached/README.Debian
/usr/share/doc/memcached/copyright
/usr/share/doc/memcached/changelog.Debian.gz
/usr/share/doc/memcached/memory_management.txt.gz
/usr/share/memcached
/usr/share/memcached/scripts
/usr/share/memcached/scripts/start-memcached
/usr/share/memcached/scripts/memcached-tool
/usr/share/memcached/memcached.conf.default
/usr/share/man
/usr/share/man/man1
/usr/share/man/man1/memcached.1.gz
/usr/bin
/usr/bin/memcached
/usr/include
/usr/include/memcached
/usr/include/memcached/protocol_binary.h
#


Wish this helps.
regards,
Stanley Huang

[Level 2] Repication in Cassandra 0.7 Beta

In Cassandra 0.7, it supports online change schema.
So, when you want to create a keyspace, the steps are as following:
1. Connect to Cassandra
 # ./bin/cassandra-cli 
2. Create keyspace
# create keyspace keyspace_name with replication_factor = n
PS. In here, 'n' is integer, and the number of cassandra node must great or equal than 'n'.

You can set replication factor

Wish this helps.
regards,
Stanley Huang

Wednesday, September 8, 2010

[Level 2] Use apt-get to Install VritaulBox from official repository

If you want to use apt-get command to install VirtaulBox from official resposity.
The steps are as following:

1. Use browser to connect official website:
http://www.virtualbox.org/
2. Click the left side menu bar with item "download"
3. Select "VirtualBox 3.2.8 for Linux hosts"
4. Then you can see a section call "Debian-based Linux distributions"
5. add respository to your system. (modify /etc/apt/sources.list)
Ex. lucid version
# echo "deb http://download.virtualbox.org/virtualbox/debian lucid non-free" >> /etc/apt/source.list
6. get keys by wget
# wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add -
7. update your apt
# sudo apt-get update
8. install by apt-get
# sudo apt-get install virtualbox-3.2

Wish this helps.
regards,
Stanley Huang

Monday, September 6, 2010

[Level 1] Install openvpn in Ubuntu

How to setup openvpn client in Ubuntu?
The steps as following:
1. Install openvpn package:
# apt-get install openvpn
2. Setup client configuration:
# vi ./my.ovpn
3. Run openvpn with root permission:
# sudo openvpn --config ./my.ovpn

Wish this helps.
regards,
Stanley Huang

[Level 1] ntpclient in Ubuntu

If you want to sync system time.
You can use command ntpdate.

# sudo ntpdate ntp.ubuntu.com

Wish this helps.
regards,
Stanley Huang

[Info] Riptano Cassandra Summit 2010 Vedios

Good for you to reference.

http://www.riptano.com/summit-2010

Wish this helps.
regards,
Stanley Huang

Sunday, September 5, 2010

[Level 1] Widget on Ubuntu

If you like the widget of Mac, and you want your Ubuntu has widgets too.
You can try the following widgets.
1. screenlet:
# sudo apt-get install screenlets screenlets-doc
# screenlets
2. gdesklets:
# sudo apt-get install gdesklets gdesklets-data
# gdesklets
3. google gadgets:
# sudo apt-get install google-gadgets-gtk
# ggl-gtk


Wish this helps.
regards,
Stanley Huang

Tuesday, August 31, 2010

[Level 2] Bash completion in Ubuntu

As we know, we can use "tab" for word completion.
And now, you can also use "tab" for bash completion.
That means when you finished typing your command,
ex. # apt-get
and you press "tab", then you will get the options for apt-get.
# apt-get
autoclean        clean            purge            upgrade
autoremove       dist-upgrade     remove          
build-dep        dselect-upgrade  source          
check            install          update

How could you enable this feature?
add the following command in your ~/.bashrc, if not exists.
if [ -f /etc/bash_completion ] then;
    . /etc/bash_completion
fi


Wish this helps.
regards,
Stanley Huang

Sunday, August 29, 2010

[Level 2] Math exam generator

This morning, my son ask me to give him a 50 question math exam.
So I wrote a math exam generator to produce the exam.
PS. You need OpenOffice to open result file.

#!/bin/bash
set -f
declare -i nQ=${1:-50}
declare    sF=$0.csv; [ -f $sF ] && rm $sF;
declare -i i=0
declare    aOperator=(+ - * /); declare -i nOperator=4
declare    aOperator=(+ -); declare -i nOperator=2

getRandomNumber() {
  declare -i n=$RANDOM*89/32767+10
  echo $n
}

getRandomOperator() {
  declare -i n=$RANDOM*$nOperator/32767
  echo ${aOperator[$n]}
}

for i in `seq 1 $nQ`
do
  declare -i n1=`getRandomNumber`
  declare -i n2=`getRandomNumber`
  declare    sO=`getRandomOperator`
  echo "$n1,$sO,$n2,=,,=if(isblank(e$i);0;if(e$i=(a$i${sO}c$i);1;0))" >> $sF
done
echo ",,,correct,=,=sum(f1:f$i),/$i" >> $sF
echo ",,,score,=,=sum(f1:f$i)/$i*100" >> $sF
soffice $sF


Wish this helps.
regards,
Stanley Huang

Monday, August 16, 2010

[Level 1] Upgrade GNOME desktop from 2 to 3 in Ubuntu.

Upgrade your GNOME desktop from 2 to 3.
  • sudo apt-get build-dep gnome-shell
  • sudo apt-get install gnome-shell
  • gnome-shell --replace

Wish this helps.
regards,
Stanley Huang

[Level 1] OpenSolaris is died?!

In these days, friends of mine asked about "Is OpenSolaris is died?".
My answer is, "OpenSolaris" is died, but the spirit of "Open" "Solaris" is never die.
Because some boarders of OpenSolaris, host a new project call "IllumOS".
If you like OpenSolaris, IllumOS might be your best choice.

Wish this helps.
regards,
Stanley Huang

Thursday, August 5, 2010

[Level 3] Menu Bash Script

One day, one friend of mine ask me how to create a menu with timeout limitation in bash, then I wrote the sample code for him.
I think this maybe a good idea if I can write a menu bash script with dynamic setting menu item and so on.
Therefore I write the script below, any feedback will be appreciate.

#!/bin/bash

##############################################
##
## for menu utility
##
## author: Stanley Huang
## licence: Creative Commons Attribution-Share Alike 3.0 Taiwan License
## last release reversion: 0.1
## last modify date: 2010/08/04 15:30
## change list:
##   01. 2010/08/04 15:30, Stanley Huang. Build.
##
##############################################

showUsage() {
  cat<<EOF
Usage:
  $0
     [-e] (expert mode)
     [-h] (help menu)
     [-t] timeout_sec (default timeout = $nTimeout sec)
     [-c] no. of columns to display (default no. of column = $nColumn)
     [-w] column wide (default column wide = $nWide)
     [-m] menu file
Ex.
  $0
  $0 -e
  $0 -h
  $0 -t 10
  $0 -c 3
  $0 -w 10
  $0 -m /tmp/t.menu
EOF
}

pak2c() {
  read -n 1 -p "Press any key to continue..." pak2c
}

checkItemExist() {
  local sItem=$1
  grep "^$sFilter$sItem$sMenuActSeparator" $sMenuFile > /dev/null 2>&1
  return $?
}

checkItemNotExist() {
  local sItem=$1
  checkItemExist $sItem
  if [ $? -eq 0 ]
  then
    return 1
  else
    return 0
  fi
}

getHeader() {
  local sHeader="`grep "^$sHeaderFilter" $sMenuFile | head -1 | cut -d' ' -f2-`"
  echo $sHeader
}

setHeader() {
  while true
  do
    read -p "Please enter your header: " sNewHeader
    [ ! -z "$sNewHeader" ] && break
  done
  sHeader=$sNewHeader
  if [ `grep -c "^$sHeaderFilter" $sMenuFile` -ne 0 ]
  then
    perl -pi -e "s/^$sHeaderFilter.*$/$sHeaderFilter$sNewHeader/" $sMenuFile
  else
    echo "$sHeaderFilter$sNewHeader" >> $sMenuFile
  fi
}

buildMenu() {
  clear
  declare -i nColumn=$1
  declare -i nWide=$2
  declare -i nCount=0
  declare -i nMod=0
  declare    sCount=""

  printf -- "$sOuterSeparatorLine\n" && \
  printf -- "        `getHeader`\n" && \
  printf -- "$sOuterSeparatorLine\n" && \

  while read fItem item
  do
    nCount=$nCount+1 && sCount=$nCount && [ $isExpert -eq 0 ] && sCount=.
    aMenu[$nCount]="`echo $item | awk -F$sMenuActSeparator '{print($1)}'`"
    aActs[$nCount]="`echo $item | awk -F$sMenuActSeparator '{print($2)}'`"
   
    fDisable=`echo $fItem | sed -e 's/[^*]//g'`
    printf "%${#nTotalCount}s) %${nWide}s%1s" $sCount ${aMenu[$nCount]} $fDisable
   
    nMod=$nCount%$nColumn
    if [ $nMod -eq 0 ]
    then
      printf "\n";
    else
      printf " ";
    fi
  done <<EOF
`grep "^$sFilter" $sMenuFile ## disable display with sorting`
EOF
  #### `grep "^$sFilter" $sMenuFile | sort -k 2 ## display with sorting`
  [ $nMod -ne 0 ] &&  printf "\n"

  printf -- "$sOuterSeparatorLine\n" && \
  if [ "$isExpert" -eq 0 ]
  then
    printf "%${#nTotalCount}s) %${nWide}s\n" "a" "(A)dd"
    printf "%${#nTotalCount}s) %${nWide}s\n" "c" "(C)hange name"
    printf "%${#nTotalCount}s) %${nWide}s%s\n" "d" "(D)isable" ", marked *"
    printf "%${#nTotalCount}s) %${nWide}s\n" "e" "(E)nable"
    printf "%${#nTotalCount}s) %${nWide}s\n" "h" "set (H)eader"
    printf "%${#nTotalCount}s) %${nWide}s\n" "m" "(M)odify"
    printf "%${#nTotalCount}s) %${nWide}s\n" "r" "(R)emove"
    printf "%${#nTotalCount}s) %${nWide}s\n" "s" "(S)ort data"
    printf "%${#nTotalCount}s) %${nWide}s\n" "v" "(V)iew cmd"
    printf -- "$sInnerSeparatorLine\n"
    printf "%${#nTotalCount}s) %${nWide}s\n" "n" "(N)ormal mode"
  else
    printf "%${#nTotalCount}s) %${nWide}s\n" "e" "(E)xpert mode"
  fi
  printf "%${#nTotalCount}s) %${nWide}s\n" "q" "(Q)uit"
  printf -- "$sOuterSeparatorLine\n"
}

## Usage:
##   repeat [character] [line size]
## Ex.
##   repeat x 100
repeat() {
  [ $# -lt 2 ] && return 1
  sChar=${1:0:1}
  nSize=$2
  printf -vch  "%${nSize}s" ""
  printf "%s\n" "${ch// /$sChar}"
}

############################################# main

clear
set -o noglob
declare -i nDefaultTimeout=10
declare -i nExpertTimeout=65535
declare -i nTimeout=$nDefaultTimeout
declare -i isExpert=1
declare -a aMenu
declare -a aActs
declare    sMenuActSeparator=":"
declare    sFilter=""
declare -i nTotalCount=0
declare -i nDefaultColumn=1
declare -i nExpertColumn=3
declare -i nColumn=$nDefaultColumn
declare -i nWide=16
declare -i nActionWide=20
declare    sMenuFile=$0 ## default menu file is program itself.

declare -i nSeparatorLength=30
declare    sOuterSeparatorLine=`repeat = $nSeparatorLength`
declare    sInnerSeparatorLine=`repeat - $nSeparatorLength`

while getopts ":ehc:t:w:m:" opt
do
  case $opt in
  e)
    isExpert=0
    ;;
  h)
    showUsage
    exit 0
    ;;
  c)
    nDefaultColumn=$OPTARG
    ;;
  m)
    sMenuFile=$OPTARG
    ;;
  t)
    nDefaultTimeout=$OPTARG
    ;;
  w)
    nWide=$OPTARG
    ;;
  :)
    echo "The option ($opt) without parameters, exit program..."
    showUsage
    exit 1
    ;;
  \?)
    echo "Not such option($OPTARG), exit program..."
    showUsage
    exit 1
    ;;
  esac
done

sEnableFilter="#@ "
sDisableFilter="#\* "
sNormalFilter=$sEnableFilter
sExpertFilter="#[@*][ ]"
sExpertFilter4Perl="(#[@*][ ])"
sHeaderFilter="#\^ "
if [ $isExpert -eq 0 ]
then
  sFilter=$sExpertFilter
  nTimeout=$nExpertTimeout
  nColumn=$nExpertColumn
else
  sFilter=$sEnableFilter
  nTimeout=$nDefaultTimeout
  nColumn=$nDefaultColumn
fi
nTotalCount=`grep -c "^$sFilter" $sMenuFile`

while true
do
  buildMenu $nColumn $nWide
  declare -i nChoice
  declare    sChoice
  declare -i fRead=0
  declare    sItem=""

  while true
  do
    echo -n "Please enter your choice ($nTimeout secs to timeout): "
    read -t $nTimeout sChoice || fRead=$?

    #### special events
    [ $fRead -eq 142 ] && echo "Time out..." && exit 0
    [ $isExpert -eq 1 ] && [ $sChoice == 'e' ] && $0 -e -t $nDefaultTimeout -m $sMenuFile && exit 0
    [ $isExpert -eq 0 ] && [ $sChoice == 'n' ] && $0 -t $nDefaultTimeout -m $sMenuFile && exit 0
    [ $sChoice == 'q' ] && exit 0

    #### choice reactions
    nChoice=$sChoice
    [ -z "$sChoice" ] && buildMenu $nColumn $nWide && continue
    [ $isExpert -eq 1 ] && ( [ $nChoice -le 0 ] || [ $nChoice -gt $nTotalCount ] ) && continue
    [ $isExpert -eq 0 ] && ( [ $sChoice == "0" ] || [ $nChoice -ne 0 ] ) && continue
    break
  done

  case "$sChoice" in
  a)
    while true
    do
      read -p "Please enter the item you want to add: " sItem
      [ -z $sItem ] && break
      checkItemExist "$sItem" || break
      echo "Item ($sItem) exist!!"
    done

    if [ ! -z $sItem ]
    then
      read -p "Please enter the action of the item you added: " sAct
      if [ ! -z $sAct ]
      then
        echo "$sEnableFilter$sItem$sMenuActSeparator$sAct" >> $sMenuFile
        echo "Add item ($sItem) done..."
      fi
    fi
    ;;
  c)
    while true
    do
      read -p "Please enter the item you want to rename: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      read -p "Please enter the new name of the item: " sNewItemName
      perl -pi -e "s/^$sExpertFilter4Perl$sItem$sMenuActSeparator.*$/\1$sNewItemName$sMenuActSeparator$sAct/" $sMenuFile
      echo "change item name ($sItem -> $sNewItemName) done..."
    fi
    ;;
  d)
    while true
    do
      read -p "Please enter the item you want to disable: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      perl -pi -e "s/^$sEnableFilter$sItem$sMenuActSeparator/$sDisableFilter$sItem$sMenuActSeparator/" $sMenuFile
      echo "disable item ($sItem) done..."
    fi
    ;;
  e)
    while true
    do
      read -p "Please enter the item you want to enable: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      perl -pi -e "s/^$sDisableFilter$sItem$sMenuActSeparator/$sEnableFilter$sItem$sMenuActSeparator/" $sMenuFile
      echo "enable item ($sItem) done..."
    else
      echo "sItem is empty..."
    fi
    ;;
  h)
    setHeader
    ;;
  m)
    while true
    do
      read -p "Please enter the item you want to modify: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      read -p "Please enter the action of the item: " sAct
      perl -pi -e "s/^$sExpertFilter4Perl$sItem$sMenuActSeparator.*$/\1$sItem$sMenuActSeparator$sAct/" $sMenuFile
      echo "modify item ($sItem) done..."
    fi
    ;;
  r)
    while true
    do
      read -p "Please enter the item you want to remove: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      perl -pi -e "s/^$sExpertFilter$sItem$sMenuActSeparator.*\n$//" $sMenuFile
      echo "remove item ($sItem) done..."
    fi
    ;;
  s)
    cp $sMenuFile $sMenuFile.bak ## backup first
    declare -i nEOS=`grep -n '#### \*\*\* Data \*\*\*$' $sMenuFile | cut -d: -f1`
    declare -i nBOD=$nEOS+1 ## not work for Ubuntu
    declare -i nLOD=`wc -l $sMenuFile | awk '{print($1)}'`-$nEOS
    [ $nEOS -eq 0 ] && exit 0
    head -$nEOS $sMenuFile > /tmp/$$.main
    ##tail +$nBOD $sMenuFile | sed -e "s/^#[@*][ ]*$//" | sed -e "/^$/d" | sort -k 2 > /tmp/$$.data ## not work for Ubuntu
    tail -$nLOD $sMenuFile | sed -e "s/^$sExpertFilter*$//" | sed -e "/^$/d" | sort -k 2 > /tmp/$$.data
    cat /tmp/$$.main /tmp/$$.data > $sMenuFile
    rm /tmp/$$.main /tmp/$$.data
    echo "Sorting data done, please restart your program..."
    ;;
  v)
    while true
    do
      read -p "Please enter the item you want to view: " sItem
      [ -z $sItem ] && break
      checkItemNotExist "$sItem" || break
      echo "Item ($sItem) doesnot exist!!"
    done

    if [ ! -z $sItem ]
    then
      grep "^$sExpertFilter$sItem$sMenuActSeparator" $sMenuFile | awk -F"$sMenuActSeparator" '{print("Command:",$2)}'
    fi
    ;;
  "")
    ;;
  *)
    if [ $isExpert -eq 1 ] ## 1 for not expert mode!
    then   
      OLD_IFS=$IFS
      IFS=';'
      for sCmdOpts in ${aActs[$nChoice]}
      do
        echo "Execute Command: $sCmdOpts"
        eval $sCmdOpts
      done
      IFS=$OLD_IFS
    else
      continue
    fi     
    ;;
  esac
  pak2c
done

echo "End of process..."

exit
exit
exit

####
#### Menu item:
####   Use '#@ ', '#* ' at the begin of the line for setting menu item
####   #^ header(title)
####   #@ enable items
####   #* disable items
#### Ex.
####   #@ item
#### PS.
####   Do not modify the data below, use option "-e" (export mode) to modify.
####
#### *** Header ***
#^ My Menu
####
#### *** Data ***
#@ apple:echo "this an apple"
#@ banana:echo "this an banana"
#@ ls:ls
#@ id:id
#@ pwd:pwd
#@ stanley:id;pwd;ls -al;ls ./;echo 1 2 3;pwd;id

Wish this helps.
regards,
Stanley Huang

Monday, July 26, 2010

[Level 3] My Boy Friend (Bash Framework) Project @ first release

Recently, I collect my bash script,
and design my pattern for it.

Now, I decided to release it with
Creative Commons Attribution-Share Alike 3.0 Taiwan License.

With it can help you for your daily jobs.

Download link:
My Boy Friend (Bash Framework) Project.

Wish this helps.
regards,
Stanley Huang

Thursday, July 22, 2010

[Level 1] Install CouchDB in Ubuntu

How to install CouchDB in Ubuntu,
just use apt-get
# apt-get install couchdb

After start couchdb, then if you want to test manage couchdb.
You can use your brower to mange it.
# firefox http://localhost:5984 (default port)

If you want to test it by command,
you have two ways to do that.

1. Use telnet command:
# telnet locahost 5984
GET /test/test1234 HTTP/1.1
HTTP/1.0 200 OK
Server: CouchDB/0.10.0 (Erlang OTP/R13B)
Etag: "2-51d7e462ab7a57a53c0bd5a2b3becd52"
Date: Thu, 22 Jul 2010 03:04:54 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 80
Cache-Control: must-revalidate

{"_id":"test1234","_rev":"2-51d7e462ab7a57a53c0bd5a2b3becd52","name":"Stanley"}
Connection closed by foreign host.
#

2. Use curl:
a. First, download curl.
# apt-get install curl
b. Use curl to get data
# curl -X GET http://localhost:5984
/test/test1234{"_id":"test1234","_rev":"2-51d7e462ab7a57a53c0bd5a2b3becd52",
"name":"Stanley"}
#

Wish this helps.
regards,
Stanley Huang

Thursday, July 8, 2010

[Level 3] Maintain MySQL schema.

If you want to maintain MySQL with more flexible,
you need a procedure to do this for you.
(especially you want to manage schema upgrade patch...)
Therefore I write a procedure for this purpose, please refer to following code:

-- Usage: sp_altertable('database','table','column','add/drop/modify', 'type');
-- ex. mysql> call sp_altertable('test','mytab','mycol','add', 'varchar(2)');
-- ex. mysql> call sp_altertable('test','mytab','mycol','drop', '');
delimiter //
DROP PROCEDURE IF EXISTS sp_altertable//
CREATE PROCEDURE sp_altertable(in tableschema varchar(32), in tablename varchar(32), in columnname varchar(32), in action varchar(8), in ddl_statement varchar(128))
BEGIN
    set @sDDL='';
    select concat('ALTER TABLE ', tableschema, '.', tablename, ' ', action, ' ', columnname,' ', ddl_statement) into @sDDL;
    -- select @sDDL;
    prepare stmt_name from @sDDL;
    IF action='add' AND NOT EXISTS(
        SELECT * FROM information_schema.COLUMNS
        WHERE COLUMN_NAME=columnname AND TABLE_NAME=tablename AND TABLE_SCHEMA=tableschema
        ) THEN
            execute stmt_name;
    ELSEIF action='drop' AND EXISTS(
        SELECT * FROM information_schema.COLUMNS
        WHERE COLUMN_NAME=columnname AND TABLE_NAME=tablename AND TABLE_SCHEMA=tableschema
        ) THEN
            execute stmt_name;
    ELSEIF action='modify' THEN
        execute stmt_name;
    END IF;
END;
//
delimiter ;

Wish this helps.
regards,
Stanley Huang

[Level 1] Install Cassandra on OpenSolaris

You can install Cassandra by following steps:
# pfexec mkdir -p /var/lib/cassandra
# pfexec mkdir -p /var/lib/cassandra/data
# pfexec mkdir -p /var/lib/cassandra/commitlog
# pfexec mkdir -p /var/lib/cassandra/logs
# pfexec mkdir -p /var/log/cassandra
# pfexec chown -R root:root /var/lib/cassandra /var/log/cassandra
# pfexec chmod -R 755 /var/lib/cassandra

Set user environment on ~/.bashrc
export CASSANDRA_HOME=$HOME/cassandra/src
export CASSANDRA_CONF=$HOME/cassandra/conf
export CASSANDRA_PATH=$CASSANDRA_HOME/bin
export PATH=$CASSANDRA_PATH:$PATH

Then you have to download git (SUNWgit) from OpenSolaris repository to get Cassandra's source code.
# pkg install SUNWgit

Use git command as following to get the Cassandra's source:
# cd ~/         ## change working directory to user home, because we set 
                           CASSANDRA_HOME directory in $HOME/cassandra
# git clone git://git.apache.org/cassandra.git src

Select the 0.6.3 tag and create a branch.

# cd src
# git co origin/tags/cassandra-0.6.3
# git branch -b 0.6.3-sakai

Building the code, and the Cassandra jar using Ant.

# cd $CASSANDRA_HOME
# ant
# ant jar




Modify the storage-conf.xml in $CASSANDRA_CONF directory to add in the keyspace used.

Wish this helps.
regards,
Stanley Huang

Monday, July 5, 2010

[Level 2] Setup OpenVPN in OpenSolaris

Down pkgutil from Blastwave:
http://sourceforge.net/projects/pkgutil/
Prepare environment:
# unzip ./pkgutil-2.0.zip
# mkdir -p /var/opt/csw/
# ln -s `pwd` /var/opt/csw/
Install OpenVPN: 
# /opt/csw/bin/pkgutil -i tun tap
# /opt/csw/bin/pkgutil -i openvpn

Modify config:
# cd  /etc/csw/openvpn
# cp ./openvpn.conf.CSW ./openvpn.conf
# vi ./openvpn.conf


Setting vpn client: 
client
dev tun
proto tcp
remote vpn.server.hostname 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
comp-lzo
verb 3

Wish this helps. 
regards, 
Stanley Huang

Wednesday, June 9, 2010

[Level 2] Let 32 bit Ubuntu can use more than 3G ram.

How to let your 32 bit Ubuntu can use more than 3G RAM,
just install following packages:

# sudo apt-get install linux-restricted-modules-server
# sudo apt-get install linux-headers-server
# sudo apt-get install linux-image-server linux-server

Wish this helps.
regards,

Stanley Huang

Monday, May 24, 2010

[Level 3] Using vim to replace ^M with newline

I searched it on net

Under unix, inside vim, ^V + gives me a ^M which is the \r character.

Wish this helps.
regards,
Stanley Huang

Sunday, May 16, 2010

[Level 1] vim settings.

set nu
set ic
set nolist
set tabstop=4


Wish this helps.
regards,
Stanley Huang

Friday, May 14, 2010

[Level 3] Schema management tips for MySQL

{Database management tips}

[in source save]
4 files in source save.
1. schema:
=> by release version.
=> only create table/procedure, no alter, no insert, no drop ...etc.
=> use mysqldump -d.
2. schema change log:
=> by date.
=> split into two parts. one is schema(except foreign key), and put it on the top. Another is foreign key, and put it on the tail.
=> must add drop tabele before create, and must be sequencial by date.
=> modify manually.
3. data:
=> by release version.
=> only insert, no update, no delete...etc.
=> use mysqldump.
4. data change log:
=> by date.
=> could use insert/update/delete, but delete(truncate) must before update than insert, and must be sequencial by date.
=> modify manually.

[use case]
how to create patch:
a: use schema comparision.
=> takes time, but more efficacy.
b: use changelog comparision.
=> esay way, but suffer performance.
so, use a to build patch, but use b to verify result.
but how to verify?
use a, dump a schema and data,
use b, dump b schema and data,
compare two results.

[useful skill]
mysql> set foreign_key_checks=0;
mysql> set unique_checks=0;

Wish this helps.
regards,
Stanley Huang

Monday, May 3, 2010

[Level 3] Rownum/auto_increment, substring, reverse index, case and mutli-table update for MySQL

-- [rownum]
-- set initial equipment_id
select max(equipment_id) from device into @rownum;  
-- insert into equipment
insert into device
select @rownum:=ifnull(@rownum,-1)+1
from device;

-- [multi-table update]
update event
inner join device using (deviceid)
inner join equipment on device.macaddress = equipment.mac_address
set event.equipment_id = equipment.equipment_id
where event.eventtypeid < 400
;

-- [reverse index]
select instr(c,','),
substring(c,1,instr(c,',')-1),
reverse(substring(c,1,instr(c,',')-1)),
reverse(substring(reverse(substring(c,1,instr(c,',')-1)),1,instr(reverse(substring(c,1,instr(c,',')-1)),'@')-1))
from
(
select 'a@1:2:3:4,x,y,z' as c
union all
select '1:2:3:4,x,y,z' as c
union all
select 'a@b@1:2:3:4,x,y,z' as c
) as t

-- [case]
update types
set id =
  ( select case types.id
when 1 then 10001
when 2 then 10002
when 3 then 10003
when 4 then 10004
else types.id
end
)


Wish this helps. regards, Stanley Huang

Sunday, April 25, 2010

[Level 2] Use mkisofs to backup your filesystem.

You can use mkisofs to backup your filesystem.
# mkisofs --allow-lowercase --allow-multidot -r -o ./stanley.iso ./stanley
# mount -F hsfs `pwd`/stanley.iso /tmp/t

Wish this helps.
regards,
Stanley Huang

Friday, April 23, 2010

[Level 3] MySQL Stored Procedure Template.

This is my stored procedure template:

--
myparent_block:BEGIN
  -- declare variables
  DECLARE fetch_id INT DEFAULT NULL;
  DECLARE loop_done BOOLEAN DEFAULT FALSE;
  -- declare conditions
  DECLARE condition_not_found CONDITION FOR SQLSTATE '02000';
  -- declare cursors
  DECLARE cursor_myparent CURSOR FOR
    SELECT id FROM myparent WHERE serialnumber=sn;
  -- declare handlers
  DECLARE continue HANDLER FOR condition_not_found
    SET loop_done := TRUE;
  OPEN cursor_myparent;
  REPEAT
    FETCH cursor_myparent into fetch_id;
    DELETE FROM mychild WHERE pid=fetch_id;
  UNTIL loop_done END REPEAT;
  CLOSE cursor_device;
  DELETE FROM myparent WHERE fkid=fetchfkid;
END myparent_block;
--

Wish this helps.
regards,
Stanley Huang

Wednesday, April 21, 2010

[Level 3] South for Django 1.2

in south project:

http://south.aeracode.org/docs/databaseapi.html#database-specific-issues
South automatically exposes the correct set of database API operations as south.db.db; it detects which database backend you’re using from your Django settings file. It’s usually imported using:
from south.db import db
If you’re using multiple database support (Django 1.2 and higher), there’s a corresponding south.db.dbs dictionary which contains a DatabaseOperations object (the object which has the methods defined above) for each database alias in your configuration file:
from south.db import dbs
dbs['users'].create_table(...)
You can tell which backend you’re talking to inside of a migration by examining db.backend_name - it will be one of postgres, mysql, sqlite3, pyodbc or oracle.


It should worth to try~

Wish this helps.

regards,
Stanley Huang

[level 3] Customize Django Data Type Field.

I cannot fine char data type in Django 1.2 beta 1 .
So I try to build up my own data type field.
My sample code as following:

from django.db import models

# Create your models here.

from django.db.models import *
#from django.db import connection
#from django.db.models.fields.subclassing import LegacyConnection
#from django.db.models.query_utils import QueryWrapper
#from django.conf import settings
#from django import forms
#from django.core import exceptions, validators
#from django.utils.datastructures import DictWrapper
#from django.utils.functional import curry
#from django.utils.itercompat import tee
#from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
#from django.utils.encoding import smart_unicode, force_unicode, smart_str
#from django.utils import datetime_safe


# Create your models here.

# This is a much more flexible example.
class myCharField(Field):
    def __init__(self, *args, **kwargs):
        self.max_length = kwargs['max_length']
        super(myCharField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            return 'char(%s)' % self.max_length
        else:
            #raise exception
            pass

class myCharClass(models.Model):
  myCF = myCharField(max_length=30)
       

''' not recommend
class myCharField2(Field):
    empty_strings_allowed = False
    description = _("IP address")
    def __init__(self, *args, **kwargs):
        Field.__init__(self, *args, **kwargs)

    def get_internal_type(self):
        return "Char" ## add 'Char' type in django/db/backends/mysql/creation.py

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.IPAddressField}
        defaults.update(kwargs)
        return super(IPAddressField, self).formfield(**defaults)

class myCharClass2(models.Model):
  myCF = myCharField2(max_length=20)
'''

Wish this helps.

regards,
Stanley Huang

Monday, April 19, 2010

[Level 2] Remove all folders without any file.

If you want to remove all folders without any file, you can use the command to remove it.
# find ./ | sort -r | xargs rmdir 2>/dev/null

Wish this helps.

regards,
Stanley Huang

Thursday, April 15, 2010

[Level 2] Can't find message file on MySQL

If you have the same problem, you can use --language to assign language directory, Ex:

# ./bin/mysqld --user=mysql
100415 14:43:50 [ERROR] Can't find messagefile '/usr/share/english/errmsg.sys'
100415 14:43:50 [Note] Plugin 'FEDERATED' is disabled.
100415 14:43:50  InnoDB: Started; log sequence number 0 4604259
100415 14:43:50 [ERROR] Aborting
100415 14:43:50  InnoDB: Starting shutdown...
100415 14:43:56  InnoDB: Shutdown completed; log sequence number 0 4604259
100415 14:43:56 [Note]
#
# ./bin/mysqld --user=mysql --language=./share/english
100415 14:43:58 [Note] Plugin 'FEDERATED' is disabled.
100415 14:43:58  InnoDB: Started; log sequence number 0 4604259
100415 14:43:58 [Note] Event Scheduler: Loaded 0 events
100415 14:43:58 [Note] ./bin/mysqld: ready for connections.
Version: '5.1.45'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)

Wish this helps.

regards,
Stanley Huang

[Level 2] Check the port is used by process on Ubutun

If you want to check a port which is used by what process.
You can use the command to get information:

# netstat -an -tap | grep :::443
tcp6       0      0 :::443                  :::*                    LISTEN      31462/java
# ps -fp 31462
root     31462     1  7 10:46 pts/1    00:00:43 /opt/java/jre//bin/java ...

Wish this helps.

regards,
Stanley Huang

Wednesday, April 14, 2010

[Level 3] Install script for Ubuntu apt-get Command

I wrote a shell script for install ubuntu package:

#!/bin/bash
#apt-get update; apt-cache search key word; ## update apt-get cache and search key word
#apt-get install pkg-name; apt-get upgrade; ## install package
#apt-get remove pkg-name;                   ## remove package
#grep install /var/log/dpkg.log             ## apt-get install history
#ls /var/lib/dpkg/info                      ## apt-get installed packages
#dpkg -L tomcat6                            ## list apt-get specific installed packages

## show usage
showUsage() {
  cat <<EOF
Usage:
  $0 [-u] [-s] package1 package2
  $0 [-u] [-s] all
  $0 -l
option:
  -l: list all package
  -u: force to update apt-get cache
  -s: get source only
Ex.
  $0 vim
  $0 -u all
Package:
`egrep "^install_.*()" $0 | sort | grep -v "install_template()" | cut -d'_' -f2 | cut -d'(' -f1 | sed -e 's/^/  /'`
EOF
}

listAllPackages() {
  echo "All packages list:"
  egrep "^[_]?install_.*()" $0 | sed -e 's/^_//' | sort | grep -v "install_template()" | cut -d'_' -f2 | cut -d'(' -f1 | sed -e 's/^/  /'
}

## initialize
init_apt_get() {
  declare -i nReturn=0

  if ! grep "apt update done" $apt_get_init_file > /dev/null 2>&1
  then
    echo $update
    eval $update || nReturn=$nReturn+1
    eval $updatedone
  fi

  if ! grep "apt upgrade done" $apt_get_init_file > /dev/null 2>&1
  then
    echo $upgrade
    eval $upgrade || nReturn=$nReturn+2
    eval $upgradedone
  fi

  return $nReturn
}

## mysql server
_install_mysql-server() {
  echo $install mysql-server
  eval $install mysql-server && return $?
}

## vim
install_vim() {
  echo $install vim
  eval $install vim && return $?
}

## java
install_sun-java6-jdk() {
  echo $install sun-java6-jdk
  eval $install sun-java6-jdk && return $?
}

## eclipse
install_eclipse() {
  echo $install eclipse
  eval $install eclipse && return $?
}

## python-mysqldb
install_python-mysqldb() {
  echo $install python-mysqldb
  eval $install python-mysqldb && return $?
}

## django, use source file to install django (1.2 beta), python ./setup.py build, python ./setup.py install
_install_python-django() {
  echo $install python-django python-django-doc
  eval $install python-django python-django-doc && return $?
}

## tomcat6
_install_tomcat6() {
  echo $install tomcat6
  eval $install tomcat6 && return $?
}

## dpkg-dev, for get source from apt repository
install_dpkg-dev() {
  echo $install dpkg-dev
  eval $install dpkg-dev && return $?
}

## vnc4server
install_vnc4server() {
  echo $install vnc4server
  eval $install vnc4server && return $?
}

## template, remove the underscore at the head of function name, then replace all "template", and remove/uncomment the line "return 0".
__install__template() {
  return 0 ## uncomment it for real function
  echo $install template
  eval $install template && return $?
}


####################################################### main

## sudo init
clear
sudo id > /dev/null 2>&1

# environment variables
apt_get_init_file=/etc/.apt_get_init_file && sudo touch $apt_get_init_file
declare -i nShift
bSourceOnly=false
bForceUpdate=false
sOption=""

# command alias, called by $cmd
#echo 'Y' > /tmp/Y
search='sudo apt-cache search'
update='sudo apt-get -y --force-yes update'
install='sudo apt-get -y --force-yes install'
remove='sudo apt-get -y --force-yes remove'
upgrade='sudo apt-get -y --force-yes upgrade'
source='sudo apt-get -y --force-yes source'

updatedone="sudo echo apt update done... >> $apt_get_init_file"
upgradedone="sudo echo apt upgrade done... >> $apt_get_init_file"


sGetopts=":lsu"
while getopts $sGetopts o
do
  case "$o" in
  l)
    listAllPackages
    exit 0
    ;;
  s)
    bSourceOnly=true
    sOption="$sOption -s"
    ;;
  u)
    bForceUpdate=true
    sOption="$sOption -u"
    ;;
  \?)
    showUsage
    exit 1
    ;;
  esac
done
nShift=$OPTIND-1
shift $nShift

if [ -z $1 ]
then
    showUsage && echo "Error without args, exit program..." && exit 1
fi

## init or update
if (! init_apt_get) || $bForceUpdate
then
  ## update cache
  eval $update
fi


## replace install option with source
if $bSourceOnly
then
  install=$source
fi


while true
do
  if [ -z $1 ]
  then
    break
  elif [ $1 == "all" ]
  then
    egrep "^install_.*()" $0 | grep -v "install_template()" | cut -d'_' -f2 | cut -d'(' -f1 | xargs $0 $sOption
    break
  elif ! grep "^install_$1()" $0 > /dev/null 2>&1
  then
    echo "Cannot find $1, exit program..." && exit 2
  elif ! install_$1
  then
    echo "Error in install $1, exit program..." && exit 3
  else
    shift
  fi
done



Wish this helps.

regards,
Stanley Huang

[Level 2] Install chewing in Ubuntu

If you want to use Chinese Input in Ubuntu, you can setup the environment with scim. The commands as the following:
# apt-get install scim scim-pinyin scim-chewing scim-tables-zh scim-qtimm im-switch
# im-switch -s scim
Relogin again, and enjoy it!

Wish this helps.

regards,
Stanley Huang

Tuesday, April 13, 2010

[Level 1] Install unrar on CentOS

Install unrar on CentOS 5.4
# wget http://dag.wieers.com/packages/unrar/unrar-3.6.2-1.el4.rf.i386.rpm
# rpm -ivh unrar-3.6.2-1.el4.rf.i386.rpm

Run it:
# unrar e -kb myRar.rar

Wish this helps.

regards,
Publish Post

Stanley Huang

Monday, April 12, 2010

[Level 3] Python Desing Pattern -- Episode 0 -- Intro.

One Pattern a day, keep refactoring away~

Wish this helps.

regards,
Stanley Huang

Friday, April 9, 2010

[Level 2] MySQLdb Python API -- Cursor Objects

In myCxn.py:
import MySQLdb
cxn = MySQLdb.connect(host='localhost', db='test', user='root', passwd='admin' )
cur = cxn.cursor()


In main.py
## import object from file
from myCxn import  cur, cxn

cxn2 = cur.connection # pass the connection object from cursor
# cxn2.close() # close() will cause cur.execute() fail...

## before execute()
print "before execute():"
print "description:", cur.description
print "lastrowid:", cur.lastrowid # lastrowid => The id of last modified row.
print "rowcount:", cur.rowcount


cur.setoutputsizes(2) # seems not work, Does nothing, required by DB API.
cur.execute("select * from test.t;")
for data in cur.fetchall():
  print("cur1_fetchall.rownumber:", cur.rownumber)
  print("cur1_fetchall.rowrowcount:", cur.rowcount)
  print(data[0])
 
cur.execute("select * from test.t;")
for data in cur.fetchall():
  print("cur2_fetchall.rownumber:", cur.rownumber)
  print("cur2_fetchall.rowrowcount:", cur.rowcount)
  print(data[0]) 

cur.execute("select * from test.t;")
for data in cur.fetchone():
  print("cur3_fetchone.rownumber:", cur.rownumber)
  print("cur3_fetchone.rowrowcount:", cur.rowcount)
  print(data)

cur.execute("select * from test.t;")
cur.arraysize=3
for data in cur.fetchmany():
  print("cur4_fetchmany.arraysize:", cur.arraysize)
  print("cur4_fetchmany.rownumber:", cur.rownumber)
  print("cur4_fetchmany.rowrowcount:", cur.rowcount)
  print(data[0])
 
cur.execute("truncate table test.t;")
#cxn.query("drop procedure if exists test.proc1;")   # not show warning if not exists proc1
#cur.execute("drop procedure if exists test.proc1;") # still work, but if proc1 not exist, show warning

#cxn.execute("drop procedure if exists proc1;") # fail, no such attribute
#cur.query("drop procedure if exists proc1;")   # fail, no such attribute

## cannot query DDL for create stored procedure...
#cxn.query("delimiter $$")
#cxn.query("""
#create procedure test.proc1(in p1 int, in p2 int, in p3 int)
#begin
#insert into test.t values(p1),(p2),(p3);
#end$$
#""")
#cxn.query("delimiter ;")

results = cur.callproc("proc1",(1,2,3))
#cur.connection.commit()
print "results:", results
#results = cur.callproc("proc1",('a','b','c')) # error
#cur.connection.commit()
#print "results:", results

## after execute()
print "after execute():"
print "description:", cur.description
print "lastrowid:", cur.lastrowid # lastrowid => The id of last modified row.
print "rowcount:", cur.rowcount

## execute many
cur.setinputsizes(2) # seems not work, Does nothing, required by DB API.
cur.executemany("insert into test.t values(%s)",(10,20,30,40,50))           ## work
#cur.executemany("insert into test.t values(%s)",[(10),(20),(30),(40),(50)]) ## work
#cur.executemany("insert into test.t values(%s)",[10,20,30,40,50])           ## not work


for data in cur.fetchmany():
  #print(data[0],data[1],data[2])
  #print(data[0],data[1])
  print(data[0])

## after execute() 
print "after execute():"
print "description:", cur.description
print "lastrowid:", cur.lastrowid # lastrowid => The id of last modified row.
print "rowcount:", cur.rowcount

cur.connection.commit()
cur.close()
cxn.close()


print "End helloworld!"




Wish this helps.

regards,
Stanley Huang

[Level 3] MySQL Build Options Sample

A sample MySQL build options from MySQL Performance Blog:
# ./configure '--localstatedir=/var/db/mysql' '--without-debug' '--without-readline' '--without-libedit' '--without-bench' '--without-extra-tools' '--with-libwrap' '--with-mysqlfs' '--with-low-memory' '--with-comment=FreeBSD port: mysql-client-5.0.67_1' '--enable-thread-safe-client''--with-charset=cp1251' '--with-collation=cp1251_general_ci' '--with-extra-charset=all' '--with-named-thread-libs=-pthread' '--without-server''--prefix=/usr/local' '--mandir=/usr/local/man' '--infodir=/usr/local/info/''--build=amd64-portbld-freebsd7.0' 'CC=cc' 'CFLAGS=-O2 -mmmx -msse -msse2 -msse3 -pipe -march=nocona  -fno-strict-aliasing' 'CXXFLAGS=-O2 -mmmx -msse -msse2 -msse3 -pipe -march=nocona -fno-strict-aliasing -O2 -mmmx -msse -msse2 -msse3 -pipe -march=nocona  -fno-strict-aliasing -felide-constructors -fno-rtti -fno-exceptions' 'CXX=c++' 'build_alias=amd64-portbld-freebsd7.0'

Wish this helps.

regards,
Stanley Huang

Thursday, April 8, 2010

[Level 1] Install Django on CentOS 5.4

Just following the steps to install Django on CentOS 5.4
# yum install subversion
# cd $APACHE_HOME
# mkdir django-src
# cd django-src
# svn co http://code.djangoproject.com/svn/django/trunk/
# cd trunk
# python setup.py install

Wish this helps.

regards,
Stanley Huang

Wednesday, April 7, 2010

[Level 2] Case sensitive in MySQL.

The MySQL in Unix system, the database name and table name are case sensitive as default. But in Windows, they are case insensitive. That is because the file system in Unix are case sensitive but in Windows is not.
So, the easy way to solve the problem or for compatibility between different platform, you can choose the case sensitive or not in your MySQL database.
The way to setting it is the by the option "low-case-table-name", and there are three values (0,1,2) for this option.

0: Table and database names are stored on disk using the lettercase specified as DDL statement.
1: Table names are stored in lowercase on disk and name comparisons are not case sensitive.
2: Table and database names are stored on disk using the lettercase specified as DDL statement, but MySQL converts them to lowercase on lookup.

Wish this helps.

regards,
Stanley Huang

[Level 2] Script for mysql.

Because I have multi MySQL environments, so I have to assign different parameter (especially the "--socket" option) in different environment,
and it make me crazy.
So I create a folder "/shell" for store my scripts and create a alias "mysql" to the script in /shell.
My sample as the following:

.bashrc:
# cat ~/.bashrc | tail -3
export MYSQL_HOME=/usr/local/mysql/5.1
export PATH=$PATH:$MYSQL_HOME/bin
alias mysql="/shell/mysql"

Script /shell/mysql:
 #!/bin/bash -vx

echo "call $0..."
sMySQLCmdList="/usr/mysql/bin/mysql /usr/local/mysql/bin/mysql"
#sMySQLCmd=""
for sItem in $sMySQLCmdList
do
  if [ -f $sItem ]
  then
    sMySQLCmd=$sItem
    break
  fi
done
if pgrep mysqld
then
  mysql_socket=`ps -ef | grep mysqld | grep -v monitor | grep socket | sed -e 's/.*--socket=//' |     cut -d' ' -f1`
 
  if [ `echo $@ | grep -c -- -h` -eq 1 ]
  then
    $sMySQLCmd $@
  elif [ ! -z $mysql_socket ]
  then
    $sMySQLCmd --socket=$mysql_socket $@
  else
    $sMySQLCmd $@
  fi
else
  echo "No Running MySQL Server, Exit mysql" && exit 1
fi
 


Wish this helps.

regards,
Stanley Huang

[Level 2] How to backup MySQL partitioning table.

Sometimes, we will use partitioning to split the data into different files.
But how do we backup the data by the command mysqldump?
The same as the following:

Create table and insert data:
mysql> create table test.tr1 (
    ->   id int
    -> ) engine = InnoDB
    ->   partition by range (id)
    ->   (
    ->     partition p0 values less than (10),
    ->     partition p1 values less than (20),
    ->     partition pm values less than (maxvalue)
    ->   );
Query OK, 0 rows affected (0.17 sec)

mysql> insert into test.tr1 values (1),(2),(11),(12),(21),(22);
Query OK, 6 rows affected (0.30 sec)
Records: 6  Duplicates: 0  Warnings: 0


Dump data and list files:
# mysqldump --user=root --password=password --no-create-info --where="id<10" test tr1 > ./test.tr1.p0.sql;
# mysqldump --user=root --password=password --no-create-info --where="id>=10 and id<20" test tr1 > ./test.tr1.p1.sql;
# mysqldump --user=root --password=password --no-create-info --where="id>=20" test tr1 > ./test.tr1.p2.sql;
# ls -al ./test.tr1.p*.sql
-rw-r--r-- 1 root root 1476 2010-04-07 09:02 ./test.tr1.p0.sql
-rw-r--r-- 1
root root 1489 2010-04-07 09:02 ./test.tr1.p1.sql
-rw-r--r-- 1
root root 1479 2010-04-07 09:02 ./test.tr1.p2.sql




Wish this helps.

regards,
Stanley Huang