February 20, 2010 .NET, LambdaExpression, MasterDiploma 6 comments
February 20, 2010 .NET, LambdaExpression, MasterDiploma 6 comments
For my Diploma work I need to calculate distance between two vectors.
For example, Euclidean distance is calculated like:
How could it look if I do have two lists with values?
Something like this:
But, please take a look how sweet this all could be with Lambda Expression:
Of course main point of this post is not to show all beauty of LE, but either what did happen after I wrote this Lambda expression. Maniacal interest in what is faster to execute and what is the difference in performance of this two methods appeared in my mind, so I prepared few simple tests.
I’ve ran my tests on 1000000 elements and results were such:
Also, I played with VS performance analyzer (Analyze -> Launch Performance Wizard…).
It allows me run one version of code (Lambda) and get detailed report, then run another version of code (Loop) and get another report. After that I’m able to compare results seeing performance improvements. So that is good tool.
February 19, 2010 NHibernate, QuickTip No comments
What do you see to be wrong with this code?
.Add(Restrictions.Eq(“r.Name”, ruleName))
//other restrictions
.List();
return result.Count > 0;
}
At first I did not see any issues with it so I copied it and changed a bit for my another query. But current method is wrong. I discovered this with UTs.
First, Projections.RowCount() generates COUNT(*) in select statement.
This is query, which I got from my new Unit Tests: RuleExists_HitsDatabase_ThereIsNoRule.
Result of this query is number of rows like on picture below:
So, verification return result.Count > 0; is absolutely incorrect.
I’ve chagned it to return (int)result[0] > 0;
Moral:
Do not be lazy to write Unit Tests both for success and failure sceneries.
February 15, 2010 NHibernate, QuickTip No comments
ORDER BY
To add “order by” to your criteria you need this statement.
.AddOrder(Order.Asc(“Priority”))
TOP
To add “top 10” to your criteria you need this statement
.SetMaxResults(10)
Criteria
So code about which I’m talking could look like:
SetResultTransformer or “Why did I get 5 results instead of 10?”
So you expect to have top 10 priority Customers with status Created.
In scope of my current task it was needed to add priority to this query, so I decided to unit test it of course.
In Debug I found that there are actually 5 results in resulting collection.
That is because generated SQL generates result which contains duplicated CUSTOMER_IDs, that is because I have join-s there. But then why did not I get 10 duplicated Customers? Because query has ResultTransformer which is applied after SQL has been ran. (That is 100% since I took a look at generated SQL via NHibernateProfiler).
So .SetResultTransformer(new DistinctRootEntityResultTransformer()) is removing of all duplicated entries of my root entity (Customer).
Good explanation to this you can find here.
February 13, 2010 Design Patterns 2 comments
Imagine that you are game developer. Your game is war stategy. Army has complicated structure: it consists with Hero and three Groups. When King gives decree to treat all soldiers (Hero is also soldier) you want to iterate through all soldiers and call treat() method on each soldier instance. How can this be accomplished easily and without diving into Army structure?
Iterator is the pattern which provides you a way to access all elements in any collection of data without exposing collection implementation.
So in application to our problem. You just don’t want to care about structure of your army – you want some SoldiersIterator to loop through all soldiers in it. Red line is the Iterator (in my mind representation).
Usage
Code below shows usage of iterator. We can loop through all soldiers and increase their health level without thinking of the structure of Army. This should be easy and it is main purpose of Iterator.
Army structure
Army structure has one Hero and could have many Groups which of them could have many Soldiers. So as we see structure of Army is complicated and tree-based. Code below represents instantiating of Army:
Hero is class derived from Soldier and has only one difference – higher health level:
public class Hero extends Soldier {
protected int maxHealthPoints = 500;
public Hero(String name) {
super(name);
}
}
SoldiersIterator
So if we can move through the complicated collection of Soldiers where is that complicity?
Well, it is encapsulated in concrete Iterator class.
private Army _army;
boolean heroIsIterated;
int currentGroup;
int currentGroupSoldier;
public SoldiersIterator(Army army) {
_army = army;
heroIsIterated = false;
currentGroup = 0;
currentGroupSoldier = 0;
}
public boolean hasNext() {
if(!heroIsIterated) return true;
if(currentGroup < _army.ArmyGroups.size())return true;
if(currentGroup == _army.ArmyGroups.size()–1)
if(currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size())return true;
return false;
}
public Soldier next() {
Soldier nextSoldier;
// we still not iterated all soldiers in current group
if (currentGroup < _army.ArmyGroups.size()) {
if (currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size()) {
nextSoldier = _army.ArmyGroups.get(currentGroup).Soldiers.get(currentGroupSoldier);
currentGroupSoldier++;
}
// moving to next group
else {
currentGroup++;
currentGroupSoldier = 0;
return next();
}
}
// hero is the last who left the battlefield
else if (!heroIsIterated) {
heroIsIterated = true;
return _army.ArmyHero;
} else {
// THROW EXCEPTION HERE
throw new IllegalStateException(“End of colletion”);
//or set all counters to 0 and start again, but not recommended
}
return nextSoldier;
}
}
Why my example is not standart and classic?
Because my goal in this article was to higlight the main issue that Iterator solves in such manner that it could be easily understandable. And second reason is that you can read tonns of standard explanations of this Design Pattern.
Main difference between my explanation and others is that classic explanation is more abstrated, it contains abstract Iterator which represents interface for concrete ones, and abstract Aggregate, which creates Iterators needed.
The way I created Iterator looked like
But generally this logic could be hidden under some Aggregate’s method (like GetEnumerator in .NET). For example I could have this:
In .NET world we have IEnumerable<T> and IEnumerator<T> interfaces which provides a lot of help in impementing this pattern:
In Java we have java.lang.Iterable instead of IEnumerable, which is more intuitive naming. I think that Microsoft just wanted to be original in this :).
February 10, 2010 Success, Ukrainian 4 comments
This post is in Ukrainian and is translation to the Things you need to remember to become successful developer
1. Не переставайте вчитися
Я припускаю, що ви навіть б не читали цей пост, якщо б не мали хоча б елементарної освіти, і ви б навіть не хотіли знати як стати успішним програмістом без вищої освіти. То ж якщо ви зараз програміст навіщо зупинятися вчитися?
Це просто недозволено. Одна важлива річ тут: Стояти на одному місці не означає, що ви стоїте на місці – це означає що ви рухаєтеся назад. Просто рухатися вперед не означає що ви рухаєтеся вперед – це лишень означає, що ви не загубилися із невдахами десь в кінці. Щоб просуватися вперед вам слід вчитися постійно – не просто рухатися, а БІГТИ.
Ось мій короткий список, що підпадає під цей пункт:
• Читайте книги
• Підпишіться на RSS і читайте різні статті
• Пробуйте різні мови програмування і речі, про які ви чули
• Ходіть на семінари і готуйте власні презентації
• Вчіть будь-що, що може вам допомогти просуватися
• Вчіть інших, так як це вчить вас
2. Визначте вашу ціль і тримайтеся правильної дороги
Я думаю що важко бігти якщо не знати куди бігти. Основне завдання полягає в тому, щоб чітко уявляти свою ціль. Ваша ціль повинна бути довготермінова і велика. І після того як у вас вже є бачення своєї мети візьміть і розбийте її на дрібні завдання – тобто побудуйте свою карту до успіху. Вам слід скласти список завдань, які ви ПОВИННІ виконати за місяць, або за рік. Як тільки ви його маєте, просто чітко слідуйте за ним.
3. Будь-які проблеми є можливостями
В буденній роботі ви завжди стикаєтеся із різними траблами. Ви отримуєте нові завдання або звіти про баги від тестерів. Ви отримуєте нові проекти від Проджект менеджерів. Ваш співробітник запитує про допомогу. Вам потрібна допомога. Це все приклади проблем. І справді важливе питання тут таке: як ви зустрічаєте їх? Ви можете сказати «Ой, але так я не позбавлюся від дурної надоїдливої роботи». Ви тут абсолютно не праві. Запам’ятайте, що ваші боси будуть раді дати вам більш складну роботі як тільки побачать, що ви справляєтеся із поточними завданнями.
4. Будьте позитивно налаштовані
Ви повинні дивитися на все позитивно. Якщо ви виявили, що зробили помилку просто сприйміть це легко – кожен робить помилки. Вам подобаються люди, які ниють коли у них проблеми? Як ви думаєте ви будете виглядати у чужих очах, якщо ви скажете: «Так, хлопці, я це зробив – я це вирішу, дайте мені хвилинку» і опісля ви повертаєтеся і починаєте фіксати вашу помилку із усмішкою на лиці. Як тільки ви вирішите проблему ви будете просто щасливі.
Ваша дорога є хорошою і ви швидко рухаєтеся вперед. Ніколи, ніколи не думайте що ви не досягнете своєї цілі – ось суть цього пункту.
5. Знайдіть наставника
Це не означає, що вам потрібна людина, яка буде вам допомагати робити вашу роботу – бо це просто вчитель або ж більш досвідчений розробник. Це означає що вам потрібна людина, яка знаходиться там, де ви хочете бути. Вам потрібно брати приклад із цієї людини. Якщо ця людина недостатньо високо – просто знайдіть когось по серйозніше. Також майте друзів які будуть вам допомагати рухатися по шляху. Або просто користуйтеся підтримкою жінки або дівчини.
6. Ставайте відомими
Якщо ви не покажете іншим, що ви крутий і що ви заслуговуєте більше, як вони будуть про це знати? Є просте рішення – почніть вести блог, запитуйте і відповідайте на питання, переконайтеся що гугл знає вас. Поширюйте своє знання у вашій команді і на проекті. Якщо ви вивчили щось нове, то чому б не поділитися цим? Ви забудете ці нові речі, якщо ви не будете їх пробувати.
7. Слідкуйте за виконанням ваших завдань, будьте певні, що ви й досі на шляху
Час від часу слід перевіряти чи ви робите все правильно. Впевніться, що ви виконуєте поставлені задачі. Якщо ні, то швидко знайдіть причини і працюйте над ними. Знайдіть свої слабкі сторони і змагайтеся із ними. Це може звучати смішно, але я знаю хорошого програміста із добрими теоретичними знаннями, але його швидкість набору коду просто жахлива. Чому? Тому що в нього просто жахлива клавіатура і він не хоче провести 10-20 годин за тренажером. Хіба це не тупо? Друже, якщо ти будеш читати цю статтю, пообіцяй що ти переможеш цю слабинку.
8. Робіть гімнастику
Я зробив маленьке само-опитування, коли писав цю статтю. І «Робіть гімнастику» попало у список. Я є досить молодий і проводжу забагато часу за ноутбуком і за іншою машиною на роботі і я не можу заставити себе робити гімнастику. Але це як точіння леза. Є така історія про двох дроворубів які поспорили про те хто зрубає більше дерев. Один дроворуб був здоровий і великий, а інший худий, як я. Сильний був певен, що він переможе, оскільки він рубав дерева всі 8 годин без жодної перерви, а худий робив перериви на 15 хв. кожної години. Але боротьбу виграв худий – він зрубав 150 дерев тоді коли Силач зрубав 100. Секрет полягав у тому, що він точив лезо тоді коли відпочивав. Ваше здоров’я – це ваша сокира і якщо вона буде тупа ви не зможете вирубати собі дорогу до успіху.
Тому нехай всі ваші сокири будуть заточені!
February 3, 2010 NHibernate No comments
I have table CUSTOMER where CUSTOMER_ID is primary key.
Table
Mapping
I need to handle assigning of the CustomerID property manually. For
example I created new Customer with CustomerID = 777 and Name
= “Andriy Buday”.
When I call method Session.Save(customer);
I want NHibernate to generate me SQL like this:
Unfortunately I’m getting errors.
Main issue here is that Nhibernate tries to generate ID for me. But I want to save my entity exactly with 777.
Solution
So I need to manually setup my ID property with adding GeneratedBy.Assigned();
Like here:
February 1, 2010 English, Success 5 comments
Point 6 in my Where Do You Want to Be In a Year? is:
“Improve my English skills to have at least upper-intermediate strong level (according to my company graduating)”
Previous Level: Intermediate
Last year my level was evaluated as Intermediate, but since that time I had a lot of experience of communication with native speakers. So I was pure much sure that my language is improved. I requested reevaluation, which occurred last week.
How was it?
I’ve drank too much coffee before came for my reevaluation, so my voice was a bit hoarse. Not a plus.
We spoke a bit, I mentioned about that I requested this reevaluation and why do I need that. Then she gave me feedback and proposed me to pass some test.
Feedback
Before test she said that my English level is not upper-intermediate definitely :( , and she explained why:
1) I repeated same words to much.
2) I do not use enough adjectives.
3) My speech is not fluent.
For upper-intermediate my English should be fluent!
Exercise for me
When I speak I should think not only about what I speak, but also how I speak.
Result
Current Level: Intermediate Strong
English courses
Also, I’m eligible for English courses in my company, so I moved to upper-intermediate course. This means that course could improve my skills to that level, of course if I’ll be a good student. I really need this study, even if it will be taking some time. I know that to compel myself learning that alone will not succeed. I’ve decided that course will help me with this just fine.
I’m on the way to have desired level of English, so will learn hard to have
Future Level: Upper-Intermediate Strong
January 30, 2010 MasterDiploma 1 comment
It’s time to start seriously work on my Master Diploma.
What about is my Master Diploma work?
In Artificial Intelligence we often use neural networks in try to simulate aspects of the biological neural networks. Applicability of these is very wide, it could be smart unit in some video game, or expert subsystem when diagnosis patient. Even your inbox e-mails are filtered with algorithm, which includes neural networks usage.
One great applicability of Self-Organizing Maps (one of the artificial neural networks) is possibility to analyze high-dimensional data, save its topology and translate it to low-dimensional representation which further could be easily analyzed by human brains.
For human being it is hard to work with dozens of input information for different aspects of one thing. For example 100 patients being diagnosing and for each we need 30-40 different measurements. SOM could easily classify data and for output with knowing of some existing diagnosis we can get “Patient – Diagnosis”.
I mentioned something like “with knowing of some existing…”. This means that SOM requires training, which takes execution time. If our application domain is something for military, time could be critical constraint.
In this work I’m going to significantly improve calculations of Self-Organizing Maps with introducing multi-threading improvements.
Project hosting
I already hosted my project with google code:
http://code.google.com/p/andriybudaydiploma/
Project is host for implementation of a parallel algorithm, purpose of
which is to significantly improve calculations of standard algorithm.
This is main goal of actual project.
This project represents Andriy Buday’s Master Diploma work.
e-mail me: andriybuday@gmail.com
What do I need to accomplish?
I need to ensure that I understand computations of SOM deeply.
Research over interned for similar works and take them into account.
I’ve decided to write my code from scratch, since I already have some implementation of SOM.
After I’ll have some implementation I need to analyze results I got on different systems.
Improve my knowledge of Java, Concurrency and train my scientific habits. :)
This blog and my Diploma
I was thinking about posting status of my work on Diploma on separate blog or site, but don’t want to have myseft scattered over different locations, so I’ve decided that just tag “Master Diploma” should be enough. I don’t think that it could make sense to hide something from the world or my co-workers or Customers (don’t even think they read my blog). And of course my Diploma is part of my Road To Success.
Please, wish me luck on this!
No doubt I will do the best to take my work to the breakthrough.
January 29, 2010 Design Patterns, Java No comments
Imagine that you have shop where your Customers could buy Laptops with configuration they prefer. You need to develop system which will allow you easily build any configuration of Laptop for any User.
How could you easily accomplish this?
Builder is Creational Design Patter which allows you build some whole Product (Laptop) by constructing together some parts like Processor, Memory, Monitor, HDD, Battery and so on.
So your employee talks to Customer and asks questions which memory do you want and so on. Or otherwise if Customer is not technic, employee could ask “Do you need this laptop for gaming?”.
So you need some steps to construct you computer and they are defined in Abstract Builder.
public Laptop getMyLaptop(){
return laptop;
}
//mentioned steps to build laptop
public abstract void setMonitorResolution();
public abstract void setProcessor();
public abstract void setMemory();
public abstract void setHDD();
public abstract void setBattery();
}
If your Customer answers like “Yes, I wanna play… play…!!!“. You already have implementation of Concrete Builder for gaming laptop like:
Or if you Customer is business guy and he watches presentations and exel reports in plain:
To manage steps to build your Laptop basing on the answer you need Director:
Here we have usage code.
BuyLaptop shopForYou = new BuyLaptop();//director
shopForYou.setLaptopBuilder(gamingBuilder);//Customer answered that he wants to play
shopForYou.constructLaptop();
Laptop laptop = shopForYou.getLaptop();//just get what he wants
laptop.print();
Output:
Easy, simple and great pattern.
What have I learned regarding of Java?
Nothing special, just how to format strings:
January 29, 2010 Book Reviews No comments
Domain Driven Design by Eric Evans is one of the books that every architect must read if he wants to develop really extensible enterprise level application, which absorbs knowledge of the problematic domain.
Book talks about Ubiquitous Language which is the language between Domain Experts and Developers and helps them build model of the application.
Once you have this language you could easily start build your model with Entities and Value Objects, making Associations between them and other elements of the system. Then you use Services to apply operations on your domain. To interact with Infrastructure you need Repositories and Factories, this makes Persistace Ignorance Layer to hide and isolate your model from technical impacts of your infrastructure.
Refactoring Toward Deeper Insight plus Distilling of model takes your system to the breakthrough. If you have clear model, future Developers could easily work with it addin new functionality and speaking with Customer on common language they will know it, because code raises it to them.
This is one of most valuable book I’ve ever read!