Quick Autotest for NodeUnit and Node.Js on Mac OSX


Very simple way to get Autotesting in Node.js.

What is Autotesting? Simply put, it runs your unit tests automatically whenever you save a relevant file within your project.

  • First, install GROWL and GROWLNotify for Mac (http://growl.info/)
  • Next we want to install the ‘watchr’ gem…
    gem install watchr
    
  • Next create a file called autotest.watchr in the root of your Node.js project with the following ruby script…
    def run_all_tests
      print 'clear'
      puts "Tests run #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
      result_text = `nodeunit [TESTFOLDER]`
      result = result_text.include? 'failed'
      if result
    	`growlnotify -m 'Unit Tests Failed' Node Unit`
      else
    	`growlnotify -m 'All Unit Tests Passed' Node Unit`
      end
    end
    
    run_all_tests
    watch("(test|lib)(/.*)+.js") { |m| run_all_tests }
    
    @interrupted = false
    
    # Ctrl-C
    Signal.trap "INT" do
      if @interrupted
        abort("\n")
      else
        puts "Interrupt a second time to quit"
        @interrupted = true
        Kernel.sleep 1.5
    
        run_all_tests
        @interrupted = false
      end
    end
    

    Do not change the ` chars. This actually tells Ruby to output the text directly to the console (for those that didn’t know)

  • Replace [TESTFOLDER] in file above with your test folder
  • Run watchr..
    watchr autotest.watchr
    

Thats it! Now simply edit a .js file in your solution and the tests will run automatically and inform you of failures.

Feel free to add your favourite icons for failures and passes to GROWL. If you do, please send us an updated script ;)

Creating ruby gui applications – an introduction to ruby shoes

As part of my effort to detect objects using opencv I have found myself performing a mind numbing task and as every lazy programmer knows this is the time to build a tool.

After a bit of investigation into the various gui libraries for ruby I have found one that seems pretty good called Ruby Shoes. There seem to be a few variants of this particular library. Strangely the classic Red Ruby Shoes version does not act like a regular ruby library. It seems to be a runtime that uses ruby. The Green Shoes variant however is a straightforward ruby library. You can gem install green_shoes and get up and running straight away.

A gui application in Ruby Shoes is called a shoe app and is started by calling:

Shoes.app do
  # application code goes here
  title "Hello World!"
end

As I want to create an image selection tool I need to be able to track mouse clicks, movements and releases and then draw a rectangle as this is going on.

After playing around for a while I came up with this:

require 'green_shoes'
Shoes.app  do
  title "Selection tool"
  image("your_image.jpg").click do |button, click_left, click_top|
    mouse_down = true
    release do
      mouse_down = false
    end

    nofill
    @selection = rect :left => mouse[1], :top => mouse[2], :width => 1, :height => 1

    motion do |move_left, move_top|
      if mouse_down
        width =  move_left - click_left
        height =  move_top - click_top

        width = 1 if width < 1
        height = 1 if height < 1

        @selection.style(:width => width, :height => height)
      end
    end
  end
end

There are probably more efficient ways to handle the release but this was the best I could come up with in half an hour.

I found the manual quite helpful to figure all this out.

User authorisation with Sinatra

Today I needed to add authorisation of specific routes to my sinatra application. After having a look around I couldn’t find anything I really liked. So I sat down and did the same thing any self respecting developer would – and wrote one myself.

I was actually surprised how easy it was and the result is simple-authorisation (gem install simple-authorisation).

To include this in your app simply:

require 'simple-authorisation'

And then in your sinatra config:

configure do
Simple::Authorisation.route '/', :deny => ['?'], :allow => ['*']
Simple::Authorisation.route '/login', :allow => ['?']
Simple::Authorisation.route '/logout', :allow => ['?']
Simple::Authorisation.route '/admin', :allow => ['*'], :deny => ['?']
end

Adding configuration for a route / will actually apply it to all its child routes. Adding additional routes will overwrite that setting. ‘?’ means anonymous users and ‘*’ means any logged in user.

The last thing you need to do is add a current_user method to your application:

class Application < Sinatra::Application
def current_user
session[:user]
end
end

Now simple-authorisation knows how to get the current user it can do its thing!

I know this is very basic but so far it is all I need. The next thing to add will be specific user groups.

If you like the look of this and have something to add then please fork this on github.

Detecting objects in a photograph with opencv part 2

Eyes being detected using opencv

As I found out last time it is quite easy to detect objects in a photgraph. The difficult part is to create a classifier that will do this for the particular object you are looking for.

I am still working on building a simple object classifier and I will share how I have done this soon. In the mean time you may like to whet your appettite with some of the classifiers that ship as part of opencv.

You can find classifiers that can detect faces, eyes and whole bodies in opencvs source control. For the purpose of demonstration I will use the eye detector. I am also using ruby-opencv from this repository.

In your ruby file (eyes.rb for example) include opencv:

require "opencv"

Load the classifier into opencv:

classifier = 'haarcascade_eye.xml'
detector = OpenCV::CvHaarClassifierCascade::load(classifier)

Load the image you want to run the classifier against:

image = OpenCV::IplImage.load('sample_image.jpg')

We can now detect objects by:

detector.detect_objects(image) do |region|
color = OpenCV::CvColor::Blue
image.rectangle! region.top_left, region.bottom_right, :color => color
end

This will draw blue rectangles over around the eyes. We can then save that image:

image.save_image('eyes_detected.jpg')

The result? Yours truly with square blue glasses!

Detecting objects in a photograph with opencv

Two faces being detected using OpenCV

For a project I am working I need to detect simple rectangular objects in a photograph. After some investigation I have settled on using the Open Computer Vision (opencv) libraries to do this. I have played around with opencv a little in the past but still consider myself a newbie. Having said that it has not been too hard to get up and running.

My programming language of choice is ruby so I am making use of the ruby-opencv gem. Unfortunately this gem doesn’t seem to be very well supported and didn’t install using good old gem install opencv. What I found was that this repository seemed to be the most up to date fork of code. So I cloned it and went about getting it installed.

ruby-opencv is a native gem that wraps the opencv libraries so there is not much ruby going on in there and plenty of c++. After muddling my way through a few different messages about dependencies I did not have and some confusing error messages – which again where simply unmet dependencies I finally managed to get the gem built.

The repository has a sample that shows how to do face detection. It is one of those pieces of code that make you go what the heck! it can’t be that simple! And while you can do face detection in about 8 lines of code it is not really the code that is the magic part here.

The face detection algorithm is actually a set of Haar-like features. This is basically a description of what sort of object we are looking for – but go read the wikipedia article for a more comprehensive description. In order to detect a specific type of object we are going to have to write our own classifier that describes what we are looking for.

The next step is to write a classifier for our objects which we will do in the next post.

 

Selenium 2.0 released

Anyone who has seriously looked at automated browser testing will have come across selenium. For the last year or so it has been undergoing a pretty hefty transformation after merging with the webdriver project.

The result is a very fast (for browser based testing) reliable browser testing framework. Merging with webdriver brought native browser plugins which tremendously speeds up execution time. The plugin implements a REST API that allows the browser to be controlled from any of the client libraries or from Selenium Server – the remote control product.

One of the beauties of the Selenium project is that you can use it from pretty much any programming language. That is thanks to the REST API, as it is called over http pretty much any language can communicate with it so creating a library is not technically challenging. My language of choice is Ruby and the client library for it is excellent.

Today sees the release of version 2.0 which you can get from here. Ruby users can of course simply: gem install selenium-webdriver

 

Using Dalli client with Heroku Memcache plugin in Sinatra

Today we are going to learn how to use the Memcache plugin on Heroku in a Sinatra app. We will be using a gem called ‘Dalli’. Memcache means ‘a general-purpose distributed memory caching system’ or in other words, something cool, fast and easy to use for speeding up your website. The way to do this is to cache certain parts of your application for a specific time period (ttl) so that users on your site would share the same data output and not need to trigger the data collection mechanism for each request.

Lets get to it! First we have to enable the Memcache plugin on heroku, so go ahead and find the plugin (see screenshot) and add it to your app.

The 5MB version is free and should be adequate enough for your average blog, brochure website. In a commercial website, don’t be surprised if the number is closer to 20GB.

Adding the Memcache plugin would add the necessary environment variables that ‘Dalli’ needs to use. So, lets go ahead and add ‘Dalli’ to our Gemfile….

gem 'dalli'

and install it…

bundle install

Next we need to set up ‘Dalli’ in our rack_app.rb

require 'sinatra'
require 'erb'
require 'dalli'

set :cache, Dalli::Client.new
set :enable_cache, true
set :short_ttl, 400
set :long_ttl, 4600

get '/' do
  erb :index
end

You can play around with the :short_ttl and :long_ttl times to find the best setting for your content, but it wouldn’t be frowned upon to cache certain things for hours or even days (ie. ‘Post of the week’ promotion on your homepage).

Next we simply need to store our data in ‘Dalli’ whenever we want to cache it, and remember to look for it before using our time consuming fetching mechanism. We will do this with a CacheKey.

get '/' do

  @todays_posts = get(:todays_posts)
  erb :index

end

def get(key, time_to_live=settings.long_ttl)

  if(!settings.enable_cache)
    return some_really_complicated_dataretrieval(key);
  end
  if(settings.cache.get(key) == nil)
    settings.cache.set(key, some_really_complicated_dataretrieval(key), ttl=time_to_live+rand(100))
  end

  return settings.cache.get(key)

end

Note that I added a rand(100) to the TTL. This is so that when the cache refreshes, it doesn’t refresh all the items with the same TTL at once. This would cause a small hiccup in performance at that time. Thats it! That should be all you need to use Memcache on Heroku using Sinatra.