Read QR code from Javascript and Webcam


Here, at Flockin we needed a way to login from Browser using a QR-code card and the Webcam.

For the time being (ealy 2012), Javascript have no API to stream/parse from webcam, also the main free library for QR code, Google’s ZXing (actually the only one working I know of) does not support Javascript.


The most viable solution detected was to parse Webcam from ZXing’s ActionScript module, in a very dry package that could interact with JavaScript through ExternalInterface with Javascript registering a callback.


The use is pretty simple. When the swf object gets completely loaded on the page just register the JS callback which is a function that takes 1 param (String or null), the Interval of call (default 500), and an error callback (default null)

You can download all files from github, that is the project home. *Recommend you adapt the .as3 and recompile to fit your specific needs


The example below is the same found at the project’s example/index.html

// sample of function that may be registered as Callback.
function actQR( msg ){
	// msg comes null if no code were detected
	if( msg === null ){ //expect a lot of nulls
		console.log("no QR were read at this time")
	} else {
		// a valid QR reading, do something with it
		// ask flash to stop parsing, this saves processing as webcam reading stop

// sampe of function to be called when something goes wrong
function noWebcam( msg ){
	alert("Err! "+msg)

// this setInterval is a safe measure, so we don't call flash function before it is loaded;
var registerQRCb = setInterval(function(){
	//var nomeDoFlash = "QR"
	if( typeof QR === 'object' && QR != null && typeof QR.start === 'function' ){
		// first param is the function signature we want the SWF to call periodicaly
		// second param is the intervall we want it, in miliseconds (default: half-second)
		// third is an signature for callback if something goes wrong, aka, user has no Webcam (default: null)
		QR.start( "actQR", 200, "noWebcam" )
}, 100)

Ruby’s fear-cancer

This video: High Performance Ruby: Threading Versus Evented by Dr Nic Williams, Engine Yard

It meant so much to me!

For around 4 months I’ve been using Node.js, and before that, for 3 years, programming Rails.

As soon as I started on Node.js, I could feel that something was different. My little Computer Science bachelor conscience was starting to tell me: now you are starting to do it right 🙂

But then, lets go back, Ruby’s syntax is lovely.. Rails API is sugar! But still, it’s neverland. Why??

It does not fit real world! It is a thin layer of happiness, so delicate, that we feel fear of touching it and breaking it. So what we puny humans do? We delegate it to those genius heroes who will be able to take that code and maybe squeeze a few more couples of requests/sec!

But not even that is the cancer I mean.

The cancer here is represented by clown hosting the video. “Oh those scientific articles mess with our head and stuff O.o Let me chew that evil reality and I will give you the RIGHT (sugar coated) solution!” and all other non fun nor assertive statements. By the way, he may be referring to the C10K problem, and alike, articles.

The problem here is, VP  EngineYard and want ppl addicted on his junk. He does not host Node.js.

Ruby always had so many language implementations to solve some important language problems, as well as servers. This is not the first time a good solution for ruby is born (JRuby+Trinidad), but why would they share it before if he could have people paying for so much RAM?

The reason I believe he felt compelled to share it now, is that Node.js unoptimized code can outperform Rails by a LOT,  under 150Mb.

But my main problem is fear of complexity. The host talks about it all over the initial part of the video. He refers his audience under constant fear of it’s own ignorance all the time. This is a awful, and that’s how I felt using Rails. Such a large stack, complex language design, only understanding the framework code itself was hard task.

To keep people in bliss ignorance he just goes like: “Oh I promissed evented? We are past that, right?! HAAAA” so just be happy and keep the status quo. You would’t want to mess your pretty little head with asynchronous code, would you?

I like Node.js, besides performance, language is simple; it is JavaScript, open Objects, closure and more. Of course, don’t assume well-written JS is something easy to do. No great code in any modern language is easy to achieve.

If you’ve developed Rails, you have concepts of MRI, thin, mongrel, jruby, 1.8.7, 1.9.2, rubinius, unicorn, and LOT MORE, whilst in node.js world all that stands for: node.js. It is a unification point for language and server.

What about gems?  npm, a easier system of distributing packages.

Wrapping it up, node.js is no silver bullet, it just made me realize the problems I had while programming ruby, as much as ruby did it for me on php. If nothing else, node.js helped improve ruby’s community by adding options to the web development mainstream.

Would I work with Rails again? If a employer would point me that out as the only chosen solution, then yes, and I’d probably try that stack, but I prefer confidence instead of fear.

When to Ruby on Rails, when to Node.js

(update) Take this post as a naive overview, it may not reflect the most accurate reality


I am trying to do a sort of indirect comparison between Rails and Node.js. The very main reason of being indirect, is that Rails is a Framework, while Node.js is a runtime with custom libraries.

If it were be to put in a simple phrase, Rails is resourceful and Node.js is light and fast.

Lets elaborate some more..


Is the most complete open-source framework available (that I know of)! Big companies use it. It can do lots of stuff well, in an organized manner; this meaning, Rails is more than just MVC, it has a full stack of features well-integrated, at the same time being very modular. Some of the features included out of the box:

  • Database adapter for the majority of them, supporting plug your own.
  • Database migrations, so multiple dev can sync and experiment with their DB.
  • Powerful engines for Views, Controllers and Models.
  • Support to code generator.
  • Has structure to all sorts of tests and friendly to TDD.
  • Really awesome documentation.
  • Model has all kinds of hooks, validations and associations.
  • Controller has support to handle XML/JSON in the same action that serves HTML.
  • Gems that integrate, for instance, Memcached, MongoDB, Auth and lots more.
So Rails is war-proven, capable of integrating lots of features together without harass. There is also a very cool post of Fabio Akita in the refs. about how it made possible to develop systems in periods before impossible.


Two things make this platform suitable for web:

Its engine, V8 is very fast! In a very loose average, 8 times faster than Python (or even up to 200 at peak). Python already outperforms Ruby (ref. bottom)

Second point; and this argument is separated from the above, is that it async-driven (is built around reactor pattern). As in the case, requests can be performed in parallel, without any blocking I/O. A single server can handle a lot. (update) And with >0.6.0 Cluster API, it can scale to use all of available CPU cores.

So, it is a very new sort of backend language, but huge players, besides Joyent, who invented it, are adopting it, including LearnBoost and LinkedIn, which has an awesome article about using. The language, and it’s main web framework, Express, deserve a list of features (you can check more info in the references below).

  • It´s web server is able to handle a HUGE number of connections out of the box
  • Various libraries can be run on browser, the same as in the server
  • Very friendly to Websockets (real-time web apps)
  • Lots of libraries are being ported to it from other langs.
  • Express, inspired in ruby´s Sinatra; is very light on memory but also very powerful
Running a simple benchmark against a single server instance, I were able to get 587 req/s accessing MySQL without any external cache support. This number could scale, if I used Cluster to spawn at least a process per processor.

Summarizing, When to use each?

Rails really shines when..

  • The database is complex in terms of associations.
  • The app structure is well defined.
  • Business rules are complex, and validation is needed.
  • When the number of requests isn´t the a decisive factor.
  • Administrative interfaces.
  • Many developers in parallel keep the DB up-to-date with migrations
  • The database to be used is undefined, or may vary.
What about Node.js?
  • APIs
  • Real-time web/mobile apps.
  • Application that should scale to lots of concurrent requests.
  • Little memory footprint

This being said, there is no reason at all, a web-site or service can´t easily integrate both.

— I’d appreciate if you could leave a comment, either to talk about your case, or add up.




Testing a Node.js Express API server with Vows (functional)

How to test an API that must be authenticated via session?

vows: plural of vow

Noun: A solemn promise.
Verb: Solemnly promise to do a specified thing: “one fan vowed, “I’ll picket every home game.””.

Oh wait..

Asynchronous behaviour driven development for Node.

I should… test every method I expose to the client..
Since the Vows documentation is very awesome, and I already have another post that explains the strategy used on the API, there is no need to much talk; just not that this code is still very early in maturity.
Straight to current code [ test/api-test-authed.js ]

 * run the site at localhost, port 8010
 * run vows --spec test/api-test-authed.js

var request = require('request'),
    vows = require('vows'),
    assert = require('assert'),
    apiUrl = "http://localhost:8010/",
    cookie = null

var apiTest = {
  general: function( method, url, data, cb ){
    //console.log( 'cb?', cb )
        method: method,
        url: apiUrl+(url||''),
        json: data || {},
        headers: {Cookie: cookie}
      function(req, res){
        cb( res )
  get: function( url, data, cb  ){ apiTest.general( 'GET', url, data, cb    )  },
  post: function( url, data, cb ){ apiTest.general( 'POST', url, data, cb   )  },
  put: function( url, data, cb  ){ apiTest.general( 'PUT', url, data, cb    )  },
  del: function( url, data, cb  ){ apiTest.general( 'DELETE', url, data, cb )  }

function assertStatus(code) {
  return function (res, b, c) {
    assert.equal(res.statusCode, code);

function assertJSONHead(){
  return function(res, b, c ){
    assert.equal( res.headers['content-type'], 'application/json; charset=utf-8' )

function assertValidJSON(){
  return function(res, b ){
    // this can either be a Object or Array
    assert.ok( typeof( res.body ) == 'object' )
    //assert.isObject( res.body)

// TODO include unauthed tests
var suite = vows.describe('API Localhost HTTP Authenticated Tests')

// Very first test!
  "Server should be UP as in: var apiUrl": {
    topic: function(){
      apiTest.get('', {} ,this.callback )

    '/ should repond something' : function(res, b){

  'Authenticate to /login': {
    topic: function(){
          url: "http://localhost:8010/login",
          json: { user:{ username: 'flockin_lab', password: '123456' }}

    'get a valid Cookie': function(req, res, body, err){
        cookie = res.headers['set-cookie'].pop().split(';')[0]
        console.log("GOT COOKIE!", cookie)
      } catch(e){ }

      assert.ok( typeof(cookie) == 'string' && cookie.length > 10 )
  'Users#index': {
    topic: function(){
      apiTest.get('admin/employees', {}, this.callback)
    'should be 200': assertStatus(200),
    'should have JSON header' : assertJSONHead(),
    'body is valid JSON' : assertValidJSON(),

  'Qrcodes#index': {
    topic: function(){
      apiTest.get('admin/qrcodes', {}, this.callback)
    'should be 200': assertStatus(200),
    'should have JSON header' : assertJSONHead(),
    'body is valid JSON' : assertValidJSON(),


// )
suite.export( module )

Brief Discussion

This code is still state-of-art,
We depend on the lib ‘request’, which is pretty good,
The server should already be started, since I see no point in having the test being responsible to bring it up and handle it.

Can improve it? Please leave a comment! 🙂

Starting a Node.js Express API to serve json, (with auth, MySQL – based)

via Axiom Zen

Hello and welcome!

Foreword, and purpose

I will be putting this JSON-API up, to serve USERS as a restful resource, trying to be light as possible, still serving content only to authenticated peers (auth based on cookie).

The regular use will be something as, the client makes login, sending params via POST, ant then is able to access all resources we may serve.

I will be using some packages, all being possible to install via npm install, lets talk about them:

  • Express, itself is like the Ruby’s Sinatra Framework, but async, for Node.js
  • Express-resource, a simple and extendable way to define Restful resources
  • Sequelize, a MySQL ORM! Offer n-m relations, and a .sync() way to define your own Schema! (better than migrations?)
  • Faker, a generator of fake-data that we need
  • Mustache, String template engine. Will be using for minimal tasks, not required.
  • Jade, view template engine. Not required at all, but since I started coding there, will keep it for now.

The app skeleton

Install express with -g and generate an app from it.

We will be keeping 3 core files:

app.js  : The main file; require all other from there, and configure Express!

models.js : The file that has all models definitions exported.

routes.js : Acts as a general router and controller for the app. Also holds the functionality of authenticating all users that get past /admin/*. The authorization method here is static, in this case, one e-mail bounded to one password. See Auth Methods‘/login’.. for details.



// Detect Params
if (process.argv.indexOf('--seed') > -1) {
   * Indicates when the DB should be re-schemed and seeded again
  GLOBAL.db_seed = true;

if (process.argv.indexOf('--no-auth') > -1 ){
   * Indicates when to run without requiring auth for API
  GLOBAL.no_auth = true;

var express = require('express'),
     * Instantiate the unique Express instance
    app = module.exports = express.createServer(),
    models = require('./models.js'),
    S = require('mustache').to_html;

 * @type {Object}
 * A list of all Sequelize Models available, representing the tables.
GLOBAL.models = models;

 * @type {Express}
 * The Singleton of Express app instance
 */ = app;

// Configuration

app.configure(function() {
  app.use(express.logger({format: 'dev'}));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.session({ secret: 'evilWorldDom1nat10nPlanzisstillsmallshouldhaveNoWords' }));
  app.use(express.static(__dirname + '/public'));


app.configure('development', function() {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.configure('production', function() {

// Routes


console.log('Express server listening on port %d in %s mode',
   app.address().port, app.settings.env);


var Sequelize = require('sequelize'),
    db = new Sequelize('dev_', 'root', '123456');

   * @type {Object}
   * Map all attributes of the registry
   * (Instance method useful to every sequelize Table)
   * @this {SequelizeRegistry}
   * @return {Object} All attributes in a Object.
    var map_attributes = function() {
      var obj = new Object(),
          ctx = this;
        function(attr) {
          obj[attr] = ctx[attr];
      return obj;

 * @type {Object}
 * All models we have defined over Sequelize, plus the db instance itself
var self = module.exports = {
  'db' : db,

  User: db.define('user',
      name: {
              type: Sequelize.STRING,
              defaultValue: 'Not Big Deal',
              allowNull: false
      timestamps: true,
      freezeTableName: true,

      classMethods: {
        staticExample: function() { }
      instanceMethods: {
        mapAttributes: map_attributes

  Activity: db.define('activity',
      type: { type: Sequelize.STRING },
      value: { type: Sequelize.STRING }
      timestamps: true,
      freezeTableName: true,

      instanceMethods: {
        mapAttributes: map_attributes

  Company: db.define('company',
    name: { type: Sequelize.STRING, defaultValue: 'MegaCorp', allowNull: false }
    timestamps: true,
    freezeTableName: true,

    instanceMethods: {
        mapAttributes: map_attributes


self.Activity.belongsTo(self.User, {foreignKey: 'user_id'});
self.User.hasMany(self.Activity, {foreignKey: 'user_id'});

self.User.belongsTo(self.Company, {foreignKey: 'company_id'});
self.Company.hasMany(self.User, {foreignKey: 'company_id'});

if (GLOBAL.db_seed) {'SEED TIME!');

  var chainer = new Sequelize.Utils.QueryChainer;

    .add(self.Company.sync({force: true}))
    .add(self.User.sync({force: true}))
    .add(self.Activity.sync({force: true}))
    .on('success', function() {

      var seeds = require('./seeds');
      for (var model_name in seeds) {
        console.log('MODEL', model_name);
        for (var i = 0; i < seeds[model_name].length; i++) {
            .on('success', function(novo) { })
            .on('failure', function(erro) {
              console.error('DB SEED ERROR!!', erro);
          console.log('  ', seeds[model_name][i]);
    .on('failure', function(errors) {

      console.error('DB schema change FAIL', errors);


// User.staticExample()


S = require('mustache').to_html;
Resource = require('express-resource'); // paths Express, add .resource

app.get('/', function(req, res) {

  // This big mess just points out all routes we have, along with the verbs
  var path_list = S(
    '{{#routes_obj}}' +
    "<a href='{{path}}'>{{method}}: {{path}} </a> <br/>" +
      routes_obj: (app.routes.routes.get ? app.routes.routes.get : [])
        .concat(( ? : [])
          .concat((app.routes.routes.put ? app.routes.routes.put : [])
            .concat(app.routes.routes.delete ? app.routes.routes.delete : [])
              .concat([{ path: '/auth.html', method: 'get'}])))

  res.render('index', {
    title: 'DBServer',
    'path_list': path_list,
    logged: req.session.authed ? 'YES :)' : 'NO :('


 * AUTH methods
 */'/login', function(req, res) {'login PARAM: ', req.body);

  var credentials = req.body.user;

  if (GLOBAL.no_auth ||
       (credentials &&
        credentials.username == 'super_safe' &&
        credentials.password == '123456')
      ) {

    req.session.authed = true;
  } else {


app.get('/logout', function(req, res) {
  req.session.authed = null;

 * API Authentication filter
app.all('/admin*', function(req, res, next) {

  if (req.session.authed) {
  } else {
    res.json(['must auth']);

 * Resources
app.resource('admin/users', require('./resources/users'));

 * Just say it is all fine.
module.exports = true;


// npm install Faker
var Faker = require('Faker'),
    times = 0,
    id = 0

var self = {
  Company: [ ],
  User: [ ],
  Activity: [ ],

// Company: create 3 - 5
id = 1
times = Faker.Helpers.randomNumber(3)+3
for (; times > 0 ; times--) {
  var novo = {
    id: id++,
    name: Faker.Company.companyName(),
  self.Company.push( novo )
  //console.log("Company", novo)

// Users: create 0 - 8 per company
id = 1
for (var i=0; i < self.Company.length; i++) {
  times = Faker.Helpers.randomNumber(9)
  for (; times > 0 ; times--) {
    var novo = {
      id: id++,
      name: Faker.Name.firstName(),
      company_id: Faker.Helpers.randomize( self.Company ).id,
    self.User.push( novo )
    //console.log("User", novo)

// Activities: create 0 - 10 per user
var TYPES = ['level_up', 'timeout' ],
    VALUES = ['win', 'fail']
id = 1
for (var i=0; i < self.User.length; i++) {
  times = Faker.Helpers.randomNumber(11)
  for (; times > 0 ; times--) {
    var novo = {
      id: id++,
      type: Faker.Helpers.randomize( TYPES ),
      value: Faker.Helpers.randomize( VALUES ),
      user_id: Faker.Helpers.randomize( self.User ).id,
    self.Activity.push( novo )
    //console.log("Activity", novo)

module.exports = self


exports.index = function(req, res) {
  models.User.findAll().on('success', function(users) {

    res.json( {
        return user.mapAttributes();


h1= title
p Welcome to #{title}
p Paths we have:
div!= path_list
div .
footer Loggedin? #{ logged }


<!DOCTYPE html>
<html lang="en">
		<meta charset="utf-8" />
		<link rel='stylesheet' href='/stylesheets/style.css' />
					<a href="/">Home</a>
				<form action="/login" method="post">
					<label>Username: <input name="user[username]" type="text" /></label></br>
					<label>Password: <input name="user[password]" type="password" /></label></br>
					<button type="submit">OK</button>
					Express API

Brief Discussion

Overall, this post presents a short and extensible way to start a API that requires authentication, via cookie, and returns data in JSON format.

A fresh work enviroment for Node.js and Express on Ubuntu 10 in about 30 minutes

Hello and welcome.

Node.js came to me as likely the smartest choice for web development, as you are constrained at JavaScript for dynamic programming server side (ActionScript and Java, please don’t cry). Having all String, and Date operations the same as server or client is just a big thing! Also validations come to my mind as not-anymore duplicated code. Besides, the concurrency performance seems really nice. (most importantly, people smarter then me thinks the same)

This post intention is to document my efforts under Ubuntu 10.04 to install everything needed from Node.js to the actual work environment.

Lets start by some git and a good working java for Aptana, and some dependencies for Node.js install itself.

sudo aptitude install git-core sun-java6-bin sun-java6-jre sun-java6-plugin sun-java6-jdk python libssl-dev socat curl libev

Now, you should be good to both install version 0.4x as referenced here: and I also recommend you start dl Aptana Studio 3 this is my IDE of choice for web dev. (as Rails developer)

If you are new to Aptana, I also recommend going to Window > Preferences and choosing a theme(Aptana>Themes) you like, as well as configuring JS to not alert apparent errors(General>Editor>Texte Editor>Errors : uncheck boxes), since it does not know Node.js functions.

Install NPM, which is the best package handler at the moment and all packages to head into web dev, I will explain later on

curl | sh
npm install jade
npm install less
npm install -g express
npm install -g node-dev
npm install -g node-inspector

About Express, you can have noticed, it is close to ruby’s Sinatra web framework MVC, which is pretty cool, and has a great performance. I recommend some learning from their web-site videos.

In my machine, AMD Phenom II X4 965, 3.2GB Ram (bla bla) running some intensive apache ab, I got these fantastic results:

ab -n 100000 -c 100

Document Path: /
Document Length: 11 bytes

Concurrency Level: 100
Time taken for tests: 10.789 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 13200000 bytes
HTML transferred: 1100000 bytes
Requests per second: 9268.48 [#/sec] (mean)
Time per request: 10.789 [ms] (mean)
Time per request: 0.108 [ms] (mean, across all concurrent requests)

Jade and Less are about the View layer

Now… node-dev and node-inspector.. CLASSY STUFF!

If you are used to developing Rails or Sinatra, you are used to have your code auto-reloaded (development-mode or shotgun), node-dev accomplishes just that! everytime you make any changes to any file.js from the current folder it will kill and restart your Node app for you; nice!

Now, node-inspector this it the coolest debug tool I’ve ever seen! And you can use it along with node-dev with no problem 🙂

You can learn more from then at their Github page

If you want to develop along with CouchDB, you should install it too.

sudo aptitude install automake spidermonkey-bin autoconf subversion-tools libtool help2man build-essential erlang erlang-manpages libicu38 libmozjs-dev wget libicu-dev libreadline5-dev checkinstall
sudo aptitude install couchdb
npm install cradle

If couch installed fine, you can see it via And a daemon is started along with your machine every boot.

About cradle, they have a real good documentation at their website, you should start there.

And that’s it! Due aptitude and npm you can have it all done in about 30 min, heavily depending on your network connection. Good coding! 😀

2 jquery animation parallel (or a effect)

via Axiom Zen

This post is kinda drafty, but since the Google’s first page for this were outdated, here we go!

When trying running 2 animations (or multiple) side by side (in parallel) at a same element, via JQuery .animate() they run one after another; like they are supposed to do by default, but there is a argument to override;  queue. In a silly example:

  j('body').animate({ paddingTop: 100}, 500, function(){ alert('Took half a second!')}).animate({paddingLeft: 100}, {duration: 500, queue:false})

Here we are animating both in parallel, and the callback alert, run after half a second. (*be careful about callbacks on animations with queue:false, since they don’t seem to trigger )

In another example, fairly more complex (and real :)), I am using JQueryUI for both  shake, and color effects.
The objective is to simulate a div that gets overheated and waves to chill, real fast.

var pointsE = j('#health_bar .stats')
pointsE.css( {color: 'rgb(255,0,0)' })
        .effect('bounce', {times: 5, distance:10, easing: 'easeOutElastic'}, 300 )
        .animate({ color: 'rgb(255,255,255)' }, { duration: 500, queue: false})

Just be aware, that it doesn’t seen .effect(), supporting queue: false –it breaks. That’s why I put it in the .animate()
About the .stop(true), it is just to be sure that the queue is empty before starting the animation (in practice, it is a minor fix for consecutive .effect(‘shake’))

jQuery .animate() API
jQueryUI Color
jQueryUi Shake Effect