Friday, December 31, 2010

Android's Process != Application ???

Still trying to understand the statements ... "Internally, each user interface screen is represented by an Activity class. Each activity has its own life cycle. An application is one or more activities plus a Linux process to contain them.
In Android, an application can be “alive” even if its process has been killed. Put another way, the activity life cycle is not tied to the process life cycle. Processes are just disposable containers for activities." (Hello Android 3rd edition p.35)

Tuesday, December 21, 2010

How to take care of your leather seats ?

Use hair dryer to remove wrinkles from leather seat.
1. Wipe down the leather seat with mild soap and water or a specifically formulated leather cleaner. Use the cloth to rinse and dry the leather seat so that no soap or cleaner residue remains on the surface of the leather.

2. Inspect the leather seats and find all the places that have wrinkles.

3. Turn on the hair blow dryer to its hottest, strongest setting.

4. Position the end of the dryer eight to 10 inches away from the wrinkled leather surface. Move the end back and forth so that the hot air from the dryer is not hitting a single portion of the leather for too long. This prevents the dryer from burning the leather.

5. Wait for the wrinkles to disappear. The heat from the hot air in the dryer will gradually shrink the leather, tightening its surface and effectively removing the wrinkles. Hair blow dryers operate at a lower temperature than the professional heat guns that are typically used to remove leather wrinkles. As a result, it might be several minutes before the wrinkles are completely gone.

6. Apply a light coat of premium leather conditioner and work it into the surface of the leather. This helps to protect the leather from the environment, and it might prevent or minimize future wrinkles. Buff lightly with a cloth. A high-quality leather conditioner might cost slightly more than some other brands, but it has less wax and can extend the life of your leather. Popular leather conditioners include Mothers Leather Conditioner and Meguiar's Gold Class Rich Leather Cleaner and Conditioner. Such products may be purchased at your local automotive store or online.

How to generate a thread dump ?

Generating a Thread Dump
Windows
The Java application that you want to produce a thread dump for must be running / started in a command console. When you want to produce a thread dump press Ctrl-Break
Note: it's easier to produce a thread dump on Linux as the JVM doesn't need to be started in a console window.
Linux
If the JVM is running in a console then simply press Ctrl-\.
If the JVM is running in the background then send it the QUIT signal:kill -QUIT process_id

Note: the thread dump will show on the console where the to-be-kill process is running on, not the console where you issue the kill command.

Thursday, December 9, 2010

Using yum to install packages locally

# yum localinstall /media/disk/Fedora/Packages/gftp-*
(If DVD is mounted on /media/disk)

Linux tips

> ls -l | grep -v total | awk '{ S+=$5} END { print "Total = ",S, ", Average = ", S/NR, ", Entries = ", NR, ", Columnss = ", NF}'
Total = 70238 , Average = 4389.88 , Entries = 16 , Columnss = 9
================================================================
> x=2008
> y=1957
> echo "$[$x - $y]"
51
> echo "$(($x - $y))"
51

================================================================
> gunzip < /usr/share/man/man8/vgrename.8.gz | nroff -man less

================================================================
> for i in `find /usr/home -name '*.jar'`
> do
> jar tvf $i | grep Something 2>/dev/null
> if [ $? -eq 0 ]; then
> echo $i
> fi
> done

================================================================
> groovy -e "System.env.each { println it }"
> groovy -e "System.props.each { println it }"

How to find the locking order for equals() ?

Always lock them in the same order, one way you could decide the order is on the results of System.identityHashCode(Object)

References:
http://stackoverflow.com/questions/1636399/correctly-synchronizing-equals-in-java
http://download.oracle.com/javase/tutorial/essential/concurrency/atomic.html


Never abruptly exit a finally block

Every finally block should complete normally, barring an unchecked exception.
Never exit a finally block with a return, break, continue, or throw, and never allow a checked exception to propagate our of a finally block.
When both try block and the finally block complete abruptly, the reason for the abrupt completion in the try block is discarded. Discarding the reason for abrupt completion is almost never what you want ... (Java Puzzlers p.78)


References:
http://accu.org/index.php/journals/236 (handle checked exception in finally block)
http://www.javamex.com/tutorials/exceptions/exceptions_finally.shtml
http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml

Wednesday, December 8, 2010

Install VLC on CentOS

If you are not able to install VLC through command "yum install vlc" then most likely you have to enable the RPMForge repository by following the instructions provided by the link here

p.s. RPMforge is a collaboration of Dag and other packagers. They provide over 5000 packages for CentOS, including wine, vlc, mplayer, xmms-mp3, and other popular media tools. It is not part of Red Hat or CentOS but is designed to work with those distributions.

Java volatile vs. synchronized

If volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory.

volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

volatile:
- Get a global lock on the variable
- Update the one variable from main memory
- Write any change of the one variable back to main memory
- Release the lock

synchronized:
- Get a global lock on the monitor
- Update all shared variables that have been accessed from main memory
- Process some statements
- Write all shared variables that have been changed back to main memory
- Release the lock


reference: http://www.javaperformancetuning.com/news/qotm051.shtml

Saturday, December 4, 2010

How to record/replay X events

Download xnee 2.05
> cnee --record --mouse --keyboard --out-file mouse-keyboard-events.xnl
> cnee --replay --file mouse-keyboard-events.xnl

Run shell script through keybinding

Press Ctrl+Alt+Insert to start an Xterm running the 'top' command, and press Ctrl+Alt+Delete to kill it:
gconftool-2 -t str --set /desktop/gnome/keybindings/custom1/name "Start top command"
gconftool-2 -t str --set /desktop/gnome/keybindings/custom1/binding "Insert"
gconftool-2 -t str --set /desktop/gnome/keybindings/custom1/action "xterm -e /usr/bin/top"

gconftool-2 -t str --set /desktop/gnome/keybindings/custom2/name "Stop top command"
gconftool-2 -t str --set /desktop/gnome/keybindings/custom2/binding "Delete"
gconftool-2 -t str --set /desktop/gnome/keybindings/custom2/action "xterm -e kill -9 $(ps aux grep top grep -v grep)"

Thursday, November 18, 2010

Java / Ektorp / CouchDB

Ektorp is a persistence API that uses CouchDB as storage engine. The goal of Ektorp is to combine JPA like functionality with the simplicity and flexibility that CouchDB provides ... more ...

Below is an example that I used to access my CouchDB and I ran the command curl --user user:password -X PUT http://my.couchone.com:5984/testdb/ektorp -d '{ "color": "red" }' first to create a document 'ektorp' before executing Java code.


import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.support.CouchDbDocument;

public class Ektorp {
public static void main(String[] args) {
HttpClient httpClient = new StdHttpClient.Builder()
.host("my.couchone.com")
.port(5984)
.username("user")
.password("password")
.build();

CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
CouchDbConnector db = new StdCouchDbConnector("testdb", dbInstance);

db.createDatabaseIfNotExists();
Sofa sofa = db.get(Sofa.class, "ektorp");

if (sofa.getColor().equals("red")) {
sofa.setColor("green");
} else {
sofa.setColor("red");
}
db.update(sofa);
}
}

class Sofa extends CouchDbDocument {
private String color;
public void setColor(String s) {
color = s;
}

public String getColor() {
return color;
}
}

More examples here ...

Wednesday, November 17, 2010

Groovy / REST / CouchDB

The codes below from REST up with CouchDB and Groovy's RESTClient was modified to use login authentication based on this link ...

import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON

@Grab(group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '[0.5.0,0.5.1)')
def getRESTClient(local = false) {
RESTClient client;

if (!local) {
client = new RESTClient("http://my.couchone.com:5498/")
} else {
client = new RESTClient("http://my.couchone.com:5984/")
}

def authHash = "user:password".getBytes('iso-8859-1').encodeBase64()
client.headers.Authorization = "Basic $authHash"

return client;
}

def client = getRESTClient(true)

try {
client.get(path: "parking_tickets")
println "Deleting DB parking_tickets ..."
client.delete(path: "parking_tickets")
} catch (Exception e) {
println "Creating new DB parking_tickets ..."
}

def response = client.put(path: "parking_tickets", requestContentType: JSON, contentType: JSON)

assert response.data.ok : "response from server wasn't ok"

Note: Grab will download required jars to C:\Users\userName\.groovy\grapes\org.codehaus.groovy.modules.http-builder

Thursday, November 11, 2010

My free CouchDB account (faked)

I don't have time to learn how to make good use of it yet so I temporarily put it here to remind me its existence ...

http://my.couchone.com/_utils/


Useful commands:
> curl -x myproxy:80 -X GET http://my.couchone.com/_all_dbs
> curl -u user:password -x myproxy:80 -X PUT http://my.couchone.com/testdb
> curl -u user:password -x myproxy:80 -X GET http://my.couchone.com/_all_dbs
["testdb","mybooks","_users","test_suite_db/with_slashes"]

Monday, November 1, 2010

How to burn a DVD on Linux

Just in case I couldn't remember how to do it ...

> mkisofs -r -o MyDVD.iso /home/david/Folder_to_Burn_to_DVD

> growisofs -dvd-compat -Z /dev/dvdrw=MyDVDS.iso -speed=2

- or do the following without creating an ISO file -

> growisofs -Z /dev/cdrom -R -J /home/david/Folder_to_Burn_to_DVD

Saturday, October 9, 2010

Swiz Framework

I like the way how Christophe Coenraets describes the Swiz Framework below:
At his core, Swiz is a simple inversion of control framework (IoC). Using an IoC framework, the components of your application (for example, Views) don't instantiate or even look up their dependencies (the objects they work with). The framework injects those dependencies when the components are created (hence the term "Dependency Injection" also used to describe this approach). The result is looser coupling and more reusable components. The components managed by the Swiz IoC framework are called beans.
Swiz uses the [Autowire] custom metadata to inject beans into other beans and views.

Disabled JSplitPane causes the resize cursor not working in JTable

I just found that whenever I disable a JSplitPane with setEnabled(false) then all the JTable in the pane will stop showing the resize cursor on the table header even though they are still resizable. So if you have to disable JSplitPane (make it not resizable) but still want the JTable in it be resizable then you need to provide your own resizer as below and apply it to your JTable this way new TableHeaderCursorResizer(jTable);



Wednesday, August 4, 2010

My love is the place where I came from - Taiwan

A wonderful series of introduction to Taiwan. It has five parts and each part contains three or four segments. You have to wait for a few seconds of black-out between the segments.

http://cbs5.com/video/?id=65565@kpix.dayport.com Taiwan Part 1
http://cbs5.com/video/?id=65564@kpix.dayport.com Taiwan Part 2
http://cbs5.com/video/?id=65566@kpix.dayport.com Taiwan Part 3
http://cbs5.com/video/?id=65569@kpix.dayport.com Taiwan Part 4
http://cbs5.com/video/?id=65572@kpix.dayport.com Taiwan Part 5

Sunday, July 25, 2010

Ubuntu 10.04 uses OpenJDK by default

Ubuntu recommends to use OpenJDK instead of the Oracle JDK, but you still can configure your system to use Oracle JDK by adding the repository indicates in the link below:
http://www.dzone.com/links/r/java_missing_on_ubuntu_no.html

Monday, June 14, 2010

Be aware of Java 1.6 upgrade

After I upgraded to Java 1.6 through Mac OS X Software ... I found I totally lost my previous Java 1.5 setting since all the older JDK versions are being soft-linked to the Current(1.6) but luckily this blog below helped me get back what I used to have.

The link is also very useful and easier:


Sunday, April 18, 2010

64-bit Eclipse ?


64-bit Eclipse(left screenshot) on Mac OSX is still a No-Go for me, it's very CPU hogging and can't be used as an efficient development tool ... 153.2% of CPU usage for rebuilding a project seems too high for me but 32-bit Eclipse (right screenshot) scored 126.6% is not conceivable too.

I may have missed something, but should I test 64-bit Eclipse with 64-bit kernel to get a better performance number ? unfortunately Apple will not support 64 EFI for my aged MacPro 1.1 ... :( should have done my homework before I bought this 4-year-old MacPro ... well, smart people sometimes make stupid mistakes let alone a regular person like me ...

Wednesday, April 7, 2010

Symbolic link on Windows

For a long time Linux/Unix user I sometimes complain that Windows is not so cool as Linux because it lacks symbolic link, but not anymore now ... symlinker can do the job for you on Windows Vista and 7.




Saturday, April 3, 2010

Record high surfing speed

Can't believe my eyes but my Internet download speed is now 30.14Mbps ...




Monday, March 29, 2010

How to setup JDK on Snow Leopard

Here is how I did it ...

1. Modify /etc/profile by adding two entries as below
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
export PATH=$JAVA_HOME/bin:$PATH

2. run setJDK to change JDK version
3. source /etc/profile

Thursday, February 25, 2010

The Bloom box - green energy



My sixth sense tells me that this company is ready for prime time ... period.

Tuesday, February 23, 2010

My best budget SSD

Super Talent UltraDrive ME 128GB $308
Sequential Read Rate: 260 MB/s (max)
Sequential Write Rate: 195 MB/s (max)
NAND Flash: MLC
64MB DRAM cache
Access Time: 0.1 ms
Firmware upgradeable: Yes

OCZ Vertex Turbo 120GB SSD $365
Maximum sequential read speed up to 270 MB/s
Maximum sequential write speed up to 200 MB/s
Indilinx Barefoot controller and Samsung MLC NAND flash for maximum performance
64MB 180MHz DRAM cache for ramp up stutter-free performance
Seek Time less than 0.1 ms
Firmware upgradeable: No

NetBeans 6.9 new feature



It's nice to know that Netbeans will support OSGI in the next release (6.9), more detail can be found here ...

Monday, February 22, 2010

How to copy a file

How to copy a file

In Java 5 and 6:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
....
String orig ="file.xml";
String dest = "file.xml.bak";
InputStream in = new FileInputStream(orig);
OutputStream out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();

In Java 7:
import java.file.io;
import org.apache.commons.io.FileUtils;
....
String orig ="file.xml";
String dest = "file.xml.bak";
File fOrig = new File(orig);
File fDest = new File(dest);
FileUtils.copyFile(fOrig, fDest);

In Groovy:
new File("/tmp/otherFile") << new File("/tmp/someFile").text
( new AntBuilder ( ) ).copy ( file : 'blah' , tofile : 'fobar' )

Reference

Sunday, February 21, 2010

Groovy tips

How to use 'split' on each line of a file:
new File("simple.tab").withReader{r->
line = r.readLine();
println "first line: $line"
r.splitEachLine("\t"){fields->
println "fields on line: $fields"
}
}

linefeed = "\n" //or "\r\n" if the user chose so
lines = new File('pathtofile').text.split("${linefeed}")

Tuesday, February 16, 2010

Test how to upload an image ..

It's fun to do image ... :-)

Sunday, February 14, 2010

Another way to make good use of your webcam

Just bookmarked this link for future experiment.

Highlight cam is a free software you can register online and start monitoring immediately and make your PC a security system and act as a silent security guard for your office, Home or any other space

Features:
* Motion alert notifications sent via Email
* Off-site backup in case the intruder takes the computer

Tagging for your blog

Finally found how I can add Tag to my blog and here is the link ... the 3D tag provided by Blogger works fine on Google Chrome and FireFox but Microsoft IE.

Code formatting test

By using this formatting tool (or this) I'm able to display code snippets properly in my blog.

<target name="build"
depends="copydata,copyresources">
<echo message="Building ${bundle_name} in ${component_name}..." />
<mkdir dir="${build_root}/build/${bundle_name}/bin" />
<mkdir dir="${build_root}/output" />
<copy todir="${build_root}/${bundle_name}/bin/">
<fileset
dir="${build_root}/build/${bundle_name}/src/">
<include name="${bundle_name}.xml" />
<include name="**/*.png" />
<include name="**/*.gif" />
</fileset>
</copy>
<antcall target="compile_with_javac" inheritrefs="true" />
<antcall target="compile_with_iajc" inheritrefs="true" />
<antcall target="renameoutput" />
</target>

Sunday, February 7, 2010

groovy++ looks cool

Groovy++ make Groovy run a lot faster by trimming dynamism and flexibility that you don't need.
And after I looked at the performance of groovy++ here I feel more confident to say that Groovy will be gaining ground fast ... sooner or later :)