# Sunday, April 13, 2008

Refactoring

On a recent project I had after some thoughts I decided to unify some coding styles.
Eclipse rules in that matter. It was cumbersome, but easy enough. Until I reached a point.

Refactoring some coding style differences is a piece of cake.
Refactoring some design issues you want to fix is mission impossible.

The best way to proceed - scrap it and start from scratch. By scrap it I mean make a clean project and copy only relevant stuff.

Now this project has 2 times less classes :)

Dude, where's my terrace?!

И сега къде ще си простра прането:
(коментарът е на БГ, щото ми е трудно да преведа "простра прането" на английски)

Fix this

Only a restart can fix this
(happened after a beamer was unplugged, vista rulez)


10 kilometers

I ran 10 kilometers today. But only if the track was 400 m long, if it was 300, I ran only 7.5, which is still a good result for me.

# Tuesday, April 08, 2008

Старата фонетична за Виста

(Само и само да си вдигна рейтинга в Гугъл...)

Както всички, които са ползвали поне малко Windows Vista, са забелязали - няма я старата фонетична подредба. Аз лично я ползвах доста. Вместо нея има сложена една "стандартизирана от БАН" фонетична подредба, на която обаче няколко букви са разместени. Примерно Ж е на мястото на W, което на мен не ми харесва.

Имаше някъде спор из нета относно коя да бъде - старата или новата, но ме мързи да търся.
Аз си харесвам старата и открих един инструмент от Майкрософт (тук ще ги похваля), с който сравнително лесно могат да се пренаредят клавишите (едно време имаше нещо подобно във FlexType (моля ви, не си слагайте FlexType - Инженерът ще се кара)).
Инструментът се казва Microsoft Keyboard Layout Creator. Работата с този инстурмент не е толкова елементарна колкото изглежда, аз няколко пъти оплесквах нещата.

Та а използвайки тоя инструмент си направих фонетична подредба.

Update: във фонетичната на БАН забелязах нещо интересно: Shift + ь = ѝ. Тоест малка оптимизация. Ер малък се използва само като малка буква. Главна такава буква в Българския език няма. На мястото на главната буква те са сложили "и с ударение". И с ударение също няма главна буква, тоест ѝ трябва само една позиция на клавиатурата. За "и с ударение" имам малко инфо тук.
Та аз реших да направя същата оптимизация и направих нова версия на класическата фонетична за Виста.

Инструкции за инсталация:
  1. от zip файла с инсталатор цъкнете на setup.exe, следвайте инструкциите.
  2. Клавиатурата сама се "пъха" в активните, така че веднага е готова за употреба.
  3. Ако все пак искате да цъкате ръчно разни неща: "Regional and Language Options" в Contol Panel -> "Keyboards and Languages" -> "Change keyboards..."
  4. Фонетичната на Виста/БАН се казва "Bulgarian (Phonetic)", моята излиза като "Bulgarian (Phonetic) - REAL"
  5. Ако имате старата ми версия инсталирана, по-добре я махнете, тъй като и старата и новата излизат с еднакво име. В списъка с инсталирани програми се различават по версията, обаче.
Поддържани хардуерни платформи: i386 (32 bit), ia64 (64 bit), amd64, wow64 (дори не знам какво е това).

Това е фонетичната подредба за Windows Vistа (в архива има инсталатор):
Bulgarian (Phonetic) - Old School (by Mihail Stoynov).zip (253.38 KB)      (без оптимизацията за "и с ударение")
Bulgarian (Phonetic) - Old School (by Mihail Stoynov) v2.0.zip (252.92 KB)       (с оптимизацията за "и с ударение")

Ето и самата подредба (ако някой иска да си играе с нея, не е никак елементарно):
Bulgarian (Phonetic) - Old School (by Mihail Stoynov).keyboard layout.zip (2.26 KB)      (без оптимизацията за "и с ударение")
Bulgarian (Phonetic) - Old School (by Mihail Stoynov) v2.0.keyboard layout.zip (2.33 KB)     (с оптимизацията за "и с ударение")

# Thursday, April 03, 2008

JPA (Hibernate) and enums, Updated

If there's an enum
(this is all java 5)
  
@Entity
public static enum Type {
    TYPE_1(1);

private int i;
    private Type(int i) {this.i = i;}
}


you can't do entityManager.merge( Type.TYPE_1 ), because merge returns a persisted copy of that object and requires a default constructor.
Even if you add

      
private Type(){}


it would fail.

The only way to add the possible values is with persist:

step1:
for( Type type : Type.values() ) {
    entityManager.persist( type );
}

Unfortunately I don't know of a shortcut for that operation - it seems logical all enum values to be in the DB, but are not there by default.

So what happens if there's an object

@Entity
public class Subscription {
   // Cascading for all operations
   protected Type type;
}


and one wants to persist an object like that: 

entityManager.persist( new Subscription() ); // would work even without step1
entityManager.merge( new Subscription() ); // would work only with step1
entityManager.merge( new Subscription() ); // without step1: "
InstantiationException: No default constructor for entity

So the conclusion is:
It's relatively easy to use enums as @Entities as long as on DB init all the enum values are preloaded in the DB (step1).

UPDATE:
What I wrote so far is true, BUT:

Even if one can persist enum, one cannot get them back, because of the aforementioned problem with the default constructor.

I was thinking of the doing the type-safe enum design pattern myself (as it was done pre- java 5): useless supplying a default .ctor prevents having a small number of instances - so again no good. Maybe if the .equals() and .hashcode() are rewritten this could work (but with a larger number of instances and a small number of different hashcodes) - just thought of it, may or may not work. One has to think about @Enumerated (JPA) or about Enum.name() and enum.ordinal() - still it does not look achievable.

There is an ugly solution of which I shall speak tomorrow because I want to go home !!!.

UPDATE: The solution: (be warned it's really ugly).

There should be an @Entity with an int (or whatever actually) @Id.
Then there should be the enum with a private property, whose type should be the @Id of the previous class. There should be a getter of that property
The getter() and setter() of the @Entity should be with the enum's type and in the getter and the setter the wrapping between the enum and it's int (or whatever actually) should occur.


Examples when I get back from lunch.

UPDATE: Example

// The enum
public enum Gender {
  Male(0),
  Female(1);
  private int value;

  private Gender(int value) {
    this.value = value;
  }

  public getValue() {
    return this.value;
  }
}

@Entity
public class Entity1 {
  @Id
  private int gender;


  // ... other properties

  public Gender getGender() {
    return Gender.valueof(this.gender);
  }


  public Gender setGender( Gender gender) {
    this.gender = gender.getValue();
  }


  // ... other stuff.
}


Yes, I know - it's ugly, but this is the best I know.

JVM Crash - have never seen that before



This is to JVM* what BSOD** is for Windows.

* Java Virtual Machine (the Java runtime)
**Blue Screen of Death (the thing windows does when it crashes)

Note: this happened when trying to merge (in Hibernate) an enum with a default private .ctor.

It is a happy day :)
# Wednesday, April 02, 2008

ICQ in GoogleTalk web client (gmail) - amazing

Open browser, go to the messenger part, log in, as simple as that.

First impressions:
  • no ICQ groups - that sucks - I used to use it a lot
  • aliases of people are retained ('MG Zas' for example) - which is a backup for groups ('group MG -> user Zas' becomes 'MG Zas').
  • Cyrillic characters work fine (if it was working with my other client - Pidgin/Gaim)

Concerning the standalone client - Google Talk - I have no idea if it works there - Google have a pretty wierd update policy - they update silently and only some clients - it sucks.



After all  - it's usable

First in weird google search

How can this blog be the first in this search
email program fails needs ttl start first

What's wrong with you google?!

Update: Now I'm sixth.

# Monday, March 24, 2008

Being a referee at the IT Boxing event

The event: http://itboxing.devbg.org/


100 000 bucks joke

I have a friend who once called and asked whether I could loan him 100 000 bucks just as easily as if he has said 'let's go have a cup of coffee'.

So for his birthday he got:

# Monday, March 17, 2008

I failed exam 11

I have a bad feeling in my mouth. Too bad, it would have been a good T-shirt sign: 12 exams in 1 month. Now it's gonna be even longer 10/11 exams passed, 1/2 failed in one month :)

180° flips with and without help

The last two days I went skiing (well, actually snowboarding) with a friend with which I haven't before and learned some new tricks. Now 180° turns aren't a problem. First the training started with doing (trying to do) turns without jumps (this is really exhausting because a jump alleviates the whole thing - rises you in the air), then little by little I started testing steep jumps with low speed (rises you high without being fast) and it worked.

Some of the turns (when riding on the back edge of the board) can be done in an easier manner when part of it is touching the snow while turning - it looks like doing half a circle. This way if there's some unevenness it can be used to help lift the board.

The whole thing took a lot more energy than usual, because of all the jumping and falling down. Now I have muscle aches all over my body, but it was worth it.

There are no pictures because it's hard to take some with two pairs of gloves and wrist-protectors in the middle.

# Wednesday, March 12, 2008

Psycho II

There's a second Psycho coming soon.

Guess who's on the picture there (1st row, 1st guy from right to left).
    Yes, you're right, that's me on the first Psycho.

Here's one more picture from it (I'm the guy looking right):

# Tuesday, March 11, 2008

Facebook cause invitation

After a ton of spam email, and numerous invitations for outrageously stupid quizzes I was thinking of closing my facebook account.

Today I saw an invitation to support: "Stop violence in porn animation" cause.

The account will stay open - facebook emails are now forwarded to my PHUN folder.

The exams are over

After a month and a half of homeworks, essays, analyses and exams, it's all over. There are still four exams pending, but the studying is over.
Life is beautiful again :)

# Monday, March 03, 2008

Some Google services do not work today (in firefox only?!)

Since yesterday there are problems connecting to Google:

Reply from 64.233.167.99: bytes=32 time=152ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Request timed out.
Request timed out.
Reply from 64.233.167.99: bytes=32 time=150ms TTL=9
Request timed out.
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=152ms TTL=9
Request timed out.
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=150ms TTL=9
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Request timed out.
Request timed out.
Request timed out.
Reply from 64.233.167.99: bytes=32 time=151ms TTL=9
Reply from 64.233.167.99: bytes=32 time=150ms TTL=9

There are time-outs connecting even from the states.

Really strange. Search and Calendar work fine, Gmail does not even load:

Loading…
This seems to be taking longer than usual.
...

Google reader does not load.

It all on periods - it works, it doesn't, ...

Update: Gmail, calendar work in IE, they do not in firefox - no idea.
A friend experieces the same issues but with different services (Docs)...
# Sunday, March 02, 2008

dasBlog, medium trust and pingbacks

I had an issue for quite a while with pingbacks in dasBlog:

Error:
System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, ... failed.
at ...
at newtelligence.DasBlog.Runtime.Proxies.WeblogUpdatesClientProxy.Ping(String weblogName, String weblogUrl)
at newtelligence.DasBlog.Runtime.BlogDataServiceXml.PingWeblogsWorker(Object argument)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Net.WebPermission


It comes up that medium trust allows opening connections only to originHost (I guess localhost).

Here's how I solved it:

go to
%windir%\Microsoft.NET\Framework\{version}\CONFIG\web_mediumtrust.config

and find
<IPermission class="WebPermission" ...

and add some additional URIs:
<IPermission
    class="WebPermission"
    version="1">

    <ConnectAccess>
        <URI uri="$OriginHost$"/>
            <!-- [Mihail Stoynov] dasBlog needs it for pingbacks START -->
            <URI uri="http://rpc.weblogs.com/RPC2"/>
            <URI uri="http://rpc.technorati.com/rpc/ping"/>
            <URI uri="http://ping.blo.gs/"/>
            <URI uri="http://rpc.pingomatic.com/"/>
            <URI uri="http://ping.feedburner.com"/>
            <URI uri="http://api.feedster.com/ping"/>
            <URI uri="http://xping.pubsub.com/ping/"/>
            <URI uri="http://api.my.yahoo.com/RPC2"/>
            <!-- [Mihail Stoynov] dasBlog needs it for pingbacks END -->
        </ConnectAccess>
</IPermission>

These addresses were in %dasBlog%\SiteConfig\WebServices.xml

Orbit watermelon after laundry



Second time I do that.

Now all my clothes smell like strawberry :(