Csabi's blog

Software Craftsmanship, Agile, and other Ideas about Programming

Subscribe to RSS feed

Sticky post

Books I Read about Programming

, , , ...

Now Reading

Writing Effective Use Cases
I expect this book to be very educative with a highly applicable content.
The book on amazon...





The Art of Unix Programming
This is a book of why and not how in programming, and more precisely why are programs made the way they are in the UNIX world. The book starts with a short history of UNIX, continued by a series of concrete, real world examples and the motivation behind their design. This is a must-read for any programmer, not just UNIX / Linux programmers.
Read the book online or order it here...


Read more...

CD DVD Tray won't Stay Open

In case your system decides to not keep you CD/DVD tray open so you cant put/remove disks, and the button on the device doesn't work either....
dev.cdrom.autoclose = 0
dev.cdrom.lock = 0
Put the above lines in /etc/sysctl.conf and then reload the file with
# sysctl -p

Thunar Send to BlueTooth Device with ObexFTP

, , , ...

Pair your computer with your device using whatever BT manager your system has. Make sure you have obexftp installed, than create a new "Send to" file for Thunar and put into it something like this:
[Desktop Entry] 
Type=Application
Version=1.0 
Encoding=UTF-8 
Name=Bluetooth Send to LG Viewty 
Icon=bluetooth 
Exec=/usr/bin/obexftp -b 00:00:00:00:00:00 -p %f
Replace 00:...:00 with your blue tooth device's address (use "hcitool scan" to find it)Save the file to ~/.local/share/Thunar/sendto/Your-Great-BT-Script.desktop

Easy Way to AutoLogin into X on Sabayon Linux

, , , ...

So, it took me 3 days to find this very simple solution for an auto login into X on Sabayon Linux.

Install SLiM Simple Log-in Manager
equo install slim

Set xdm to use slim by modifying /etc/conf.d/xdm
DISPLAYMANAGER="slim"

Make sure xdm starts at default level
rc-update add xdm default

Change /etc/slim.conf to select a default user and log in automatically. Find and modify the following lines:
default_user        your_user_name_here
auto_login          yes

Also change the login method to use ~/.xinitrc in the same /etc/slim.conf file
login_cmd           exec /bin/sh - ~/.xinitrc %session

Make sure your ~/.xinitrc starts the proper DE. I am using Enlightenment E17, and I have this single line in my .xinitrc
exec /usr/bin/enlightenment_start

That's all. Now reboot to see it in action.

Ruby's Watchr Configuration for ShUnit2

, , , ...

require "erb"

watch('tests/.*Test\.sh') do |md|
  clear_console
  run "#{md[0]}"
end

watch('source/(.*)\.sh') do |md|   # runs test when source code changes
  clear_console
  testpath = "tests/" + md[1] + "Test.sh"
  run "#{testpath}"
end

def clear_console
  puts "\e[H\e[2J"  #clear console
end

def run cmd
  result = `#{cmd} 2>&1`
  if result.match(/FAILED\s+\(failures=/)
    notify_failed cmd, result
  elsif result.match(/ERROR/) or result.match(/command not found/)
    notify "#{cmd}", result, "pending.png", 6000
  elsif result.match(/\nOK\n/)
    notify "#{cmd}", "<font size=4 color=lightgreen><b><i>Tests Passed Successfuly</i></b></font>", "success.png", 1000
  else
    notify "#{cmd}", "Unknown error: 
" + result, "pending.png", 3000
  end
  puts result
end

def notify_failed cmd, result
    ft = result.match(/.*(test.*)\nASSERT:(.*?)\n/m)
    first_failing_test = defined?(ft[1]) ? ft[1] : "no match"
    first_failure_message = defined?(ft[2]) ? ft[2] : "Critical"
 
    notify "#{cmd}", "<b>" + first_failing_test + "</b> failed!\n" +
      "<font size=3 color=pink><b><i>" + ERB::Util.html_escape(first_failure_message) + "</i></b></font>", "failure.png", 6000
end

def notify title, msg, img, show_time
  images_dir='~/.autotest/images'
  system "notify-send '#{title}' '#{msg}' -i #{images_dir}/#{img} -t #{show_time}"
end

Using Ruby's Watcher for Continuous Bash (shUnit) Testing

, , , ...

So, did you ever TDD a Bash script? ... Very well, I thought so. But, what about continuous testing with shUnit? You know, the cool automatic tests we run when programming in Ruby wink

Yeees! You can do that with any language with the help of Ruby's Watchr gem. If you are on Linux, you will want libnotify also. So, how do you do it? Take a look at the script below, adjust the parameters to your needs and run watcher like this: 'watchr autotest_file_you_just_wrote'

watch('tests/.*Test\.sh') do |md|
  clear_console
  run "#{md[0]}"
end

watch('source/(.*)\.sh') do |md|   # runs test when source code changes
  clear_console
  testpath = "tests/" + md[1] + "Test.sh"
  run "#{testpath}"
end

def clear_console
  puts "\e[H\e[2J"  #clear console
end

def run cmd
  result = `#{cmd}`
  if result.match(/No tests failed/)
    notify "#{cmd}", "<font size=4 color=lightgreen><b><i>Tests Passed Successfuly</i></b></font>", "success.png"
  else
    first_failing_test = result.match(/^.*:\s+(.*)\s+E/)[1]
    first_failure_message = result.match(/^(.*)failed/)[1]
    notify "#{cmd}", "<b>" + first_failing_test + "</b> failed!\n" +
      "<font size=4 color=pink><b><i>" + first_failure_message + "</i></b></font>", "failure.png"
  end
  puts result
end

def notify title, msg, img
  images_dir='~/.autotest/images'
  system "notify-send '#{title}' '#{msg}' -i #{images_dir}/#{img} -t 3000"
end

Have fun smile

Ruby Plasmoid and Qt::Timer (time events)

, , , ...

In the past couple of days I was working on a simple plasmoid for KDE and my NVidia video card. This time it is written in Ruby.

However I had a big problem. I lost more than a day to figure out how to use a timer in Ruby in a plasmoid. There are several tutorials and examples out there but all I could find is outdated and not working. Finally, I found a working ruby plasmoid and adapted a solution from it. It is, as everything in Ruby, more simple than anyone would expect. So, here it is.
In your 'def init' write this:
@refresh_interval = 10000
start_timer(@refresh_interval)

And than define a timer event:
def timerEvent(event)
	# your code to be run every @refresh_interval miliseconds
end


My plasmoid can be found on kde-look:
http://kde-look.org/content/show.php/Simple+NVidia+Info+v2?content=147669

A Couple of Words. The Pragmatic Programmer

Now Reading

So I started reading The Pragmatic Programmer about a month ago, but I did not write about the book yet. It is an interesting reading. The book was written a couple of years before Agile and it reflects the techniques and ideas of late '90s. I can't keep not comparing it with The Clean Coder.
Both books talk about similar things. About how should professional programmers behave, work and live. The Clean Coder is more person oriented, more team oriented, it's more about 'sentimental' principles. On the other hand The Pragmatic Programmer is more about programming. Many of the principles and techniques presented in the book are common knowledge our days, but back in 1999 it was like Agile and Clean Code is today.

So, even if the information is more than 12 years old it is still valid and the book is a joyful reading.

Fun Day Testing Views

So, what (how) do you test when you test views? It is easy to find a lot of technical information about how do you test a view in Rails. You can find so many code and examples that you do not even know where to start. This is good, but there is a problem.

Which parts of a view should you test? This is a much harder question and there is no general answer for it. Me and my colleagues had a long talk about this and we concluded 3 main ideas:
  1. test only conditionally shown parts of a view (this includes text shown dynamically from objects or variables)
  2. do not test for HTML tags or CSS selectors (only in special circumstances)
  3. always try to match a text that should be visible

These 3 simple principles led us to much clearer views, conditional rendering being extracted in helpers and method calls tested on views. You almost can read a view as well written prose.

Extracting 'render' statements into helpers also helps a lot. You can test the call in the view to the appropriate helper method. Then, you can test the helper and check that the method calls 'render' with the desired parameters. Unfortunately you can't directly test a call to 'render' in a view. This is an intensional limitation of RSpec 2. But, this is, after all, a good thing. It forces you to decouple any logic, including render and partial render logic, in the views. Any other view can this way use the helper and render all that stuff easily ... also some code duplication is reduced.

Code Retreat was Fun!

, , , ...

Last Saturday (3rd Dec 2011) there was the Global Code Retreat. It was my first participation on this event and I very much enjoyed it. It was one of the best coding days of my life. I never thought that coding just for fun with a bunch of strangers can be so much fun and also educational.

What is Code Retreat:
http://coderetreat.com/

Romania was the first non US country to hold a Code Retreat, in may-june 2009:
http://photos2.meetupstatic.com/photos/event/8/9/6/e/highres_75515182.jpeg

What Makes a Program Object Oriented?

Many may argue, but the most important thing that makes a program really object oriented is the "Dependency Inversion Principle". If you do not invert your dependencies you are just writing traditional procedural code "masked" within classes and objects.
Inverting dependencies is not enough but it is necessary for any application for it to be truly object oriented.

Dependency Inversion Principle:
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.

More details:
http://www.objectmentor.com/resources/articles/dip.pdf
http://www.oodesign.com/dependency-inversion-principle.html

Ruby or not Ru-(be)

It is one week since my first contact with Ruby (and with Rails), and it is time for some first impressions.
As every beginning, this one also was hard. Ruby is so different from what I've used so far, but that does not mean it is bad. In fact Ruby is quite nice. What I have problems with is Rails. First I had to better understand the whole concept of MVC, than learn the conventions, then discover all the "magics" Rails do for you. Unfortunately this is a very steep learning curve and with very little results at the beginning. For example, it can take days just to figure out how to output a form with nested attributes. Of course, I could hardcode it in 30 minutes, but that would defeat the point.

Another dilemma is what IDE to use for Ruby and Rails? First of all, let's point out that editors are not IDEs.
If you are looking for Ruby editors, TextMate, Vim, Komodo pops up as first choices.
However I was looking for IDEs, where I have advanced features, refactorings, unit testing support and so on. There are only a few cross-platform solutions: Ecplipse + some plugins, Aptana for Ruby (based on Eclipse), NetBeans + RubyPlugin, RubyMine from IntellyJ.
Now, each of these has it's pros and cons. Ecplipse and Aptana are quite strange and with hard to change presets which makes you loose a considerable amount of time for setup. Also Eclipse based IDEs are pretty slow. The effective Ruby and Rails support is good, though.
RubyMine is the most advanced IDE I've found, unfortunately it has 2 major drawbacks: it does not run well on OpenJDK (note that even Sun recommends OpenJDK on Linux instead of the sunJDK) and it is commercial (it has a $99 price, which is pretty fair).
So, I ended up with NetBeans (again) and Ruby plugin. This one is the best I could find, the only (temporary) problem is that the plugin is not yet ready for NetBeans 7.1 which in turn is in RC state at the moment of writing this post. As far as I know there is some work going on to port the Ruby plugin to the new NetBeans 7.x API and it should be available in the near future, let's hope it will be there when 7.1 will be released.

Programmers Should Use the SHELL

After all, can't you do everything equally well by pointing and clicking?
The simple answer is "no". [...] A benefit of GUIs is WYSIWYG - what you see is what you get. The disadvantage is WYSIAYG - what you see is all you get.

The Pragmatic Programmer, by Andrew Hunt and David Thomas

Programming is not Easy

Programming a computer does require intelligence. Indeed, it requires so much intelligence that nobody really does it very well. Sure, some programmers are better than others, but we all bump and crash around like overgrown infants. Why? Because programming is by far the hardest intellectual task that human beings have ever tried to do. Ever.


- Gerald M. Weinberg, Understanding the Professional Programmer by Gerald M. Weinberg , ISBN: 0932633099 , Page: 11

Always write your code S.O.L.I.D.

You should always write your code with S.O.L.I.D. in mind. Probably no programmer can achieve perfection but that doesn't mean you should not try to. Be a purist and code that respects these principles:
Single Responsibility
Open / Close
Liskov Substitution
Interface Segregation
Dependency Inversion

Thanks to the inventor of S.O.L.I.D., Robert C. Martin, any code can become much better by respecting just five simple principles.

One more interesting thing I've learned from Evans' book

Developers should talk a lot. Both with each other and with domain experts. If they are also experts in the domain they develop for, they should talk even more. The lack of an ubiquitous language can lead to very strange designs. And I am not talking about complex enterprise designs. The impact on those could be catastrophic. I am talking about small design decisions like naming classes or methods or even variables.
It doesn't matter if the programmer named all those tiny variables with good intention and of he's best understanding of the domain. They may even be named perfectly correct. But if the other programmers do not understand the names or they have a different view about the things that should happen in that particular part of the code, it can lead to much confusion and frustration.

So, talk with you colleagues and with you domain experts. Talk to them all the time until all of you are talking the same language and all of you understand the same things by the same words / expressions.

Language Hopping. Is it Possible?

Lately I've read and saw a few times that a good programmer, with enough experience should be able to relatively easily start programming in a language he/she doesn't know.
So, to test my abilities, last week and over the weekend I did some coding katas in Java. I never programmed anything more complex than a "Hello World" in Java, but it was really easy to do the TennisKata, it was ready in less than 2 hours. Than I did a couple of more katas, just for fun. (hmm ... never finished the MineSweeper Kata).

So, at least for simple things, the programming language is irrelevant. Learning the intricacies of a language is a totally different thing though. Also I fully agree with Robert Martin when he says that it should take about a week to get used with a language, about another 3 weeks to get used with the tools and after a month a professional programmer should be able to be productive in any language and tool.

Can I do that? I have no idea, probably not, yet, but it would be a curious exercise to do.

Extranct Method (Introduce Method) Macro for NetBeans PHP

I miss some refactoring in NetBeans PHP, one of them is the Extract Method or Introduce Method refactoring already present for Java. So I figured I will write one in NetBeans' macro language. This is a very limited language and the resulted macro also does just a limited version of the extract method. There is no way for me to guess variables, parameters and return values, but still, this macro will take the selected text and create a private method for it just below the current method. You will have to rename it.

cut-to-clipboard
"$this->UNNAMED_METHOD();"
collapse-fold
caret-end-line caret-backward caret-end-line insert-break
"private function UNNAMED_METHOD() {"insert-break
paste-from-clipboard insert-break

Why should you read DDD?

Recently some of my colleagues and I were talking about Evans' book, Domain Driven Design. As we work at a small company where the challenges of huge and complicated designs are inexistent we started to identify the principles from the book we can apply in our daily jobs. So, here is a list why you should read this book even if you are not working in an big enterprise environment:
  1. A unique perspective about some common design patterns like Repository and Factory
  2. The "Specification" design pattern invented by Evens and Fowler can and should be applied in many applications
  3. Objects are categorized in an interesting way: entities, value object and services. Understanding these will change the way you see the code.
  4. "Aggregates", a design pattern to decouple modules or groups of logically dependent classes and encapsulate functionalities of several objects. Very interesting even if it is hard to implement in certain programming languages.

Capace de canal = mission impossible

Vroiam de mult sa scriu asta dar mai mereu uitam...

De ce nu sunt in stare romanii sa puna capacele de canal la nivelul drumului / asfaltului?

Recent s-a reasfaltat calea Lipovei (Timisoara). Evident dupa aceea toate capacele de canal erau cu 5-10cm sub nivelul suprafetei de rulare.

A urmat o operatiune complexa de ridicare a capacelor ... acum sunt cu 2-5cm mai sus decat ar trebui.

Si asa a decis UE sa platim tot noi datoria bancilor...

De ce e criza de 2 ori mai greu pentru oamenii de rand? Raspunsul este simplu:
1) Cand a inceput criza, din banii nostri au fost "salvati" prin imprumuturi bancile si firmele de asigurari si alte companii cu o conducere inconstienta.
2) Tocmai s-a dat o lege, fiecare tranzactie bancara din UE va fi taxata si bancile va trebui sa plateasca. Sau mai precis, fiecare dintre noi, la fiecare tranzactie va plati o parte din datoria bancilor.

Rezultatul? Simplu, nu numai ca noi, oamenii de rand, platim pentru criza dar o facem de 2 ori.

Opera's javascript engine rocks!

Here are some result for the ECMAScript Test262 on 64bits Linux (Mandriva 2011):

Opera:

 Tests To Run: 10927 | Total Tests Ran: 10927 | Pass: 10926 | Fail: 1 | Failed To Load: 0

FF5:

Tests To Run: 10927 | Total Tests Ran: 10927 | Pass: 10670 | Fail: 257 | Failed To Load: 0

Chrome 13 stable:

Tests To Run: 10927 | Total Tests Ran: 10927 | Pass: 10444 | Fail: 483 | Failed To Load: 1

... si te mai intrebi de ce nu umbla lumea cu biciclete si role

Astazi a fost o premiera. Considerand ca era ziua inceperii anului scolar m-am hotarat sa-mi las masina acasa si sa ma duc la service cu role.

Proasta decizie sad

Desi unele trotuare sunt acceptabile, drumul pana la servici este un chin si plin de surprize. De exemplu ma gandeam sa traversez calea Lipovei la un semafor cu buton pentru pietoni. Fiind pe role si cu echilibrul mai imperfect, mi s-a parut cea mai sigura solutie. Macar cand traversez sigur nu trece nici o masina (la intersectii stiti si voi cum e cu verde simultan pentru masini si pietoni). E... asa, cu ideea pornita ma apropiu de trecere cand observ ca stalpul pe care e butonul e la vreo 2 metri de trotuar. Cu alte cuvinte trebuie sa iesi efectiv de pe suprafata asfaltata, sa te calci pe pamant (sau noroi daca ploua) ca sa apesi butonul pentru a face semaforul verde. Desigur, cu role pe pamant si pietrisi e un efort semnificativ de echilibristica.

Reusit, cu chiu-si-cu-vai, plus vreo doau priuete, se facu verde si traversat cu succes.

Mai departe spre Mall, pe partea dreapta a caii Lipovei. Trotuarul relativ bine asfaltat dar copacii lasati sa creasca pe unde vor. In multe locuri distanta pana la crengi e pe la 1.5metri ... cam greu cu rolele in aceste parti.

Dupa aceea au mai urmat vreo cateva sute de metri cu trotuar dezastru (zona centrului vechi), cu trecei de pietoni unde nici o masina nu incetineste sa poti trece si cu drumul la vreo 2 benzinarii spart deci traversarea pe role aproape imposibil (si mergand pe jos ar fi fost dificil).

Concluzie: poluare sau nu, la lucru cu masina, in parc cu rolele. As vrea eu sa protejez natura, dar nici sa-mi pun viata in pericol pentru asta.

Mandriva 2011 “Hydrogen” is out! | Mandriva Blog

Mandriva 2011 “Hydrogen” is out! | Mandriva Blog
Official announcement:

Hooray! As promised earlier, we are happy to announce that Mandriva 2011 is out. [...]

Angry Birds on a physics exam

Angry Birds on a physics exam

 

Via BoingBoing