Author Archives: stefanhendriks

Stuff I’ve learned #03

Another week has passed:

  • Unlike in Windows; in Chrome you cannot easily focus on your bookmarks bar with a keyboard short key on Mac OS X.
  • If you want to run rake tasks in your specs in a before block, be sure to set a line[code language=”ruby”]Rake::Task[name].reenable[/code]

    so you can re-execute them every time. Rake seems to remember which task has been executed, so you cannot execute it twice.

  • If you want to stub out STDOUT messages (like with ‘puts’) in your spec, use:[code language=”ruby”]STDOUT.stubs(:puts)[/code]
  • When in doubt, speak up. Always.
  • With Scrum, big stories are big risks. Split them up.
  • Don’t use PID files to remember which proces has been started and when it should be stopped. Especially if you want to reboot a deamon process automatically once it has died. Instead wait for it when the deamon has quit and act upon a not-normal exit code.
  • Sometimes using ‘git fetch -p’ is not enough to prune all your local branches (which do not exist anymore on remote). You can use a rather long command (see below, from stackoverflow question)[code language=”shell”]git branch -r | awk ‘{print $1}’ | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk ‘{print $1}’ | xargs git branch -d[/code]
  • With editorconfig (*) you can create code formatting rules, nothing new here, but editorconfig has plugins for a lot of known editors, (I tested it in Vim & Sublime), meaning you can now share these rules cross-editor. Now that is cool!
  • With C++, when your function argument is using const, and you’re calling a non-const function on that argument you will end up with a message like:

    “error: passing ‘const xxx’ as ‘xxx’ argument of ‘function you where trying to call on xxx’ discards qualifiers”.

    You can fix this by telling the function body is const:

    [code language=”cpp”] bool myFunction() const { /* code here */ } [/code]

* Thx to Arjen about editorconfig.

Stuff I’ve learned #02

Some time has passed, and I’ve learned new stuff again:

  • Updating a single gem is not done with ‘bundle update <gemname>’ but in fact with ‘bundle update –source <gemname>’. See this post for more info on that.
  • Mailbox (iOS) is a really neat mail program. I really love this ‘remind me later’ stuff which keeps my mailbox clean and keeps me from writing these reminders myself in the Calendar app.
  • With CTRL-F2 you can get focus on the menu bar in any mac app. (more keyboard shortcuts here)
  • With JSONLint you can easily verify JSON.
  • In Ruby you can actually create a Hash using brackets with key, value order. Ie like: Hash[“myKey”, “value”, “myOtherKey”, “myOtherValue”]. The [] is a class method.
  • I am really happy that we spent time creating a ‘load dump from environment X into my dev environment’ so we can easily test migrations and fix lots of bugs beforehand (instead of having to solve issues while deploying to an environment).
  • When using ZShell and you want to issue a rake task you cannot pass parameters with [] (ie rake myjob[someparam] won’t work). You need to use single quotes around the jobname + its parameters. Ie: rake ‘myjob[someparam]’ works.
  • You can download free, legal, VM’s to test IE versions on different versions of Windows (here)
  • You can create your own events with SDL using User events., as is done here
  • The Global Day Coderetreat 2013 will be held at the 14th of December and we (at Zilverline) host one!

Thx to Sander for his tips about MailBox and ZShell.

Stuff I’ve learned #01

I am learning so much every day at Zilverline, and I’d really like to write them down some time and share. Mostly just because this way I can summarise what I’ve learned and carve it into my brains.

And it also gives me the chance to show you how awesome it is to be creating software at Zilverline.

See more conversion options in preview in OS X 10.8

See more conversion options in preview in OS X 10.8

Lets say you have a file (image.png) and you want to convert it to a BMP for whatever reason. It seems in OS X 10.8 you can still do this, but the options are a bit hidden.

This link gives the hint to do this. Within preview you need to hold the “option” key first so you can choose “save as”. After that you still need to hold the option key when you use the ‘format’ dropdown so you can select the BMP format. If you don’t do this, you will not see the BMP format.

Worst Commit – Ever

Got this via a friend and had to share this with you…

Ever heard of Bumblebee? Well I thought it was about this guy:

Apparently it wasn’t, in this case.

In fact, I still don’t even know what piece of software it is, but I do know about one of its most famous commits on github now.

This commit is very small, yet makes a very big difference for the user…

If you want to have a laugh see the commit yourself, and then all the comments, they are hilarous.

Ok, one teaser:

Still reading…?

Terminal: Show git branch, changes, RVM ruby version, gemset.

I was looking for a way to easily print the current gemset I am in when working in the terminal. I found a stack overflow post, but it did not really satisfy me. With some googling I also found this post.

I modified the script a tiny bit (color preferences + added __git_ps1 to detect branch) and would like to share you what I’ve got.

This is the complete script I use now, copy & paste if you like.

The result looks like this:

terminal

[sourcecode]
# This shows the git branch of the current directory
function __git_ps1 () {
git branch 2> /dev/null | sed -e ‘/^[^*]/d’ -e ‘s/* (.*)/ (1)/’
}

function __git_dirty {
git diff –quiet HEAD &>/dev/null
[ $? == 1 ] && echo " (changes!)"
}

function __git_branch {
__git_ps1 " %s"
}

function __my_rvm_ruby_version {
local gemset=$(echo $GEM_HOME | awk -F’@’ ‘{print $2}’)
[ "$gemset" != "" ] && gemset="@$gemset"
local version=$(echo $MY_RUBY_HOME | awk -F’-‘ ‘{print $2}’)
[ "$version" == "1.8.7" ] && version=""
local full="$version$gemset"
[ "$full" != "" ] && echo "$full "
}

bash_prompt() {
local NONE="[\033[0m]"    # unsets color to term’s fg color

# regular colors
local K="[\033[0;30m]"    # black
local R="[\033[0;31m]"    # red
local G="[\033[0;32m]"    # green
local Y="[\033[0;33m]"    # yellow
local B="[\033[0;34m]"    # blue
local M="[\033[0;35m]"    # magenta
local C="[\033[0;36m]"    # cyan
local W="[\033[0;37m]"    # white

# emphasized (bolded) colors
local EMK="[\033[1;30m]"
local EMR="[\033[1;31m]"
local EMG="[\033[1;32m]"
local EMY="[\033[1;33m]"
local EMB="[\033[1;34m]"
local EMM="[\033[1;35m]"
local EMC="[\033[1;36m]"
local EMW="[\033[1;37m]"

# background colors
local BGK="[\033[40m]"
local BGR="[\033[41m]"
local BGG="[\033[42m]"
local BGY="[\033[43m]"
local BGB="[\033[44m]"
local BGM="[\033[45m]"
local BGC="[\033[46m]"
local BGW="[\033[47m]"

local UC=$W                 # user’s color
[ $UID -eq "0" ] && UC=$R   # root’s color

PS1="$M$(__my_rvm_ruby_version)$Wh$W:$EMGw$EMC$(__git_branch)$EMW$(__git_dirty)${NONE} $ "
}

bash_prompt
unset bash_prompt
[/sourcecode]

Compiling Stratagus on Mac OS X (10.8.2)

I loved playing Warcraft 2. I played it on DOSBox recently, but the fact that 640×480 is just plain ugly on my MPB these days made me look for alternatives.

And so I found Stratagus and Wargus.

With Stratagus as engine, Wargus as “MOD” and with the original Warcraft 2 CD you can re-live Warcraft 2 again on your machine.

On Windows you should be able to install this without any problems, installers are provided and these work just fine. However, on a Mac you might be in some hassle to get this working. In fact, there is no official support as none of the authors run a Mac. Basically this means people with Macs had to figure out how to do this. After some time of googling I got Stratagus compiling and working with a Wargus game I already created on Windows.

Fortunately someone at github already made a version that should work on Mac OS X. Combined with a tutorial I found elsewhere I got it to compile. I can play Wargus now on my Mac!

For completeness sake I have combined the steps I have taken (and also forked Stratagus) so you can use that version. Don’t credit me for making Stratagus compile on the Mac though, as I did not make the nescesary changes in the makefile or code.

Install Xcode (from App store) & Install command line tools from Xcode

in Xcode, go to preferences, tab "Downloads" -> " Components" -> Command Line Tools
  • – The command line tools should have installed git and svn for you, try them out:
hit "svn --version", and "git --version" in your terminal.
If they are not installed, you could install them via homebrew (brew install git && brew install svn) (after you installed Homebrew of course)

Install homebrew

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go

Installing required dependencies

I have installed the following dependencies with homebrew like this:

brew install cmake libogg libvorbis theora libpng zlib libmikmod sqlite3 doxygen

Compile and build tolua

Go to your projects dir

git clone https://github.com/LuaDist/toluapp.git

cd toluapp

cmake -G "Unix Makefiles"

make && sudo make install

Git clone stratagus

Determine where you want to checkout stratagus, ie in your ~/projects, then:

git clone https://github.com/stefanhendriks/stratagus

Compile it

cd stratagus
mkdir build
cd build
cmake -G "Unix Makefiles" ..
make

Now you should be able to run a stratagus game. Since I already created Wargus by using Windows, I copied this over to my mac (and put it in ~/projects/Wargus). Then I ran stratagus as:

./stratagus -d ~/projects/wargus/

A known issue I have is that on startup the screen looks as if it is drawing with a weird offset (ie too much out of screen at the upper left). By simply changing resolution this goes away. Don’t know why yet, but since we have the code now and we can compile, we might as well try to fix it some day! 🙂

Personally I’d like to see a better AI for wargus, especially since I like to play Skirmish games.

I hope this guide helped you get it to work on your mac. Please share your experiences in the comments section.

Getting started with Allegro 5.1 on Mac OS X 10.8 (Xcode 4.5, and homebrew)

In Dune 2 – The Maker, I have used Allegro quite a bit. Back then it was around version 4.2. Allegro is a library that allows you to make games. In essence it has functions for manipulating the screen (ie, drawing bitmaps, manipulating palettes, etc), use controls (mouse, joystick, keyboard, etc) and more. With plugins you could extend it further, to use fonts (TTF), networking, etc.

Currently, the most recent version is Allegro 5 which breaks with the Allegro 4 API and makes it impossible to convert from Allegro 4 to 5 (atleast for D2TM). From a nostalgic perspective I wanted to try Allegro 5 and on my new system which runs Mac OS X 10.8.

In this post I will describe how you can get Allegro 5 working on Mac OS X, under XCode 4.5. I had great help from the documentation provided, and hopefully this post is sufficient for you. If not, I would suggest to checkout this documentation, or this one.

Rough steps

To give you an idea what we’re going to do, here is the installation in very rough form:

  1. – Installing required software
  2. – Installing dependencies to make Allegro more useful and to get it compiling (cmake, etc)
  3. – Compiling Allegro for Xcode, installing it and making sure the Frameworks are installed in /Library/Frameworks
  4. – Setting up an Xcode project to test if Allegro works

Prerequisites (Installing required software)

Requirements for getting started, if you already have this installed you can skip the prerequisites

  • Mac OS X 10.8
  • Xcode 4.5 (with command line tools)
  • Git/SVN
  • Homebrew

Before we can start, we need to have installed some prerequisites. Which are Xcode (you can get this from the App store), git and svn. I have used homebrew to install dependencies, you can also use Macports but I do not have any experience with this. (as far as I can tell it should behave quite the same). My advice would be to install these in the following order:

  • – Xcode
  • – Install command line tools from Xcode
in Xcode, go to preferences, tab "Downloads" -> " Components" -> Command Line Tools
ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
  • – The command line tools should have installed git and svn for you, try them out:
hit "svn --version", and "git --version" in your terminal.
If they are not installed, you could install them via homebrew (brew install git && brew install svn)

Installing required dependencies

As suggested by the Allegro 5 wiki we need to install dependencies. The wiki explains how to do it with Macports, but since I am using Homebrew, you need to do it like this:

brew install cmake

brew install zlib
brew install freetype
brew install jpeg
brew install libogg
brew install physfs
brew install libpng
brew install flac
brew install ffmpeg

The first one is cmake, which we will need to build Allegro. Cmake is required to create the OS specific build steps to compile Allegro, without it we cannot proceed. The other dependencies are used to make Allegro more useful. When we prepare to build Allegro in the next section, cmake will check what dependencies are installed. The more it finds, the more features it will provide in Allegro 5.

Note, you might get  a warning about zlib. If thats the case, you can ignore it.

Compiling Allegro for Xcode, and making sure the Frameworks are in /Library/Frameworks

Once we have everything set up, this step is relatively easy. Since we are going to compile it for Xcode, we basically are doing the same as the Allegro wiki is saying.

Open a terminal, and go (cd) to a directory where you want to get allegro’s sources. For example: ~/projects

cd ~/projects

We now need to fetch the sourcecode of Allegro, which we can do by using git clone. At this moment of writing, Allegro 5.1 is the current version. Our git clone command looks like this:

git clone git://git.code.sf.net/p/alleg/allegro

This takes a little while. Once git is done, you have Allegro’s sources in ~/projects/allegro.

Now: cd to allegro, and create a new directory called “build”, then go into that directory.

cd allegro
mkdir build
cd build

The first step is to let cmake (the first dependency we installed) prepare our build, then build it and then install it. This is done by the following:

cmake -G Xcode -DWANT_FRAMEWORKS=1 - ..
xcodebuild
sudo xcodebuild install

The last step requires you to enter your password.

I found that the last step did not work for me, in order to fix that I did:

cd lib/RelWithDebInfo

Within here all Frameworks are built. Now copy them over to your /Library/Frameworks directory with sudo. With this:

sudo cp -r *.* /Library/Frameworks/

If you don’t want to copy this over to your Library/Frameworks directory, then you need to remember the path to these frameworks as we are going to need them later.

Setting up an Xcode project and see it all working

This section is a copy & paste + improvement from this page.

  • Start XCode, create a new empty project (Other->Empty)
    Xcode new empty project
  • Add a Cocoa Application target to the project, let’s call it MyGame. (Click your project, then the + button at the bottom saying Add target, then Mac OSX->Application->Cocoa.)
    New cocoa application MyGame
  • Select the MyGame target, go to the Build Phases tab and add a new Copy Files Build Phase (+ button down right).
    • Select Frameworks from the dropdown
    • Leave Subpath blank
    • We leave this build phase empty for now, we will need it later.
      Add new build phase
  • Select the Build Settings tab then:
    • Note: You can change display from Basic to All at the top and use the search box to locate the following settings
    • Change Header Search Paths to (just copy & paste):
      /Library/Frameworks/Allegro-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroMain-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroAcodec-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroAudio-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroColor-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroDialog-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroFont-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroImage-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroPhysfs-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroMemfile-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroPrimitives-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroTTF-5.1.framework/Versions/Current/Headers
      

      (yes, it is intended to be one line)
      add framework headers

    •  
    • In the targets Build Settings specify the Framework Search Paths as/Library/Frameworks.add framework search path
      • This is needed to have cross-platform code (#include <allegro5/allegro.h> working – otherwise paths like using #include <Allegro-5.0/allegro5/allegro> would work without changing the search path)
      • If you use another location, one way to save on typing is to double click the input field, then navigate to the Headers folder in each framework and drag it into the xcode input list
    • Delete Prefix Header (Edit->Delete)
      • You can of course use your own prefix headers – but the default Cocoa one will only work with objective C projects that’s why we remove it, assuming MyGame is a cross-platform C/C++ project
  • Add all the Allegro frameworks as follows (this can be done in many ways, a group just keeps things tidy):
    • Select the Summary tab
    • Click the + button under Linked Frameworks and Libraries and add all the Allegro frameworks
      • In case they are not listed use the Add Other button and navigate to /Library/Frameworks to find themadd frameworksselect frameworkslinked frameworks added
    • Go to the Build Phases tab, then in the list to the left select all the Allegro frameworks and drag them to the Copy Files entry which we added before
      drag frameworks to copy build phase
    • Select all the frameworks again and this time drag them to the Frameworks group to the left (just to have things more tidy)
  • Don’t forget to remove the created source files under MyGame and add your own source code instead (note the main.m in Supporting Files for example)
    • Create a new main.c
      create new main
    • Give it the following content:
#include <allegro5/allegro.h>

int main(int argc, char **argv) {
   al_init();
   al_create_display(640, 480);
   al_clear_to_color(al_map_rgb_f(1, 1, 0));
   al_flip_display();
   al_rest(5.0);
   return 0;
}

Caveats

  • Cannot find header files: Make sure you have set the header paths correctly. Try to copy the one line given above, into your header paths (remove old ones first). If that does not work. Try adding them one by one, to make it easier to copy/paste I have provided them for you separately as well:
    /Library/Frameworks/Allegro-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroMain-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroAcodec-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroAudio-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroColor-5.1.framework/Versions/Current/Header
    /Library/Frameworks/AllegroDialog-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroFont-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroImage-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroPhysfs-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroMemfile-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroPrimitives-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroTTF-5.1.framework/Versions/Current/Headers
    
    
  • Compiling works fine, linking does not work: Make sure you have specified the Framework Search Paths as/Library/Frameworks.

OS X (10.8) Mountain Lion path settings not ‘picked up’ in RubyMine

Recently I have switched jobs to Zilverline.

And so far I love it there.

One of the things I now work in is OS X (10.8.2). I am programming in Ruby using RubyMine. I think RubyMine is great (especially since I am coming from IntelliJ as a Java programmer).

However, one of the things that bugged me was path variables not picking up in RubyMine.

From terminal all my stuff works great. Ie, rake spec, rails, etc. No problem.

However it seems RubyMine does not launch with the same path variables set as you terminal does. Also, the suggestions for does not work in OS X 10.8.

There where two ways for me to get around this problem. One is to simply launch RubyMine from terminal:

[code]
open -a /Applications/RubyMine.app/
[/code]

Because you launch it from the terminal itself, RubyMine will get all the environment settings from there.

Another way was to edit the default settings in RubyMine for (in this case) rSpec:

rubymine_rspec_defaults

And set the environmental path with value:

[code]
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH
[/code]

rubymine_set_path

Now all rspec tests will use this environment path and run fine.

Coupling: The factory method

One of the challenges we face with coding is dealing with coupling. Coupling is an important aspect of programming, it tells us how much our code is tangled. When coupling is too high, we can’t easily re-use code. When the coupling is too low it does little. You can measure coupling, there are several metrics for it even (for instance “Coupling between Objects, CBO”).

In this blog post I’d like to talk about a subtle introduction of coupling: when you introduce a factory method.

Consider you have an interesting piece of code, and this piece of code has quite a lot of properties:

[sourcecode language=”java”]
class Person {
private String firstName;
private String lastName;
// .. more properties here

public void subcribeTo(Subscription subscription) {
// do something interesting here
}

}
[/sourcecode]

The problem is, because of the amount of properties and other dependencies, we’d like to simplify its creation by introducing a Factory method. In this case we are building a web application, so we take the Request as input to read the parameters:

[sourcecode language=”java”]
class Person {
private String firstName;
private String lastName;
// .. more properties here

public static Person create(HttpServletRequest request, .. more arguments here .. ) {
this.firstName = request.getParameter("firstName");
// .. read more properties
// .. set up dependencies, etc.
}

public void subcribeTo(Subscription subscription) {
// do something interesting here
}

}
[/sourcecode]

In the code that uses Person, it becomes easier to construct the Person and we’re happy with that. However, we have introduced coupling on several levels:

  • We construct the object with specific parameters in the create method. If we want to create from different parameters, we cannot use it. There is a coupling between the parameters and the properties.
  • The object is constructed using a Request object. We cannot now move the class to an application that does not use the web. A person has nothing to do with a request, it is just convenience that we put the factory method in the Person class. There is a coupling between the code of Person and the dependency delivering the Request object.

There are several ways to deal with this. But lets start with the last reason of coupling. It is easy to fix this coupling by creating a Factory class within your web application. From there you can generate the Person object out of a request. The Person class has no create method anymore, and thus is not tightly coupled to a Request class. The newly created Factory however is coupled to the Request, which is fine as it is meant to convert Requests into Person objects. Hence we could even name it that way:

[sourcecode language=”Java”]
class Person {
private String firstName;
private String lastName;
// .. more properties here

Person(String firstName, String lastName, …) {
this.firstName = firstName;
this.lastName = lastName;
// …
}

public void subcribeTo(Subscription subscription) {
// do something interesting here
}

}

class PersonFromRequestFactory {

// .. dependencies here

public Person create(HttpServletRequest request) {
Person person = new Person(request.getParameter("firstName"), )
// .. read more properties
// .. set up dependencies in Person, etc.
}

}
[/sourcecode]

Once we have this Factory, you can take it a step further:
If you have different kind of request parameters to create the same object you could create different methods in the new Factory:

[sourcecode language=”Java”]
class PersonFromRequestFactory {

// .. dependencies here

public Person createFromRegistrationForm(HttpServletRequest request) {
Person person = new Person(request.getParameter("firstName"), )
// .. read more properties
// .. set up dependencies in Person, etc.
}

public Person createFromSubscriptionForm(HttpServletRequest request) {
Person person = new Person(request.getParameter("givenName"), )
// .. read more properties
// .. set up dependencies in Person, etc.
}

}
[/sourcecode]

You could also create a Parameter object and go from there. For instance, if your web application uses Spring, you could wire your request parameters to an object (called “Form binding“) automagically and use that object as input in your Factory. This way it is type safe:

[sourcecode language=”Java”]
class PersonFromRequestFactory {

// .. dependencies here

public Person create(RegistrationForm form) {
Person person = new Person(form.getFirstName(), …)
// .. read more properties
// .. set up dependencies in Person, etc.
}

public Person createFromSubscriptionForm(SubscriptionForm form) {
Person person = new Person(form.getGivenName(), )
// .. read more properties
// .. set up dependencies in Person, etc.
}

}
[/sourcecode]

But how do you test all this?
Did you notice the Person has private fields, and no get/set methods? The only way to set the fields is using the Person constructor. How do you test the correct construction of this Person class from the request? Since we are not able to read the properties, we have to use other ways to test that code. I’ll cover that in the next blog post.