The Answer to Life, the Universe, and Everything

Monday, December 18, 2006

Delete old files

remove.sh
#!/bin/bash
FILE=/xxx/xxx
find ${FILE} -ctime +5 -type f -exec rm -f {} \;


Change the permission.
# chmod +x remove.sh
# crontab -e


Register it as cron job.
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
1 20 * * * root /root/remove.sh


Done.

Thursday, November 30, 2006

Debian apt management

This is the latest package update tool. Unlike netselect-apt, it doesn't use ICMP! which is often blocked now by firewall..

# s...location
# d...release type
# f...file to examin
# e...the number of host try
apt-spy -s nl -d unstable -f ls-lR.gz -e 10

Debian Keymap

Simple solution to change the keymap on Debian GNU/Linux.
loadkeys /usr/share/keymaps/i386/qwerty/jp106.kmap.gz
cp /usr/share/keymaps/i386/qwerty/jp106.kmap.gz /etc/console/boottime.kmap.gz

Monday, November 13, 2006

HibernateException


package org.hibernate;

import org.hibernate.exception.NestableRuntimeException;

/**
* Any exception that occurs inside the persistence layer
* or JDBC driver. SQLExceptions are always wrapped
* by instances of JDBCException.
*
* @see JDBCException
* @author Gavin King
*/

public class HibernateException extends NestableRuntimeException {

public HibernateException(Throwable root) {
super(root);
}

public HibernateException(String string, Throwable root) {
super(string, root);
}

public HibernateException(String s) {
super(s);
}
}

Sunday, November 12, 2006

Hibernate - Composite key

For a table with a composite key, you may map multiple properties of the class as identifier properties. The <composite-id>element accepts <key-property> property mappings and <key-many-to-one> mappings as child elements.

<composite-id>
<key-property name="medicareNumber"/>
<key-property name="dependent"/>
</composite-id>

Monday, November 06, 2006

Regex

Small sample to replace the regular expression..
Using Core API
String body = "\n";
String out;
Pattern pattern = Pattern.compile("class=\".*?\"");
Matcher matcher = pattern.matcher(body);
out = matcher.replaceAll("");
System.out.println(out);


Using Jakarta ORO
String body = "\n";
String out;
Perl5Util util = new Perl5Util();
out = util.substitute("s/ class=\".*?\"//g", body);
System.out.println(out);

Tuesday, October 10, 2006

Gilbert O'Sullivan

I love the songs of Gilbert O'Sullivan. This is the ones that I like.

Clair


Clair, the moment I met you I swear
I felt as if something somewhere
Had happened to me
Which I couldn't see

And then
The moment I met you again
I knew in my heart we were friends
It had to be so
It couldn't be no

But try as hard as I might do I don't know why
You get to me in a way I can't describe
Words mean so little when you look up and smile
I don't care what people say,
To me you're more than a child
Oh! Clair, Clair

Clair, if ever a moment so rare
Was captured for all to compare
That moment is you
It's all that you do

But why in spite of our age difference do I cry
Each time I leave you I feel I could die
Nothing means more to me than hearing you say
I'm going to marry you
Will you marry me Uncle Ray?
Oh! Clair, Clair

Clair, I've told you before
Don't you dare
Get back into bed
Can't you see that it's late
No you can't have a drink
Oh! all right then but wait just a bit
While I, in an effort to baby sit,
Catch of my breath what there is left of it.
You can be murder at this hour of the day
But in the morning this hour
Will seem a lifetime away
Oh! Clair, Clair



Alone Again


In a little while from now,
If I'm not feeling any less sour
I promised myself to treat myself
And visit a nearby tower,
And climbing to the top,
Will throw myself off
In an effort to make it clear to who
Ever what it's like when your shattered
Left standing in the lurch, at a church
Where people 're saying,
"My God that's tough, she stood him up!
No point in us remaining.
May as well go home."
As I did on my own,
Alone again, naturally

To think that only yesterday,
I was cheerful, bright and gay,
Looking forward to, but who wouldn't do,
The role I was about to play
But as if to knock me down,
Reality came around
And without so much as a mere touch,
Cut me into little pieces
Leaving me to doubt,
All about God and His mercy
For if He really does exist
Why did He desert me
In my hour of need?
I truly am indeed,
Alone again, naturally

It seems to me that
There are more hearts
Broken in the world
That can't be mended
Left unattended
What do we do? What do we do?

(instrumental break)

Now looking back over the years,
And what ever else that appears
I remember I cried when my father died
Never wishing to have cried the tears
And at sixty-five years old,
My mother, God rest her soul,
Couldn't understand, why the only man
She had ever loved had been taken
Leaving her to start with a heart
So badly broken
Despite encouragement from me
No words were ever spoken
And when she passed away
I cried and cried all day
Alone again, naturally
Alone again, naturally

Wednesday, October 04, 2006

Hot water supply

 

Finally we got the repair of the boiler at house. For the last 7days we had no hot water supply at house because of the boiler breakdown. We could enjoy the bath tonight. 

Tuesday, October 03, 2006

Class JarInflater

This is the general method to read the image data from jar file.
In DoJa programming, there is a size limitation. In order to reduce the main program file size, at the initial launch of the application, we download the resource file. Then jar file would be better in terms of the usage of the network resource especially for mobile phones.


public static Image loadJarImage(int pos,String name){
DataInputStream in = null;
JarInflater ji = null;
MediaImage mi = null;
Image img = null;
byte[] b = null;
try{
//Read the data from sp
in = Connector.openDataInputStream("scratchpad:///0;pos=" + pos);
b = new byte[(int)ji.getSize(name)];
in.readFully( b );
ji = new JarInflater(b);

mi = MediaManager.getImage(ji.getInputStream(name));
mi.use();
img = mi.getImage();
ji.close();
in.close();
}catch (Exception ex){
Util.showErr(ex);
}
return img;
}

Saturday, September 30, 2006

Already 2nd half!!

 

Recently my daughter asks me every morning like "Where do we go?" when she is about to leave the house for the kindergarten. I answer "Kindergarten" and she says "Disssnneeland". Then I think about what she said. Ah-humm "Disneyland!".

After several days, I'm forced to make a plan to take them to Disneyland. Now I'm looking for the nice hotel around there in France.

Wednesday, September 27, 2006

At Command for PDP Context

If there is no hotspot around while you are out, it's good to use your mobile as modem to connect to internet via your note PC.

Define PDP Context +CGDCONT
  1. at+CGDCONT= < cid > , <PDP_type>, <APN>, <PDP_addr> ,<d_comp>,<h_comp>

  2. <precedence> a numeric parameter which specifies the precedence class
    <delay> a numeric parameter which specifies the delay class
    <reliability> a numeric parameter which specifies the reliability class. Only values 3, 4 and 5 are currently supported.
    <peak> a numeric parameter which specifies the peak throughput class
    <mean> a numeric parameter which specifies the mean throughput class

  3. at+CGQREQ?

  4. +CGQREQ: <cid>, <precedence>,<delay>, <reliability>, <peak>, <mean>

  5. +CGQREQ=?

  6. +CGQREQ: <PDP_type>, (list of supported <precedence>s), (list of supported <delay>s), (list of supported <reliability>s) , (list of supported <peak>s), (list of supported <mean>s)

      For more info: http://www.phonestar.com.my/s_at_10.html

[RFC 2616] Transfer Codings

Trouble maker transfer coding:chunked ! Just for ref, putting RFC.

3.6 Transfer Codings

Transfer-coding values are used to indicate an encoding transformation that has been, can be, or may need to be applied to an entity-body in order to ensure "safe transport" through the network. This differs from a content coding in that the transfer-coding is a property of the message, not of the original entity.

transfer-coding = "chunked" | transfer-extension
transfer-extension = token *( ";" parameter )

Parameters are in the form of attribute/value pairs.

parameter = attribute "=" value
attribute = token
value = token | quoted-string

All transfer-coding values are case-insensitive. HTTP/1.1 uses transfer-coding values in the TE header field (section 14.39) and in the Transfer-Encoding header field (section 14.41).

Whenever a transfer-coding is applied to a message-body, the set of transfer-codings MUST include "chunked", unless the message is terminated by closing the connection. When the "chunked" transfer- coding is used, it MUST be the last transfer-coding applied to the message-body. The "chunked" transfer-coding MUST NOT be applied more than once to a message-body. These rules allow the recipient to determine the transfer-length of the message (section 4.4).

Transfer-codings are analogous to the Content-Transfer-Encoding values of MIME [7], which were designed to enable safe transport of binary data over a 7-bit transport service. However, safe transport has a different focus for an 8bit-clean transfer protocol. In HTTP, the only unsafe characteristic of message-bodies is the difficulty in determining the exact body length (section 7.2.2), or the desire to encrypt data over a shared transport.

The Internet Assigned Numbers Authority (IANA) acts as a registry for transfer-coding value tokens. Initially, the registry contains the following tokens: "chunked" (section 3.6.1), "identity" (section 3.6.2), "gzip" (section 3.5), "compress" (section 3.5), and "deflate" (section 3.5).

New transfer-coding value tokens SHOULD be registered in the same way as new content-coding value tokens (section 3.5).

A server which receives an entity-body with a transfer-coding it does not understand SHOULD return 501 (Unimplemented), and close the connection. A server MUST NOT send transfer-codings to an HTTP/1.0 client.

3.6.1 Chunked Transfer Coding


The chunked encoding modifies the body of a message in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer containing entity-header fields. This allows dynamically produced content to be transferred along with the information necessary for the recipient to verify that it has received the full message.

Chunked-Body = *chunk
last-chunk
trailer
CRLF

chunk = chunk-size [ chunk-extension ] CRLF
chunk-data CRLF
chunk-size = 1*HEX
last-chunk = 1*("0") [ chunk-extension ] CRLF

chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
chunk-ext-name = token
chunk-ext-val = token | quoted-string
chunk-data = chunk-size(OCTET)
trailer = *(entity-header CRLF)

The chunk-size field is a string of hex digits indicating the size of the chunk. The chunked encoding is ended by any chunk whose size is zero, followed by the trailer, which is terminated by an empty line.

The trailer allows the sender to include additional HTTP header fields at the end of the message. The Trailer header field can be used to indicate which header fields are included in a trailer (see section 14.40).

A server using chunked transfer-coding in a response MUST NOT use the trailer for any header fields unless at least one of the following is true:

a)the request included a TE header field that indicates "trailers" is acceptable in the transfer-coding of the response, as described in section 14.39; or,

b)the server is the origin server for the response, the trailer fields consist entirely of optional metadata, and the recipient could use the message (in a manner acceptable to the origin server) without receiving this metadata. In other words, the origin server is willing to accept the possibility that the trailer fields might be silently discarded along the path to the client.

This requirement prevents an interoperability failure when the message is being received by an HTTP/1.1 (or later) proxy and forwarded to an HTTP/1.0 recipient. It avoids a situation where compliance with the protocol would have necessitated a possibly infinite buffer on the proxy.

An example process for decoding a Chunked-Body is presented in appendix 19.4.6.

All HTTP/1.1 applications MUST be able to receive and decode the "chunked" transfer-coding, and MUST ignore chunk-extension extensions they do not understand.

Tuesday, September 26, 2006

Quick Sort in Java

I developed small application and used sort algorythm. Here is the good performance quick sort Java sample.


public static DTO[] sort(DTO _dto[],int left,int right){
//Quick Sort
int key;
if(left<right){
key = _dto[(left+right)/2].getDateValue();
int i=left -1;
int j=right +1;
while(true){
while(_dto[++i].getDateValue() while(_dto[--j].getDateValue()>key);
if(i>=j)break;
DTO t = _dto[i];
_dto[i]=_dto[j];
_dto[j] =t;

}
sort(_dto, left, i-1);
sort(_dto, j+1, right);
}


/*Bubble Sort
for(int i=0;i<_dto.length-1;i++){
for(int j=_dto.length-1;j>i;j--){
if(_dto[j].getDateValue()>_dto[j-1].getDateValue()){
DietDTO t=_dto[j];
_dto[j]=_dto[j-1];
_dto[j-1]=t;
}

}

}
*/

return _dto;
}

Tuesday, September 12, 2006

int <=> byte[]

In some occation such as the low level processing in the Java programming, you might need to convert the "int" data into "byte array" and the opposite case as well.

Here is the sample code ( in my case for CLDC1.0 or 1.1 programming).

Converting the int data type into byte array.

/**
* In order to conver the int data type into byte array
* @param value the int value you want to convert
* @return byte array data
*/
public static byte[] getIntBytes(int value) {
byte[] b = new byte[4];
b[0] = (byte) ((value >>> 24) & 0x000000FF);
b[1] = (byte) ((value >>> 16) & 0x000000FF);
b[2] = (byte) ((value >>> 8) & 0x000000FF);
b[3] = (byte) (value & 0x000000FF);
return b;
}


Converting the byte array into int data type

/**
* In order to convert the byte array into int data type
* @param value the byte array you want to convert
* @return int data
*/
public static int getInt(byte value[]) {
int ret = 0;
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(value);
ret = new DataInputStream(bais).readInt();
bais.close();
bais = null;
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (bais != null) {

try {
bais.close();
bais = null;
} catch (Throwable t) {
}
}
}
return ret;

}

Monday, September 11, 2006

Pareto chart


A Pareto chart is a special type of bar chart where the values being plotted are arranged in descending order. It is named for Vilfredo Pareto, and its use in quality assurance was popularized by Joseph M. Juran and Kaoru Ishikawa.
Simple example of a Pareto chart using hypothetical data showing the relative frequency of reasons for arriving late at work.
Enlarge
Simple example of a Pareto chart using hypothetical data showing the relative frequency of reasons for arriving late at work.

The Pareto chart is one of the seven basic tools of quality control, which include the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, flowchart, and scatter diagram. See Quality Management Glossary.

Typically the left vertical axis is frequency of occurrence, but it can alternatively represent cost or other important unit of measure. The right vertical axis is the cumulative percentage of the total number of occurrences, total cost, or total of the particular unit of measure. The purpose is to highlight the most important among a (typically large) set of factors. In quality control, the Pareto chart often represents the most common sources of defects, the highest occurring type of defect, or the most frequent reasons for customer complaints, etc.
(Reference WiKipedia)

Cause & Effect Diagrams


The cause & effect diagram is the brainchild of Kaoru Ishikawa, who pioneered quality management processes in the Kawasaki shipyards, and in the process became one of the founding fathers of modern management. The cause and effect diagram is used to explore all the potential or real causes (or inputs) that result in a single effect (or output). Causes are arranged according to their level of importance or detail, resulting in a depiction of relationships and hierarchy of events. This can help you search for root causes, identify areas where there may be problems, and compare the relative importance of different causes.

If the influence level of the factor is quantitatively Pareto chart.

Small Giant Step

This month is her first Debut for social community. Now she goes to British pre-school. So far she really enjoy the time at the kindergarten.

It's a small step but giant step for her future!!

Friday, September 08, 2006

Java :: Leap Year

Yes. I recovered all the photos of memory from the S/W crashed HD. I install picasa2 from google and look around the ones taken for 5 years.

Time flies. Here is the photo 1 year ago @ Italy where the family of my sister in law lives.

Good memories of pizza , mozzarella and flash back ;-)

These days I'm bussy @ work and not many time for the dev @ home. Also looking for the good server host to rent the space for the Ajax server side appli. Anyway I don't have nether time nor money ;-( Need to wait for the next month...

The formula of calculating the leap year is very simple but easy to forget. Just for a note.

/**
* This is the method to check the leap year
* @param year the year you want to check if the leap year
* @return true:leap year false: not the leap year
*/
public static boolean isLeapYear(int year){
boolean result = false;
if ((year % 4 == 0 && year % 100 != 0) (year % 400 == 0)) {
result = true;
}
return result;
}

Tuesday, September 05, 2006

Vacation @ Poland

Just before the vacation to Poland, my GNU/Linux PC @ Home crashed because of the mis-configuration of some xorg etc... I bought Acronis Disk Director Suite to recover some of the data stored in the HD. The application was on promotion (25 euro) and very well that I could recover the data of photos for 6 years. ( My wife would kill me if I couldn't get it back ;-0) I immediately made the buckup to DVD which I bought a month ago. Now I know how important it is to make a backup regularlly.

The vacation was so busy that we couldn't really relax at all. Everyday meeting the relatives and friends of my wife. But kids seems to be very happy that the sister in law and her bf played with them a lot. There we did a lot of shopping as well. We spent the amount of 2 month salary.

This is the snapshot @ hotel in Berlin on our way back home.

Monday, August 21, 2006

Summer vacation

Our summer vacation is comming soon and I spent a whole weekend to find accomodations as we make our travel plan by ourselves for this time. How easy to use travel agency to find a vacation plan... Still I need to make reservation 2 nights in Germany & Poland.

By the way, I somehow find the way to customize blogger and google map. I put some functions to this blog to see if everything is all right. How cool that blogger can customize the design of the blog. Free (as a free speach) is good that I can enjoy ;-) Finally I could put a bit of Ajax taste in my blog with the big help of google ;-)

BTW, the kernel 2.6.17.9 is released on 18th Aug. Aren't they on vacation ?

Thursday, August 17, 2006

Vim setting for .vimrc

Vim is the very powerful text editor for GNU/Linux. Here is the sample of the .vimrc which confortably set up your vim.
" .vimrc
" Clear any existing autocommands:
autocmd!

" *** User Interface
" use indents of 4 spaces, and have them copied down lines:
set shiftwidth=4
set tabstop=4
set shiftround
set expandtab
set autoindent

" Set for visible tab
"set listchars=tab:>-,extends:<,trail:-,eol:<
set listchars=tab:>-
set list

" The format of status line
set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P

" No beep
" set vb t_vb=
set visualbell

" No auto NL
set formatoptions=q

" Show line number
set number

" have syntax highlighting in terminals which can display colours:
if has('syntax') &amp;amp;amp;amp;& (&t_Co > 2)
syntax on
endif

" have fifty lines of command-line (etc) history:
set history=50

" display the current mode and partially-typed commands in the status line:
set showmode
set showcmd

" have the mouse enabled all the time:
set mouse=a

" don't have files trying to override this .vimrc:
set nomodeline

" Set the type of background color
set background=dark

" *** Text Formatting -- Specific File Formats
" enable filetype detection:
filetype on

" for C-like programming, have automatic indentation:
autocmd FileType c,cpp,slang set cindent

" for actual Java C (not C++) programming where comments have explicit end
" characters, if starting a new line in the middle of a comment automatically
" insert the comment leader characters:
autocmd FileType c,java set formatoptions+=ro smartindent noexpandtab tabstop=4

" for Perl programming, have things in braces indenting themselves:
autocmd FileType perl set smartindent

" for CSS, also have things in braces indented:
autocmd FileType css set smartindent

" for HTML, generally format text, but if a long line has been created leave it
" alone when editing:
autocmd FileType html set formatoptions+=tl

" for both CSS and HTML, use genuine tab characters for indentation, to make
" files a few bytes smaller:
autocmd FileType html,css set noexpandtab tabstop=4

" in makefiles, don't expand tabs to spaces, since actual tab characters are
" needed, and have indentation at 4 chars to be sure that all indents are tabs
" (despite the mappings later):
autocmd FileType make set noexpandtab shiftwidth=4

" *** Search & Replace
" make searches case-insensitive, unless they contain upper-case letters:
set ignorecase
set smartcase
set hlsearch

" show the `best match so far' as search strings are typed:
set incsearch

Wednesday, August 16, 2006

Shell Backup Script

Here is the shell script for backup of the server contents to another over scp.
#!/bin/sh
#################################################################
# Script for the backup the contents under the specified folder
# and the all mysql data
#
# -Cavalierski
#################################################################
# The Following setting should be modified for the each environment
##################################################################
#Date format of the back up file. This will be the prefix of the file
DATE_FORMAT=$(date +'%Y%m%d')

#Specify the folder that you want to backup
TARGET_DIR=(/var/www/xxx /home/xxx/test)

#Set the backup file name
BACKUP_LOGFILE=${DATE_FORMAT}.log
BACKUP_SQLFILE=${DATE_FORMAT}.sql.gz

#Setting for MySQL
MYSQL_PASSWD=

#Setting for Backup server over scp
SCPURL=www.loveanna.net:backup
SCPUSER=xxx

# Do not edit the below lines
##################################################################
# Temporary backup file
BACKUP_DIR=/tmp/www
function make_backup(){
for f in "$@"
do
if [ -d "$f" ]
then
tar zcvf ${BACKUP_DIR}/${DATE_FORMAT}_${f##/*/}.tar.gz "$f"/* >>
${BACKUP_DIR}/${BACKUP_LOGFILE}
else
echo "[ERROR] $f doesn't exist" >> ${BACKUP_DIR}/${BACKUP_LOGFILE}
fi
done

#The Answer to Life, the Universe, and Everything
return 42;
}

mkdir -p $BACKUP_DIR
make_backup ${TARGET_DIR[*]}
mysqldump -uroot --password=$MYSQL_PASSWD --all-databases | gzip>
$BACKUP_DIR/$BACKUP_SQLFILE

if [ $? -ne 0 ]
then
echo "[ERROR] sqldump failed" > ${BACKUP_DIR}/${BACKUP_LOGFILE}
fi

BKFILES=$(ls $BACKUP_DIR/${DATE_FORMAT}*)
BKNUM=${#BKFILES[@]}

for ((i=0;i<BKNUM;i++)); do
scp ${BKFILES[i]} ${SCPUSER}@${SCPURL}
rm -R ${BKFILES[i]:-${BACKUP_DIR}/*}
done

Useful Eclipse Plug-ins

Here are the list that I use for Eclipse on Ubuntu.
The link to the plug-ins for Eclipse

Wednesday, August 09, 2006

Firefox flash sound problem

The following steps are the solution on the problem of firefox flash sound problem.
# Flash also looks for /usr/lib/libesd.so.1
sudo ln -s /usr/lib/libesd.so.0 /usr/lib/libesd.so.1

# Flash expects /tmp/.esd/socket to exist.
sudo mkdir -p /tmp/.esd/
sudo touch /tmp/.esd/socket

Tuesday, August 08, 2006

Install log script for linux

Sometimes you need to install the program from the source as it is stable etc. However without the package management , it is difficult to find where the program files are deployed.

The following commands will tell you where the new files are created. Now that you can remove the programm following the diff output. The following each line is in one line.

%sudo find / | grep -v -e ^/proc/ -e ^/dev/ -e ^/media/ -e ^/tmp/ -e ^/mnt/ >beforeinstall.list

% sudo find / | grep -v -e ^/proc/ -e ^/dev/ -e ^/media/ -e ^/tmp/ -e ^/mnt/ >afterinstall.list

% diff beforeinstall.list afterinstall.list

Mastering dpkg

Debian GNU/Linux package manager is very cozy tool to manage applications on your system.
Here are the tips of useful commands of "dpkg".

// Search the package
$dpkg -l 'firefox*'
//Search installed package
$dpkg -l | grep firerox
//List up the files install by the package
$dpkg -L firefox
//Search the package from the specific file
$dpkg -S mozilla-firefox.png
//Aquire the complete information of the package
$dpkg -s firefox
Those commands are often needed but often forgotten...

Wednesday, July 05, 2006

Blog is Up

OK, now it's open.

So far I use Ubuntu Dapper as a desktop OS at home & work and Eclipse as an IDE. At work, I use J2ME and at home I use J2SE / J2EE for my hobby.

Recently I've been enjoying the re-config of my Ubuntu but I'm getting in the mood of programming now. I just become a member of SorceForge so I'm looking for the project that I can help.

With 3 ladies (2 cute daughters & 1 wife) , it is difficult to find time for my hobby. After 23:00-2:00 for 3 hours a day is the precious time for me. Still it's much less than I need.

Anyway, in this blog, I'll put notes or tips that I learned. Hope you could find them useful.