Java 6: get localhost address reliablely

package test;

import java.util.Enumeration;

public class IPAddrUtil {

    public static void main(String[] args) throws Throwable {

    public static InetAddress getLocalhostAddress() throws Throwable {
        // NOTE: prefer the LAN address over loopback address
        InetAddress addr = getLocalAreaNetworkAddress();
        if (addr == null) {
            addr = getLoopbackAddress();
        return addr;

    public static InetAddress getLocalAreaNetworkAddress() throws Throwable {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = ifaces.nextElement();
            if (!iface.isLoopback()) {
                for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address.isSiteLocalAddress()) {
                        return address;
        return null;

    public static InetAddress getLoopbackAddress() throws Throwable {
        InetAddress v4Addr = null;
        InetAddress v6Addr = null;
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = ifaces.nextElement();
            if (iface.isLoopback()) {
                for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address.isLoopbackAddress()) {
                        String hostAddress = address.getHostAddress();
                        if (hostAddress.indexOf('.') >= 0) {
                            v4Addr = address;
                        if (hostAddress.indexOf(':') >= 0) {
                            v6Addr = address;
        // NOTE: prefer v4 address over v6 address
        if (v4Addr != null) {
            return v4Addr;
        } else if (v6Addr != null) {
            return v6Addr;
        } else {
            return null;

see also

Ant in Eclipse: javac1.8 class not found

If you are running ANT in Eclipse using Java 8. The error
Class not found: javac1.8
could happen. Because Apache Ant versions less than 1.9.0 - are not compatible with Java 8. The solution could be
  • Option 1: Install Java 7 and set JAVA_HOME for eclipse to use Java 7.
  • Option 2: Add compiler or build.compiler attribute to the javac task in your ant build.xml:
    <target name="compile">
        <javac srcdir="src" destdir="build/classes" source="1.6" target="1.6" compiler="javac1.7" >
                <fileset dir="lib">
                    <include name="*.jar" />

see also

Mac OS X: convert binary .plist file to xml format

  • convert from binary to xml format:
    plutil -convert xml1 ~/.MacOSX/environment.plist
  • convert from xml to binary format:
    plutil -convert binary1 ~/.MacOSX/environment.plist

Mac OS X: install git without xcode

git is included in xcode. but if you just want git, you do not have to install the xcode. You can download and install git for mac.
  1. Download from
  2. Mount the .dmg file and install the .pkg package inside the image.
  3. After installation you need to prepend /usr/local/git/bin to /etc/paths file and remove /etc/paths.d/git:
    sudo sed -i  -e  '1s/^/\/usr\/local\/git\/bin\'$'\n/g' /etc/paths; rm /etc/paths.d/git
  4. Set PATH environment variables for non-terminal applications:
    /usr/local/git/bin/setup\ git\ PATH\ for\ non-terminal\

Mac OS X: set PATH for non-terminal applications using User Session Environment Variables in ~/.MacOSX/environment.plist

  • Read the PATH variable from ~/.MacOSX/environment.plist
    defaults read ~/.MacOSX/environment.plist PATH
  • Append to the PATH variable in ~/.MacOSX/environment.plist
    defaults write ~/.MacOSX/environment.plist PATH $(defaults read ~/.MacOSX/environment.plist PATH):/usr/local/git/bin

see also

Mac OS X: set PATH environment variable

  • To set the PATH variable for all the users, edit /etc/paths or add new file to /etc/paths.d
    Note: to prepend to the paths, you have to edit /etc/paths because it is loaded first then the entries in /etc/paths.d
  • To set the PATH variable for a user, edit $HOME/.bash_profile and enter the line,e.g.:
    export PATH=$PATH:/usr/local/git/bin
    Note: to make sure some commands override others, you may need to prepend it:
    export PATH=/usr/local/git/bin:$PATH

see also

shell script: insert line at the beginning of a text file

On linux:
sed -i -e '1s/^/Here is the first line.\n&/g' file.txt

On Mac OS, the above does NOT work. You have to use the following instead:
sed -i -e '1s/^/Here is the first line.\'$'\n/g' file.txt

see also

Eclipse on Mac OS X: set the Java runtime used by eclipse by editting eclipse.ini

Edit eclipse.ini:
vi /Applications/eclipse/
insert the following lines before -vmargs:

see also

Clean install Mac OS X Mavericks 10.9

How to Do a Clean Install of OS X Mavericks

Uninstall a application installed from a package .pkg file

If you install a application from .pkg file, it will be recorded into the /Library/Receipts/InstallHistory.plist. Open the file and search for the entry for the corresponding package, for example, I installed a package called Chef, open /Library/Receipts/InstallHistory.plist, you can find the entry:
com.getchef.pkg.chef is the bom file name in /private/var/db/receipts/, run the following command:
lsbom -fls /private/var/db/receipts/

see also

uninstall chef-client

  • On Ubuntu/Debian Linux:
    1. dpkg --list | grep chef
    2. sudo dpkg -P chef
  • On RedHat/CentOS/Fedora Linux:
    1. rpm -qa *chef*
    2. sudo yum remove <chef-packages>
  • On Mac OS X:
    1. sudo rm -fr /opt/chef
    2. sudo rm -f /usr/bin/chef-* /usr/bin/knife /usr/bin/ohai /usr/bin/shef

Python doc generator: sphinx docstring examples

Python: Code completion in pydev

Code Completion

Type hinting with docstrings/comments

New on PyDev 2.8.0

It's possible to provide hints for code-completion with docstrings by commenting types with the Sphinx/Epydoc format.
Below are some examples of how to provide type-hints.

Return type with Sphinx

class MyClass:

def method(self):
':rtype unittest.TestCase'

Parameter type with Sphinx

class MyClass:

def method(self, a):
':type a: TestCase'
#Note that just the class name is accepted, but in this case,
#it'll search for a TestCase class in the whole workspace

Parameter type with Sphinx inline

class MyClass:

def method(self, a):
':param TestCase a:'

Local variable with Sphinx

class MyClass:

def method(self, lst):
#Can be on the same line
for a in lst: #: :type a: GUITest

Local variable with Sphinx

class MyClass:

def method(self, lst):
#Or on the line before
#: :type a: GUITest
for a in lst:

Local variable with Sphinx

class MyClass:

def method(self, lst):
#If commented as a docstring must be on the
#line after
for a in lst:
': :type a: GUITest'

Return type with Epydoc

class MyClass:

def method(self):
'@rtype unittest.TestCase'

Parameter type with Epydoc

class MyClass:

def method(self, a):
'@type a: TestCase'
#Note that just the class name is accepted, but in this case,
#it'll search for a TestCase class in the whole workspace

Install Microsoft Consolas font on Mac OS X

  • Download the Open XML File Format Converter for Mac.
  • Double click the disk image if it wasn’t automatically mounted. You will see an Open XML File Format Converter meta package (.mpkg).
  • Right click (or Control-click) the meta package and choose “Show Package Contents”.
  • In the Finder window that opens, click “Contents”, then “Packages”.
  • Double click “OpenXML_all_fonts.pkg”, which will run the installer.

Python: equivalent to Java toString()

In Java, overrides toString() method in the your class can change the textual representation of the object. The equivalent in Python is __str__ and __repr__. The important differences are:
  • the goal of __repr__ is to be unambiguous
  • the goal of __str__ is to be human-readable.
  • str(object) calls the object's __str__ method
  • repr(object) calls the object's __repr__ method
  • by default, if __repr__ is defined and __str__ is not, calls to __str__ will be redirected to __repr__
  • __repr__: representation of python object usually eval will convert it back to that object
  • __str__: is whatever you think is that object in text form
  • str(list) calls the list elements' _repr_ methods. Therefore, to make a list of objects human-readable, you need to override __repr__, or use list comprehension like:
    [str(elem) for elem in list]

see also

Python: module file name conflicts with the package name

I have a python module file named, in the module

import xml.etree.ElementTree as ET
... ...
When executing the file, it raises the following error:

ImportError: No module named etree.ElementTree
According the stackoverflow post, it was caused by the moudle file name, rename the to something else resolved the issue.

Python: ElementTree XML element to string

import xml.etree.ElementTree as ET

# element is an xml.etree.ElementTree.Element object
xmlstr = ET.tostring(element, encoding='utf8', method='xml')

See also

Python: parse xml using ElementTree

  • parse from a file:
    import xml.etree.ElementTree as ET
    tree = ET.parse('/home/wilson/my.xml')
    root = tree.getroot()
  • parse from a string:
    import xml.etree.ElementTree as ET
    root = ET.fromstring('1')

see also

Python: class method vs static method

class A:
def object_m(self,x):
print "executing object_m(%s,%s)"%(self,x)

def class_m(cls,x):
print "executing class_m(%s,%s)"%(cls,x)

def static_m(x):
print "executing static_m(%s)"%x

According to stackoverflow:

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved.

Python: check argument type

  • for objects:

    def f(arg):
    if isinstance(arg, ClassA):
    elif isintance(arg, ClassB):
    elif issubclass(arg, ClassC):
    print('subclass of C')
  • for built-in types:

    def f(arg):
    if type(arg) is str:
    print "str"
    elif type(arg) is int:
    print "int"
    elif type(arg) is dict:
    print "dict"
    print "unsupported"

Python: get the sub-elements of a xml element

According to Python XML ElementTree API,
  • get all sub-elements(descendants):
    all_descendants = list(element.iter())
  • get direct sub-elements(children):
    children = list(element)

Python: check if a list is empty

if not a:

Python: iterate over dictionary

for name in dict.keys():

values = [ dict[name] for name in dict.keys() ]

Python: list comprehension

  • To transform a list to another:

    list2 = [ unicode(e.strip()) for e in list1 ]
  • To transform a list to another conditionally:

    list2 = [ unicode(e.strip()) if e is not None else '' for e in list1 ]

Install and uninstall Oracle JDK 8 on CentOS 6

  • Uninstall JDK 7:
    1. Find the installed rpm package:
      sudo rpm -qa | grep jdk | grep fcs
      it should return the package name, like
    2. Remove the package:
      sudo rpm -e -1.7.0_51-fcs
  • Install JDK 8:
    1. Download the JDK RPM package from Oracle
    2. Install the RPM package:
      sudo rpm -Uvh jdk-8u5-linux-x64.rpm
    3. Set up alternatives:
      sudo alternatives --install /usr/bin/java java /usr/java/latest/jre/bin/java 200000
      sudo alternatives --install /usr/bin/javaws javaws /usr/java/latest/jre/bin/javaws 200000
      sudo alternatives --install /usr/lib64/mozilla/plugins/ /usr/java/latest/jre/lib/amd64/ 200000
      sudo alternatives --install /usr/bin/javac javac /usr/java/latest/bin/javac 200000
      sudo alternatives --install /usr/bin/jar jar /usr/java/latest/bin/jar 200000

Install consolas font on Linux


cd /tmp

# download

# extract
cabextract -L -F PowerPointViewer.exe; cabextract -L -F "CONSOLA*.TTF"

# install
sudo mkdir /usr/share/fonts/windows

sudo cp /tmp/consola*.ttf /usr/share/fonts/windows/

cd /usr/share/fonts/windows

sudo mkfontdir

sudo mkfontscale

sudo fc-cache -fv

# clean up
rm /tmp/consola*.ttf

rm /tmp/PowerPointViewer.exe

rm /tmp/

Check if your ubuntu linux is affected by openssl heart bleed bug

The heart bleed bug affects openssl 1.0.1 built before 7 April 2014.
  • Check your openssl version and build time using the following command:
    openssl version -a
    If the version is 1.0.1 and build time is before 7 April 2014 (exclude 7 April 2014), your openssl is affected.
  • To patch your openssl, simply run the following commands to upgrade your openssl:
    sudo apt-get update
    sudo apt-get install openssl libssl1.0.0

Make a bootable USB drive for OS X Mavericks installation

  1. Download OS X Mavericks from app store. It will be installed to /Applications/Install OS X
  2. Format your USB drive(You need at least 8GB capacity.) as Mac OS Extended (Journaled). It will be labeled as Untitled by default.
  3. Run the following command in Terminal to clone Mavericks to the USB drive:
    sudo /Applications/Install\ OS\ X\ --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ --nointeraction
    It will take up to 90 minutes to complete. In the Terminal window, you should see the progress information like below:
    Erasing Disk: 0%... 10%... 20%... 100%...
    Copying installer files to disk...
    Copy complete.
    Making disk bootable...
    Copying boot files...
    Copy complete.



上周收到儿子学校的一封信,说是班里发现有孩子长头虱(head lice)。所以让所有家长检查自己孩子。


Office suite for Mac

  1. Microsoft Office 2011
  2. Apple iWork 2009
  3. LibreOffice 4.0