Archive

Archive for February, 2012

Example: sorted set functions with node.js + redis

February 28, 2012 1 comment

Have been playing with node.js module redis (and a bit of underscore) almost all day and I could not find any examples using zrange (or zrevrange) so I decided to write one as a practice:

var rc=require('redis').createClient();
var _=require('underscore');

rc.zincrby('myset', 1, 'usera');
rc.zincrby('myset', 5, 'userb');
rc.zincrby('myset', 3, 'userc');
rc.zrevrange('myset', 0, -1, 'withscores', function(err, members) {
        // the resulting members would be something like
        // ['userb', '5', 'userc', '3', 'usera', '1']
        // use the following trick to convert to
        // [ [ 'userb', '5' ], [ 'userc', '3' ], [ 'usera', '1' ] ]
        // learned the trick from
        // http://stackoverflow.com/questions/8566667/split-javascript-array-in-chunks-using-underscore-js
	var lists=_.groupBy(members, function(a,b) {
		return Math.floor(b/2);
	});
	console.log( _.toArray(lists) );
});
rc.quit();

Have fun.

Categories: node.js, redis, underscore

How to write javascript codes more jslint-compliant

February 21, 2012 Leave a comment

1. The basics
If you love writing Javascript codes, you should have some kind of syntax validator installed. The one and only tool I am using is jslint, which can be installed in a number of ways, depending on the os and development toolkits available. My favorite way to is to install through npm (provided that node.js is installed, if not, try nvm):
npm install -g jslint

Once installed, you can fire it like:

$ jslint my_script.js

Most likely it’ll produce a lot of errors/warnings unless you already write code in a jslint-compliant fashion. There are some options you might want to add:

$ jslint --eqeq --white my_script.js

Where

  • –eqeq: tolerant == and !=
  • –white: doesn’t enforce strict whitespace rules, for example, doesn’t require spaces around =’s

See the jslint doc site for a complete list of options.

2. Run jslint directly from vim
If you are like me – a vim nut, you might want to integrate jslint into vim, add the following into your ~/.vimrc

command Jslint !jslint --white --eqeq %
nnoremap <leader>j :Jslint<CR>

To activate jslint while your are inside vim, simply hit \j in command mode. Special thanks to http://blog.sanctum.geek.nz/series/unix-as-ide/ for the vim integration tip.

Categories: javascript, jslint, vim

Installing git on Mac OS X Lion through Homebrew error fix

February 18, 2012 14 comments

I recently did a fresh 10.7.3 installation onto an i5 hackintosh and installed Xcode on it through the app store. Then I installed my favorite tool homebrew through this one-line command. Everything went well except when I tried to install git (actually any brew install command would fail regardless the package) through homebrew I got the following error:


Error: Failed executing: make prefix=/usr/local/Cellar/git/1.7.9.1 CC=/Applications/Xcode.app/Contents/Developer/usr/bin/llvm-gcc CFLAGS=-Os

A little digging shows that file /usr/bin/make is missing, further digging reveals that the new Xcode makes the command line tools one of the optional components so in order to use homebrew, the command line tools must be installed via Xcodes -> Preferences -> Downloads -> Command Line Tools -> Install. brew install package_name works like a charm again like it used to on 10.7.2 once command line tools is installed.

Screenshot (after Xcode Command Line Tools is installed):

 

[UPDATE 2/19/2012] Additional note on installing redis with homebrew:
brew install redis would fail, even with Command Line Tools component installed, for now you need to use option --llvm to install redis:
brew install redis --use-llvm
Solution is found through https://github.com/mxcl/homebrew/issues/10305.

Categories: 10.7.3, homebrew, xcode

Getting last N element(s) from a list in redis

February 13, 2012 Leave a comment

Somehow I couldn’t find anywhere on how to achieve this: getting the last N elements from a list in redis, not even on Redis command docs. Well I just figured out the easiest way, say to get last 3 elements from list users:

redis 127.0.0.1:6379> rpush users tom
(integer) 1
redis 127.0.0.1:6379> rpush users ray
(integer) 2
redis 127.0.0.1:6379> rpush users coolguy
(integer) 3
redis 127.0.0.1:6379> rpush users bob
(integer) 4
redis 127.0.0.1:6379> rpush users alice
(integer) 5
redis 127.0.0.1:6379> lrange users -3 -1
1) "coolguy"
2) "bob"
3) "alice"
redis 127.0.0.1:6379> 

Just a couple of things worth noting:

  • start should always to be no larger than end in command lrange list_name start end
  • so the formula to get last N elements from a list is lrange list_name -N -1 where N>=1
Categories: redis

System load monitoring with nodejs+socket.io+flot

February 12, 2012 Leave a comment

I am a big fan of node.js, socket.io and a long list of other node modules, as you might have known through my News Board app. While working on a html5 charting project a few years back I discovered flot which I also became a fan of. I started a few weeks ago working on a real-time charting app with the technologies I just mentioned, by plotting some randomly generated numbers (streamed through socket.io) with flot. Today I just changed the app by using real data – system average loads. Check out the project at github if you are interested in. My next goal is to use Redis to handle the data captured.[update] A new branch using Redis as data store has also been implemented.

Screenshot:

Categories: flot, node.js, socket.io

Switch to classic gnome menu in Ubuntu 11.10 how to

February 10, 2012 Leave a comment

Steps:
1) open a terminal and run

sudo apt-get -y install gnome-session-fallback
sudo sed -i 's#\(user-session=\)ubuntu#\1gnome-classic#' /etc/lightdm/lightdm.conf

2) Disable auto login if it’s on
User icon on the top-right corner of the screen -> User Accounts -> Unlock -> Automatic Login Off

3) Reboot, click the setting icon on the login screen to make sure GNOME Classic is selected. This needs to be done only once.

References:
http://www.youtube.com/watch?v=5xDXeOsLQ3k
http://debianhelp.wordpress.com/2011/10/14/how-to-change-default-session-in-ubuntu-11-10/

To switch back to Unity,

sudo sed -i 's#\(user-session=\)gnome-classic#\1ubuntu#' /etc/lightdm/lightdm.conf
Categories: Tip, ubuntu

Fix for initial opening pdf in new Internet Explorer (6-8) window problem

February 9, 2012 4 comments

Problem:
In a recent project I am working on I need to allow user to open their documents (in PDF format, hosted in a different server with different domain) in a new window. This seems to be a pretty straight-forward task as all I need is window.open (url is not hard-coded in the href as user need to get authenticated with the local server and get the token that will be used to access the document) but when it comes to Internet Explorer I got stuck with a weird problem. For versions 6-8, the first click on the pdf view link since the initial launch of IE browser always results in a blank window. User needs to either press F5 on the popped-up window click the view link (same or different) again get PDF loaded. The following code works without issues in all browsers except IE6-8:

HTML:

<a href="void(0)" onclick="javascript:opendoc('abc123')">View Document</a>

JS:

function opendoc(docid) {
    // skipping code getting token via ajax call
    var url="https://remote.host.url/somepath&docid="+docid+"&token="+token;
    var win=window.open( url, 'newwindow' );
}

Through a lot of trial and errors which include the followings:

  • refresh the new popup after some time
  • close the popup then open it again after some delay
  • server-side redirect
  • pdfobject
  • using embed tag

I found a workaround that actually works. Basically the same url got opened twice (only for the initial loading after launching browser) with 5 seconds apart if client browser is IE6-8. Note: The last two methods fail as well. I think it has something to do with the document.domain setting in the parent window.

Solution:

// this variable is to store if the double loading trick has been done
var first_clicked=0;
function opendoc(docid) {
    // skipping code getting token via ajax call
    var url="https://remote.host.url/somepath?docid="+docid+"&token="+token;
    var win=window.open( url, 'newwindow' );
    // using jQuery to do browser testing, feel free to use other methods
    if(!first_clicked && $.browser.msie && $.browser.version.substr(0,1)<'9') {
        setTimeout( function() {
            win=window.open( url, 'newwindow' );
        }, 5000 );
        // adjust the time to be shorter but be sure to
        // do enough tests as I found if the value is too low (300, 500, 1000 for example) it won't work either
        // it may have something to do with the connection speed to remote server
        
        first_clicked=1; // set to 1 so sequential clicks open the link only once
    }
}

This doesn’t seem to be a perfect fix as it still requires user to wait for a few seconds before the first result can be viewed but it’s better than leaving user in the dark or asking them to press F5 in order fix the problem.

Get javascript function definition through this trick

February 7, 2012 Leave a comment

In Google Chrome javascript console or Firefox firebug console, type the following and followed by Enter key:

function_name.prototype.constructor

where function_name is the function you want to find out its definition. Learned this trick through
http://stackoverflow.com/questions/5469691/find-js-function-with-firebug.

Categories: debugging, javascript
Follow

Get every new post delivered to your Inbox.