Search This Blog

Java 6: get localhost address reliablely

package test;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IPAddrUtil {

    public static void main(String[] args) throws Throwable {
        System.out.println(getLocalhostAddress());
    }

    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" >
            <classpath>
                <fileset dir="lib">
                    <include name="*.jar" />
                </fileset>
            </classpath>
        </javac>
    </target>

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 http://git-scm.com/download/mac
  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\ programs.sh

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/Eclipse.app/Contents/MacOS/eclipse.ini
insert the following lines before -vmargs:
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/bin/java
-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:
    <dict>
        <key>date</key>
        <date>2014-04-25T05:28:12Z</date>
        <key>displayName</key>
        <string>Chef</string>
        <key>displayVersion</key>
        <string></string>
        <key>packageIdentifiers</key>
        <array>
            <string>com.getchef.pkg.chef</string>
        </array>
        <key>processName</key>
        <string>installer</string>
    </dict>
com.getchef.pkg.chef is the bom file name in /private/var/db/receipts/com.getchef.pkg.chef.bom, run the following command:
lsbom -fls /private/var/db/receipts/com.getchef.pkg.chef.bom

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
a.;

Local variable with Sphinx

class MyClass:

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

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'
a.;

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 xml.py, 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 xml.py, rename the xml.py 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)

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

@staticmethod
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):
    print('A')
    elif isintance(arg, ClassB):
    print('B')
    elif issubclass(arg, ClassC):
    print('subclass of C')
    else:
    print("D")
  • 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"
    else:
    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:
print('empty')

Python: iterate over dictionary


for name in dict.keys():
print(name)
print(dict[name])

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
      jdk-1.7.0_51-fcs.x86_64
    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/libjavaplugin.so libjavaplugin.so.x86_64 /usr/java/latest/jre/lib/amd64/libnpjp2.so 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

#!/bin/bash

cd /tmp

# download
wget http://download.microsoft.com/download/E/6/7/E675FFFC-2A6D-4AB0-B3EB-27C9F8C8F696/PowerPointViewer.exe

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

# 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/ppviewer.cab

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 Mavericks.app
  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\ Mavericks.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Mavericks.app --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.
    Done.

澳洲搜索附近的幼儿园和学前班

头虱的清理

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

这里是澳洲卫生部门网站关于头虱的检查和清理办法。

http://www.health.vic.gov.au/headlice/