Monday, February 23, 2009

Hibernate session merge

I've recently discovered the beauty of Hibernate's Session.merge() method.
To explain this.... I'll describe the situation on hand, using the classic Parent & Child relationship (Parent has many children, and each children can only have 1 parent - lets keep it that way for now... you might argue a child has 2 parents)

I mapped the Parent & Child as follows:

@Entity
@Table(name="parent")
public class Parent {
...
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="parent")
@Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private List children = new ArrayList();

}

@Entity
@Table(name="child")
public class Child{
...
@ManyToOne
@JoinColumn(name="parent_id", nullable=false)
private Parent parent;

}


The usual situation - we load up parent & the children, then display parent information & the children on the UI layer. User might update both the parent & the children, and that is fine, since we have specified the Cascade ALL option. But what about deleting the child? Note that Cascade REMOVE is not what you want here.... that's saying ... if the parent is deleted, then delete all the children too (quite straight forward, isnt it?).
Hibernate has the org.hibernate.annotations.CascadeType.DELETE_ORPHAN annotation, which seems like what we need here. If the child is orphan (i.e. doesnt have any parent), then delete it from the database. Looks promising, except there's a catch.
The parent & the children has to be on the session. i.e. it has to be loaded on the same session.. before this can work with the usual session.saveOrUpdate() / session.update() method. Thats kinda... sucks.... because most of the time... you will load the parent & the children, display on the UI, and then do some operations (which might remove some children), then let the UI framework to recreate the parent & children through some kind of binding mechanism (or... you might do it yourself)... and call session.saveOrUpdate() on the new hibernate object.
i.e. the object that you gave to hibernate is transient. So... hibernate wouldnt delete that orphan child...
This is where session.merge() comes into play. It just simply works with session.merge(), because session.merge() will try to merge the transient object with the persisted object

From Javadoc:

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".


So session.merge will also load the given object with the same identifier. Thats how it works.
Another beauty thing with session merge, which might be easier to explain using some pseudocodes..


Parent parent = new Parent();
Child child = new Child();
child.setChildId(1L);
parent.addChild(child);
Parent savedParent = session.merge(parent);

Session merge will return the persisted instance. So in the example above... (assuming child is already persisted in DB), then parent.getChildren().get(0).getName() will return the string from DB.

where as:

session.merge(parent);
System.out.println(parent.getChildren().get(0).getName()) will return null.

Another thing to point out, is that there's cascade MERGE type. Which, as the name suggests, does cascade on session.merge() operation.

One important thing to keep in mind, is that session merge returns a new instance.

So in the code above:
parent != savedParent
and you might want to work using savedParent onwards anyway.

Sunday, February 22, 2009

One step closer to solving Eternity 2 puzzle

Ok... I'm a bit ecstatic now. I manage to solve 14x14 eternity 2 puzzle in 18ms. That is a major leap for me. From 6 minutes for a 12x12 board, to this result.... I cant be any happier :)

Do I have anything else in mind to improve the code? Not yet. Ah well, I have another strategy, but I'm a bit afraid that the cost of doing it outweighs the benefit. Well... I dont have the 16x16 pieces at the moment. But my friend does. So I'll run the program tomorrow against those pieces.

Wish me luck! :)

Eternity Puzzle - 12 x12

I have made some improvements to my eternity puzzle solver.
It can now solve up to 12x12 within 'reasonable' time, albeit I have to say it is still way too slow for 12x12 (6 minutes). If my calculation is correct, a 12x12 puzzle has:

144! x 4^(144) possible combinations, or roughly
22 x 10^(335) possible combinations.

So, that is not a terrible result. :)
I still have some improvements in mind - although I'm not too sure if they will affect the result that much, since they are merely using language features.

Well.. time will tell. :)

Oh, in case you are wondering how long it takes to solve the 4x4 puzzle with my current solver, it is 4ms.

My US$2 million quest

Monday, November 26, 2007, 01:45 PM - Technology
I'm currently writing an application to solve Eternity II puzzle. For those who dont know what Eternity II puzzle is, here is the website.
So far my application can solve the 4x4 puzzle in about 15 ms.

For a 4x4 puzzle, there are about 16! x 4^16 combinations, which according to windows calculator, it comes to 89,862,698,310,039,502,848,000 combinations. So to pick up one solution in that haystack in 15ms, I cant feel any happier :). Still, I can guarantee that my application wont even run to completion on the original puzzle (16x16).

For a 16x16 puzzle, there are 256! x 4^(256) combinations. Again, according to windows calculator, that is roughly 1.151 x 10^(661). What do you call that? 10^661(more than the number of atoms in the universe!). Lol. My application will certainly throw StackOverflowError. :P

There are a couple of strategy I have in mind - which of course I wont reveal here (yet). :)

Steve Jobs Stanford Commencement Speech

I watched a very inspiring video on YouTube this morning. It was by Steve Jobs on his commencement speech at Stanford University, in 2005. I wish I had this kind of talk on my graduation, rather than some bloke who talked about his project (which happened to be building city sewerage.. bahhhh).

Anyway, here is the script.



This is the text of the Commencement address by Steve Jobs, CEO of Apple Computer and of Pixar Animation Studios, delivered on June 12, 2005.

I am honored to be with you today at your commencement from one of the finest universities in the world. I never graduated from college. Truth be told, this is the closest I've ever gotten to a college graduation. Today I want to tell you three stories from my life. That's it. No big deal. Just three stories.

The first story is about connecting the dots.

I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out?

It started before I was born. My biological mother was a young, unwed college graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: "We have an unexpected baby boy; do you want him?" They said: "Of course." My biological mother later found out that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would someday go to college.

And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn't interest me, and begin dropping in on the ones that looked interesting.

It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms, I returned coke bottles for the 5¢ deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example:

Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and san serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating.

None of this had even a hope of any practical application in my life. But ten years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, its likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backwards ten years later.

Again, you can't connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something — your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life.

My second story is about love and loss.

I was lucky — I found what I loved to do early in life. Woz and I started Apple in my parents garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4000 employees. We had just released our finest creation — the Macintosh — a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating.

I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down - that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me — I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over.

I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life.

During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the worlds first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is at the heart of Apple's current renaissance. And Laurene and I have a wonderful family together.

I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle.

My third story is about death.

When I was 17, I read a quote that went something like: "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "No" for too many days in a row, I know I need to change something.

Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life. Because almost everything — all external expectations, all pride, all fear of embarrassment or failure - these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.

About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor's code for prepare to die. It means to try to tell your kids everything you thought you'd have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.

I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and I'm fine now.

This was the closest I've been to facing death, and I hope its the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept:

No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life's change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.

Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma — which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.

When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960's, before personal computers and desktop publishing, so it was all made with typewriters, scissors, and polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: it was idealistic, and overflowing with neat tools and great notions.

Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: "Stay Hungry. Stay Foolish." It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.

Stay Hungry. Stay Foolish.

Thank you all very much.

Saturday, February 21, 2009

IntelliJ shortcuts

Here are some shortcut keys that I found useful in IntelliJ

NAVIGATION

Ctrl-E Show recent edited file
Ctrl-Alt-Left Go back (through recent editing locations)
Ctrl-Alt-Right Go forward (through recent editing locations)
Alt-Left Go to previous editor window in current tab set
Alt-Right Go to next editor window in current tab set
Ctrl-] Go forward to matching bracket
Ctrl-[ Go backward to matching bracket
Ctrl-G Go to line number
Ctrl-B Go to declaration of object at cursor
Ctrl-H Show class hierarchy of current class
Ctrl-Shift-H Show class hierarchy of current method
F2 Go to next error


FINDING STUFFS
Ctrl-N
Ctrl-Shift-N
Ctrl-Alt-Shift-N
Ctrl-Shift-F
Ctrl-Shift-F7 Highlight all occurrences of identifier in file
Alt-F7 Find all references in workspace (showing them in Search pane)
Alt-F3 incremental search
Ctrl-F Search within a file
F3 Search Next within a file
Shift-F3 Search previous within a file
Ctrl-Shift-n Toggle bookmark n
Ctrl-n Go to bookmark n
F11 Toggle bookmark
Shift-F11 Show bookmarks

EDITING

Ctrl-Space Code completion
Ctrl-Alt-Space Class name completion (adding import if missing)
Ctrl-Shift-Enter Finish current line
Ctrl-Shift-J Smart line join
Ctrl-F4 Close editor window
Ctrl-Q show quick javadoc
Ctrl-P show parameter to method
Alt-Q Show current context (method, class, etc)
Alt-insert insert constructor/getter setter/etc
Ctrl-Alt-T surround by (highlight portion of code first)
Ctrl-Shift-V insert from clipboard (keeps track of last few clipboard item)
Ctrl-Shift-F12 Maximize editor
Ctrl-O override methods
Ctrl-I implement method
Ctrl-Shift-U toggle case for selected block
Ctrl- Numpad +/- expand/collapse code block
Ctrl-D duplicate current line
Ctrl-X cut current line
Ctrl-Alt-I auto indent
Ctrl-Alt-L reformat code
Ctrl-Alt-O optimise imports
Ctrl-W select successively increasing code blocks
Ctrl-Shift-W decrease current selection

REFACTOR
Ctrl-Alt-M extract method
Ctrl-Alt-V introduce variable
Ctrl-Alt-P introduce parameter
Ctrl-Alt-F introduce field
Ctrl-Alt-C introduce constant
Shift-F6 Rename
F6 Move
Ctrl-F6 change signature


LIVE TEMPLATES
sout System.out.println
psvm public static void main
iter Java 5 style iteration
itli Iterate through list
itar Iterate through array
itit Iterate through iterator

VCS
Ctrl-T Update project from VCS
Ctrl-K commit project to VCS

Work

I had a complaint for quite some time... that I got underpaid for the job I'm doing. Strange enough.... I had this weird dream. I spoke to my division manager, and he said.. "Do you really think you get underpaid? You said that you worked hard, did overtime, etc etc. Try to go home earlier everyday, spend more time with the one that you love. Then you will feel that you get that extra pay from them".
Maybe thats true... I spent so little time with her lately...

Tuesday, February 03, 2009

Pergi

Putus sudah teratai terunjuk benang..
tak kutahu beda sunyi dan tuli, gelap dan buta..
detak jantung dan bunyi nafas berlomba,
memacu waktu yang tak kunjung berhenti..

hari seakan serasa bulan,
pelangi pun senggan berbagi warna,
helai yang tak tergapai telapak tangan,
bayangannya menjauhiku di sini..

dia telah pergi,
enggan berbagi sedetik lebih waktu
inilah ujung jalan kita