Thursday, September 29, 2011

Hi Mr. Everything's-a-Class, please copy other language's closure

If it's a hard pill to swallow for Mr. Everything's-a-Class to copy closure syntax from Mr. Method Pointers' language..

using System;

namespace TestCsharpClosures
{
    class Program
    {
        static void Main(string[] args)
        {
            var f = Test();
            Console.WriteLine("F: " + f());
            Console.WriteLine("F: " + f());
            Console.WriteLine("F: " + f());
            
            var g = Test();
            Console.WriteLine("G: " + g());
            Console.WriteLine("F: " + f());
            Console.WriteLine("G: " + g());
            Console.WriteLine("G: " + g());

            
        }

        public static Func<int> Test()
        {
            int a = 0;
            return new Func<int>(() => 
                {
                    return ++a;
                });

            // above line can be shortened to:
            // return new Func<int>(() => ++a);
        }
    }
}

Output:
F: 1
F: 2
F: 3
G: 1
F: 4
G: 2
G: 3


..at least Mr. Everything's-a-Class could copy closure syntax from its dumb kid brother:

<script type="text/javascript">

 var f = Test();
 WriteLine("F: " + f());
 WriteLine("F: " + f());
 WriteLine("F: " + f());
 
 
 var g = Test();
 WriteLine("G: " + g());
 WriteLine("F: " + f());
 WriteLine("G: " + g());
 WriteLine("G: " + g());

 function Test() {
  var a = 0;
  return function() {
   return ++a;
  };
 }

 function WriteLine(msg) {
  document.write('<div>' + msg + '</div>');
 } 
</script>

Output:

F: 1
F: 2
F: 3
G: 1
F: 4
G: 2
G: 3


Question of the week: What is the difference between a 'closure' and a 'lambda'?

Answer, there is none. Java don't have both of them :-)

Monday, September 12, 2011

Postgresql 9.1 is released now

Download Postgresql 9.1 now

One neat feature, we can now omit extraneous fields on GROUP BY, as long as primary key is already there


create table person
(
person_id serial not null primary key,
firstname text not null,
lastname text not null,
address text not null
);

create table visit
(
visit_id serial not null primary key,
person_id int not null references person(person_id),
url text not null
);


select
    p.person_id,
    p.firstname, p.lastname, p.address, 
    count(*)
from
    person p
    join visit v on p.person_id = v.person_id
group by p.person_id
    -- ,p.firstname, p.lastname, p.address; -- omitting other fields is now possible on 9.1


And it's still the same disciplined Postgresql
select    
    p.firstname, p.lastname, count(*)
from
    person p
    join visit v on p.person_id = v.person_id
group by p.firstname  -- this is not allowed, it's confusing which lastname to pick

Thursday, August 11, 2011

Postgresql exception-catching rocks!

Gotta love Postgres. It always yield back the control to you when an exception occur.

Given this:

create table z
(
i int not null primary key,
zzz int not null
);

Try both(one at a time) alter table z drop column aaa; and alter table z add column zzz int;, your code can detect the DDL exceptions


do $$


begin

    -- alter table z drop column aaa;
    alter table z add column zzz int;


exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                     'Transaction was rolled back';

    raise notice 'Yo this is good! --> % %', SQLERRM, SQLSTATE;
end;


$$ language 'plpgsql';

Here are the errors, both kind of errors are catchable:





Contrast that with Sql Server, try both(one at a time) alter table z drop column aaa; and
alter table z add zzz int;

begin try

    begin transaction

    -- alter table z drop column aaa;
    alter table z add zzz int;

    commit tran;

end try
begin catch 

    print 'hello';
    SELECT
        ERROR_NUMBER() as ErrorNumber,
        ERROR_MESSAGE() as ErrorMessage;

    IF (XACT_STATE()) = -1
    BEGIN
        PRINT
            N'The transaction is in an uncommittable state. ' +
            'Rolling back transaction.'
        ROLLBACK TRANSACTION;
    END;

end catch

print 'reached';

Here are the errors for SQL Server:

Catchable error:


Uncatchable error:



Sql Server won't let you catch the error on alter table z add column zzz int;

Saturday, July 30, 2011

Pad blank rows to Flexigrid

$('#nav').flexigrid({
 url: '/Person/Management/List',
 dataType: 'json',
 colModel: [
  { display: 'Username', name: 'Username', width: 150, sortable: true, align: 'left' },
  { display: 'Firstname', name: 'Firstname', width: 150, sortable: true, align: 'left' },
  { display: 'Lastname', name: 'Lastname', width: 150, sortable: true, align: 'left' },
  { display: 'Favorite#', name: 'FavoriteNumber', width: 150, sortable: true, align: 'left' }
 ],
 buttons: [
  { name: 'Add', bclass: 'add', onpress: add },
  { separator: true },
  { name: 'Edit', bclass: 'edit', onpress: edit },
  { separator: true },
  { name: 'Delete', bclass: 'delete', onpress: del }
 ],
 singleSelect: true,
 sortname: 'Lastname',
 sortorder: 'asc',
 usepager: true,
 title: 'Persons',
 useRp: true,
 rp: 5, 
 rpOptions: [5, 10, 15, 20, 25, 40],
 showTableToggleBtn: true,
 width: 560,
 height: 'auto',
 preProcess: function (data) {                

    var rp = getFgRowsPerPage($('#nav'));
    for (i = data.rows.length; i < rp; ++i) {
        data.rows.push({ 'id': '', 'cell': ['', '', '', ''] });
    }
    return data;
 }
});

function getFgRowsPerPage(tbl) {
    return $('select[name=rp] option:selected', tbl.closest('.flexigrid')).val();
}


Sample output(the last two rows are from the for loop):

Resize Flexigrid's Height

/*
Flexigrid's height is for table's tbody only, it does not include the chrome's (grid's navigation panel, title bar, etc) height. So if you pass 250 to flexigrid's height parameter, and you pass the same 250 to resizeFgHeight, it will actually make the flexigrid smaller.
*/
function resizeFgHeight(tbl, newHeight) {
    grd = tbl.closest('.flexigrid');
    var heightWithChromes = grd.height();
    
    var contentHeight = $('.bDiv', grd).height();
    var chromesHeight = heightWithChromes - contentHeight;    

    $('.bDiv', grd).height(newHeight - chromesHeight);
    grd.css('height', newHeight);
}

// This height is the same as flexigrid's height parameter. 
// Flexigrid's height parameter describes the the tbody's height of the table only,
// it does not include the chromes' heights
function resizeFgContentHeight(tbl, newHeight) {
    grd = tbl.closest('.flexigrid');
    $('.bDiv', grd).height(newHeight);
}

To use
<table id="nav"></table>

$(function() {
   $('#adjust').click(function() { 
      resizeFgHeight($('#nav'), 480);
   });
});

Thursday, July 28, 2011

Postgresql unnest function can do many wonders

I saw an interesting Postgres question on Stackoverflow

How to know if all the elements of the array are NULL?

This code works if you want to test if all the elements of the array are number 8, but doesn't work on NULLs:

SELECT 8 = ALL(ARRAY[8,8,8,8]::int[]); -- returns true


Unfortunately, you cannot use that same construct for comparing nulls, this return null:
SELECT NULL = ALL(ARRAY[NULL,NULL,NULL,NULL]::int[]);

And this returns a syntax error:
SELECT NULL IS ALL(ARRAY[NULL,NULL,NULL,NULL]::integer[]);

Fortunately, there's a function to un-nest an array to row elements; then from there, we can use the ALL construct for rows

So given this:

create table x
(
y serial,
z int[]
);

create table x
(
y serial,
z int[]
);

insert into x(z) values
(array[null,null,null]::int[]),
(array[null,7,null]::int[]),
(array[null,3,4]::int[]),
(array[null,null,null,null]::int[]),
(array[8,8,8,8]::int[]);

q_and_a=# select * from x;
 y |           z
---+-----------------------
 1 | {NULL,NULL,NULL}
 2 | {NULL,7,NULL}
 3 | {NULL,3,4}
 4 | {NULL,NULL,NULL,NULL}
 5 | {8,8,8,8}
(5 rows)


Then let's try to unnest array z from x:
q_and_a=# select *, unnest(z) from x;
 y |           z           | unnest
---+-----------------------+--------
 1 | {NULL,NULL,NULL}      |
 1 | {NULL,NULL,NULL}      |
 1 | {NULL,NULL,NULL}      |
 2 | {NULL,7,NULL}         |
 2 | {NULL,7,NULL}         |      7
 2 | {NULL,7,NULL}         |
 3 | {NULL,3,4}            |
 3 | {NULL,3,4}            |      3
 3 | {NULL,3,4}            |      4
 4 | {NULL,NULL,NULL,NULL} |
 4 | {NULL,NULL,NULL,NULL} |
 4 | {NULL,NULL,NULL,NULL} |
 4 | {NULL,NULL,NULL,NULL} |
 5 | {8,8,8,8}             |      8
 5 | {8,8,8,8}             |      8
 5 | {8,8,8,8}             |      8
 5 | {8,8,8,8}             |      8
(17 rows)

We can compare the element directly from select clause:

q_and_a=# select y, unnest(z), unnest(z) is null from x;
 y | unnest | ?column?
---+--------+----------
 1 |        | t
 1 |        | t
 1 |        | t
 2 |        | t
 2 |      7 | f
 2 |        | t
 3 |        | t
 3 |      3 | f
 3 |      4 | f
 4 |        | t
 4 |        | t
 4 |        | t
 4 |        | t
 5 |      8 | f
 5 |      8 | f
 5 |      8 | f
 5 |      8 | f
(17 rows)


Now, given that information on hand, we could proceed with this query:

with a as
(
    select y, unnest(z) as b
    from x
)
select 
 y, every(b is null)
from a 
group by y
order by y

Output:
 y | every
---+-------
 1 | t
 2 | f
 3 | f
 4 | t
 5 | f
(5 rows)


But the following is a lot better than that:

select
 y, true = ALL (select unnest(z) is null)
from x


Output:
 y | ?column?
---+----------
 1 | t
 2 | f
 3 | f
 4 | t
 5 | f
(5 rows)

If you want to make your query flexible(e.g. by way of concatenated query), you could do the following:

select
y, coalesce( true = ALL (select b is null from unnest(z) as a(b)), false )
from x

Then you can change the expression b is null to something else:

select
y, coalesce( true = ALL (select b = 8 from unnest(z) as a(b)), false )
from x

Sunday, June 12, 2011

Hibernate and Java command-line compilation, the understanding

1. Prepare a directory(java package) that won't have a collision with other package name, ideally this is your reverse domain name. Mine is http://anicehumble.com. So the package goes to com/anicehumble directory.
$ mkdir -p source/com/anicehumble

2. Create a directory for your compiled class
$ mkdir class

3. Create a directory for libraries you are using, this is where you will put jar(java archive) files, e.g. Hibernate
$ mkdir lib



4. Then fire up your favorite text editor, mine is vi ;-)
$ vim source/com/anicehumble/TryHib.java

5. Then type this:
package com.anicehumble;

public class TryHib {
        public static void main(String[] args) {
                System.out.println("Hello World");
        }
}

6. Then compile:
$ javac -d class source/com/anicehumble/TryHib.java

The -d class is a directive for javac compiler to put your compiled class(es) to class directory, the compiled class(es) will be put on the directory based on the name you specified on the topmost line of your java code, which is package com.anicehumble;; with this, your .class file(s) will be put in class/com/anicehumble. Make it a habit to use -d yourdirectoryhere so your source code and compiled code is more organized. If you don't specify -d directive, the compiled code will also be put in the same directory as your source code.

7. To run:
java -classpath class com.anicehumble.TryHib

Note that we specify classpath, if we don't specify -classpath class, we have to do two steps:
cd class
java com.anicehumble.TryHib

Please do note that we need to use dots instead of forward-slashes(or back-slash when using Windows) when running Java programs.

8. Let's create a model

Create a directory for model
$ mkdir source/com/anicehumble/model

Create a Person.java class under your model directory
$ vi source/com/anicehumble/model/Person.java 

Type this in your text editor:

package com.anicehumble.model;

public class Person {

        private int personId;
        private String personName;
        private int age;


        public int getPersonId()  {
                return personId;
        }
        public void setPersonId(int value) {
                personId = value;
        }

        public String getPersonName() {
                return personName;
        }
        public void setPersonName(String value) {
                personName = value;
        }

        public int getAge() {
                return age;
        }
        public void setAge(int value) {
                age = value;
        }

}

Compile
$ javac -d class source/com/anicehumble/model/Person.java 

To check the compiled code
ls class/com/anicehumble/model/Person.class

9. Access the Person class from TryHib.java

package com.anicehumble;

import com.anicehumble.model.*;

public class TryHib {
        public static void main(String[] args) {
                // com.anicehumble.model.Person p = new com.anicehumble.model.Person();
                Person p = new Person();
                p.setPersonName("Michael");
                System.out.println("Hello " + p.getPersonName());
        }
}

Compile:
$ javac -d class -classpath class source/com/anicehumble/TryHib.java

Then run:
$ java -classpath class com.anicehumble.TryHib

Output:
Hello Michael

10. Map the Person class to Hibernate, download this first:

Download the following files and put them on your lib directory
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
postgresql-9.0-801.jdbc4.jar
slf4j-api-1.6.1.jar
slf4j-simple-1.6.1.jar

11. Create a hibernate configuration under class/com/anicehumble

$ vi class/com/anicehumble/hibernate.cfg.xml

Type this, or better yet paste it:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1/testdb</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">opensesame</property>
        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.use_outer_join">true</property>

        <mapping resource="com/anicehumble/model/person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

12. Map the class to table, use this xml mapping:

Create person.hbm.xml mapping with your favorite editor:
$ vi class/com/anicehumble/model/person.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

        <class name="com.anicehumble.model.Person" table="person">
                <id name="PersonId" column="personid">
                <generator class="sequence">
                        <param name="sequence">person_personid_seq</param>
                </generator>
                </id>

                <property name="PersonName" column="personname"/>
                <property name="Age" column="age"/>
        </class>

</hibernate-mapping>


13. Use the Person class and map it to database:

Launch your favorite editor
$ vi source/com/anicehumble/TryHib.java 

Type this:
package com.anicehumble;

import com.anicehumble.model.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;



public class TryHib {
        public static void main(String[] args) {
                System.out.println("Hello");

                SessionFactory sf = new Configuration().configure("/com/anicehumble/hibernate.cfg.xml").buildSessionFactory();


                Session sess = sf.openSession();
                Person p = (Person) sess.get(Person.class, 1);

                int result = p.getAge();

                System.out.println(Integer.toString(result));

                System.out.println("Test");
        }
}

Compile(substitute colon with semicolon when you are on Windows):
$ javac -classpath class:lib/hibernate3.jar -d class source/com/anicehumble/TryHib.java 

14. Run(substitute colon with semicolon when you are on Windows):
$ java -classpath class:lib/commons-collections-3.1.jar:lib/dom4j-1.6.1.jar:lib/hibernate-jpa-2.0-api-1.0.0.Final.jar:lib/hibernate3.jar:lib/javassist-3.12.0.GA.jar:lib/jta-1.1.jar:lib/postgresql-9.0-801.jdbc4.jar:lib/slf4j-api-1.6.1.jar:lib/slf4j-simple-1.6.1.jar com.anicehumble.TryHib

Output:
Hello
35
Test

15. I forgot, before you do step 14, here's the Postgres DDL for your model/object:

CREATE TABLE person
(
  personid serial NOT NULL primary key,
  personname varchar(1000) NOT NULL unique,
  age integer NOT NULL,
);
insert into person(personname, age) values('michael', 35);

Wednesday, June 8, 2011

Java Jar in 11 easy-to-follow steps

$ mkdir -p FirstProject/source/com/anicehumble
$ cd FirstProject/source/
$ vim com/anicehumble/Person.java

Then enter this:
package com.anicehumble;

public class Person {
        public static void main(String[] args) {
                System.out.println("Hello World");
        }
}

$ mkdir ../classes
$ javac -d ../classes com/anicehumble/Person.java 

The javac -d will build your Person.java in a mirror path(package) of your source code's path. So if you put your source code under the path of com/anicehumble, the -d ../classes parameter tells the compiler to put your compiled code in com/anicehumble path too, and under the classes path.

$ cd ../classes/

To test if your program is running properly(note, should use dots, not forward-slash, nor back-slash):
$ java com.anicehumble.Person

To put your class file in a JAR, create a manifest file first, indicating which class should the java runtime will look for main method:

$ echo "Main-Class: com.anicehumble.Person" > manifest.txt

Then put the classes in the jar, along with the manifest file:
$ jar -cvmf manifest.txt FTW.jar com/anicehumble/Person.class

Alternatively, you can do this, jar recursively get all the files if you just specify directory:
$ jar -cvmf manifest.txt FTW.jar com

To run:
$ java -jar FTW.jar

To make sure that your jar file is indeed self-contained:
$ mv FTW.jar ~/Desktop/
$ cd ../..
mv FirstProject x_Project 

The last step(mv, Unix's rename) above is to make sure that there's no false positive ;-)
$ cd ~/Desktop/

To run:
java -jar FTW.jar

Monday, June 6, 2011

Hello World

Michael-Buens-MacBook:src Michael$ mkdir -p a/nice/humble

Note above, if you are in Windows, create each directory(i.e. a, nice, humble) one by one.

Then create the file:

Michael-Buens-MacBook:src Michael$ vim a/nice/humble/Person.java

If you are in Windows, use Notepad++, it's an awesome editor.

Then type this:
package a.nice.humble;

public class Person {

        public static void main(String[] args) {
                System.out.println("Hello World!");
        }
}

Then type this in commandline:
Michael-Buens-MacBook:src Michael$ javac a/nice/humble/Person.java

Then type this in commandline to run your first program:
Michael-Buens-MacBook:src Michael$ java a.nice.humble.Person

Note, need to use dots, not forward-slash nor backward-slash

Output:
Hello World!

Saturday, June 4, 2011

Java

package buen.michael;

public class HelloWorld {
   public static void main(String[] args) {
       System.out.println("Hello World. Test Syntax Highlighter");
   }
}

Thursday, June 2, 2011

Hibernate Troubleshooting

If you have the following errors, just drag the jar file to your lib folder

java.lang.NoClassDefFoundError: org/dom4j/DocumentException
copy this to your lib: dom4j-1.6.1.jar

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
copy this to your lib: slf4j-api-1.6.1.jar

java.lang.NoClassDefFoundError: javax/persistence/EntityListeners
copy this to your lib: hibernate-jpa-2.0-api-1.0.0.Final.jar

org.hibernate.HibernateException: JDBC Driver class not found: org.postgresql.Driver
copy this to your lib: postgresql-9.0-801.jdbc4.jar
download the latest Postgresql jdbc jar file from postgresql.org


java.lang.NoClassDefFoundError: org/apache/commons/collections/map/LRUMap
copy this to your lib: commons-collections-3.1.jar

org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
copy this to your lib: javassist-3.12.0.GA.jar

java.lang.NoClassDefFoundError: javax/transaction/Synchronization
copy this to your lib: jta-1.1.jar

Sunday, March 20, 2011

Java Stripes video tutorial

This is my first Java vlog. This tutorial shows how to setup Stripes in just few minutes