Sunday, December 6, 2009

Serialize Javascript to PHP

When interacting Javascript with PHP, you might need to serialise any Javascript data type into the PHP serialized format, where it can be unserialized using PHP. The following function will serialize any Javascript data.
function serialize(mixed_value) {
    var _getType = function(inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
        return type;
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
        case "null":
        case "undefined":
            val = "N";
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
            val += ":" + count + ":{" + vals + "}";
    if (type != "object" && type != "array") {
        val += ";";
    return val;
The code fragment below will do the serializing in Javascript and the later code will unserialize it in PHP.
var array = ["ruchira", "wageesha"];
//serialize value
var serialize_array = serialize(array);
$array = unserialize($_POST['array']);

Friday, September 11, 2009

Javascript Popup - close after redirect

If you want to redirect the popup window to another location (a page or a file download) and then close the window, you can simply use the following javascript.
<script type="text/javascript">
    window.opener.location = "new_page.htm";

Sunday, August 30, 2009

Find and Replace using grep and sed

Following command finds all the occurences of <br> in all .xml files in the current directory, and replace those <br> with <br/> . Please note that < and > have been surrounded with [ and ] in the sed command. / in the <br/> tag has been escaped using \. If you want to replace foo with bar, then you can just use those words.
find . -iname "*.xml" | xargs grep -l "<br>" | xargs sed -i -e 's/[<]br[>]/<br\/>/g'
find . -iname "*.xml" | xargs grep -l "<br>" | xargs sed -i -e 's/foo/bar/g'
A more general form of the expression would be
find . \( -name "*.php" -or -name "*.html" \) | xargs grep -l 'TEXT TO SEARCH' | xargs sed -i -e 's/TEXT TO REPLACE/REPLACEMENT STRING/g'

Thursday, August 27, 2009

Rename Files with find command in linux

If you want to rename files recusivelly using linux find command, here are two example usage of it with exec and xargs. This command will convert all the *.xml files into *.html files.

Using xags
find . | xargs rename 's/\.xml$/\.html/i'
Using exec
find . -exec rename 's/\.xml$/\.html/i' {} +
Above commands recurrsively replace files within inner directories too. If you want to do it for current directory only you can use -prune.
find . -prune | xargs rename 's/\.xml$/\.html/i'
find . -prune -exec rename 's/\.xml$/\.html/i' {} +

Monday, August 10, 2009

Multiple Joins on the same table

Here are few example queries which shows how to use multiple inner joins with sql.

SELECT Fruit1, F1FruitName = F1.FruitName, F1FruitCost = F1.FruitCost,
Fruit2, F2FruitName = F2.FruitName, F2FruitCost = F2.FruitCost
JOIN T2 F1 ON Fruit1 = F1.Fruit_ID
JOIN T2 F2 ON Fruit2 = F2.Fruit_ID
If you want each fruit on it's on line(Record set), then it looks like
SELECT UserID, Fruit1 AS FruitID, FruitName, FruitCost
JOIN T2 ON Fruit1 = Fruit_ID
SELECT UserID, Fruit2 AS FruitID, FruitName, FruitCost
JOIN T2 ON Fruit2 = Fruit_ID
Here is two equivalent queries where one of them uses join and other doesn't.
SELECT codice, 
other1.value AS value_one, 
other2.value AS value_two
FROM main
LEFT OUTER JOIN other as other1 ON ( = other1.id_main AND type = 'type_one')
LEFT OUTER JOIN other as other2 ON ( = other2.id_main AND type = 'type_two)
is equivalent to
SELECT codice,
(SELECT value FROM other WHERE id_main = id AND type = 'type_one') AS value_one,
(SELECT value FROM other WHERE id_main = id AND type = 'type_two') AS value_two
FROM codice
Query below will give you a clear idea about how to use mutliple joins in the same query. Hope this will help you to understand the usage.
SELECT u1.displayname AS Player1
, u2.displayname AS Player2
, u3.displayname AS Player3
, u4.displayname AS Player4
, u5.displayname AS Player5
, u6.displayname AS Player6
DCMLeagues AS L
JOIN Users AS u1 
ON u1.userid = L.player1
JOIN Users AS u2
ON u2.userid = L.player2
JOIN Users AS u3 
ON u3.userid = L.player3
JOIN Users AS u4 
ON u4.userid = L.player4
JOIN Users AS u5 
ON u5.userid = L.player5
JOIN Users as u6 
ON u6.userid = L.player6

Thursday, June 25, 2009

find command - search content of a file

find in Unix is a very powerful tool for users which give you a very good flexibility. find command has a very broad usage among users. Here is the way how you can use find command to search files and content within files.

In order to search for a particular file named "test.txt" in /home directory, use
find /home -name "test.txt" -print
Search all the .txt files in /home directory, use
find /home -name "*.txt" -print
if you want to search for a string through all the files .txt files, there are two ways
find /home -name "*.txt" -exec grep -q "string-to-be-searched" '{}' \; -print
find /home -name "*.txt" | xargs grep "string-to-be-searched"
second one is more fast and efficient. Removal of -q in the first command will output the text segment where the specified string is. If you want to search all files for the string, just remove -name "*txt" option.

How to Increase JVM(Java) Heap Size

If you're building a big project using ant/maven then your jvm heap size may not sufficient and give you a java.lang.OutOfMemoryError: PermGen space exception. Increasing of maven/ant heap size might not sufficient enough for that and an increase of jvm heap size might also needed. When you're starting an application through command line, you can do it by specifying
java -Xms32m -Xmx128m your_application
it will be a temporary increase of heap size and if you want to increase it permanently set the following environment variable as needed.
export _JAVA_OPTIONS="-Xms64m -Xmx128m"
-Xms64m is the startup size(64MB) and -Xmx128m is the maximum size(128MB)

Monday, May 25, 2009

PNG Tranparency in IE6

1 . First Download this Zip file and unzip

2 . Copy and paste and blank.gif into your website folder.

3 . Copy and paste this into your website's CSS or HTML:
<style type="text/css">
    img, div { behavior: url( }
That CSS selector must include the tags/elements on which you want PNG support -- basically, give it a comma-separated list of tags you use. It must also include the correct path to the .HTC relative to the HTML document location (not relative to the CSS document!). For instance, yours may look like this:
<style type="text/css">
    img, div, a, input { behavior: url(/css/resources/ }
4 . If your site uses subfolders, open the .HTC file in a text editor like Windows Notepad and change the blankImg variable to include a correct path to blank.gif like so:
IEPNGFix.blankImg = '/images/blank.gif';
Again the path is relative to the HTML file. Otherwise, you will see a "broken image" graphic!

5 . If you want support for CSS1 background-repeat and background-position, make sure you include the add-on .JS file in your <head>:
<script type="text/javascript" src="iepngfix_tilebg.js"></script>
Otherwise, background images will work but won't repeat or position.

You can view two other methods at

Saturday, January 10, 2009

Add, Multiply, Divide Numbers in Fractional Format

Here is a way to do fractional calculations in Java. This might be useful when you want to get the exact values for some arithmetic operations like division. You can keep the result as a fractional number and to the operations what ever you like. i.e. add, subtract, multiply and divide.

Here are two classes named and As an example you can create the fractional number 7/8 using the constructor Fraction("8", "7"). There are many other constructors too in the Fraction class. If you want to get 10 as a fractional number, i.e. 10/1, you can use the contructor new Fraction("10").

In order to add two fractional numbers a and b, you can use Util.add(a, b) method. Likewise you can to subtraction, multiplication and division. Please refer the code, it might be useful to understand the usage.
public class Fraction {
    private Long denominator;
    private Long numerator;
    /** Creates a new instance of Fraction */
    public Fraction(String denominator, String numerator) {
        this(new Long(denominator), new Long(numerator));
    public Fraction(Long denominator, Long numerator) {
        long gcd = Util.gcd(denominator, numerator);       
        this.denominator = denominator / gcd;
        this.numerator = numerator /gcd;
    public Fraction(String number) {
        this.denominator = new Long("1");
        this.numerator = new Long(number);
    public Fraction(long number) {
        this.denominator = new Long("1");
        this.numerator = new Long(number);

    public Long getDenominator() {
        return denominator;

    public Long getNumerator() {
        return numerator;
public class Util {
    /** Creates a new instance of Util */
    public Util() {
    public static long gcd(Long a, Long b) {      
        if (b==0)
            return a;
            return gcd(b, a % b);
    public static long lcm(Long a, Long b) {
        return (a/gcd(a, b))*b;
    // (a + b)
    public static Fraction add(Fraction a, Fraction b) {
        Long denominator = lcm(a.getDenominator(), b.getDenominator());
        Long numerator = a.getNumerator()*(denominator/a.getDenominator()) +
        return new Fraction(denominator, numerator);
    // (a - b)
    public static Fraction substract(Fraction a, Fraction b) {
        Long denominator = lcm(a.getDenominator(), b.getDenominator());
        Long numerator = a.getNumerator()*(denominator/a.getDenominator()) -
        return new Fraction(denominator, numerator);
    // (a * b)
    public static Fraction multiply(Fraction a, Fraction b) {
        return new Fraction(a.getDenominator() * b.getDenominator(), a.getNumerator() * b.getNumerator());
    // (a / b)
    public static Fraction divide(Fraction a, Fraction b) {
        return new Fraction(a.getDenominator() * b.getNumerator(), a.getNumerator() * b.getDenominator());

How to find gcd and lcm in Java

Here is the easiest and efficient way to get the Greatest Common Divisor(gcd) and Least Common Multiple(lcm) in Java. This algorithm could be used for any language. Here I have used Long data type. You can use integer as needed.
public static long gcd(long a, long b) {      
    if (b==0)
        return a;
        return gcd(b, a % b);
public static long lcm(long a, long b) {
    return (a / gcd(a, b)) * b;