Norway – The land of fjords

Being born and brought up among the Himalayas, I’ve always been in love with mountains. Staring at them, while appreciating their sheer size and greatness, gives me immense peace. Although my main reason for visiting Norway was to experience the Northern Lights, seeing the pictures of Norwegian landscape was more than enough to visit this beautiful Nordic country and I’m so glad I did. Norway just blew me away with its stunning coastline, mountains, fjords and the Northern Lights.

In September 2014, I spent two weeks traveling through Norway as part of my trip across Northern Europe. I started with Tromso, a small and beautiful city above the Arctic circle. The whole city can be travelled on foot. There are a few museums and the world’s northernmost botanical garden. The most amazing view of the city can be seen from Mount Storsteinen. One can hike or reach there by cable car. I reached the top in the evening and stayed till it got dark.

Tromso

Tromso is a good place to see Northern Lights, which may or may not appear depending on how cloudy the sky is. I couldn’t see any the first two nights. The third day I took a day trip to Skjervoy, a small fishing village near Tromso. The bus goes through a very scenic route along the coast. While returning back to Tromso on a boat, I decided to go out to the deck hoping to see a glimpse of the Aurora Borealis or the Northern Lights. And there it was, spread all over the sky like threads of silk. Witnessing it for the first time in your life is indeed a magical moment. It was freezing outside and although chilled to the bone, I didn’t care about it anymore.

After having a wonderful time in Tromso, I took an 18 hour cruise to the Lofoten Islands. The ferry goes through the stunning landscape of Norwegian fjords, created during the ice age. The sheer amount of natural beauty throughout the route cannot be described in words. It feels so surreal that you wish you could capture those moments forever.

Fjords

In Lofoten, I couchsurfed at some locals who showed me around and took me to hiking. With hills all around and closeby, Lofoten is a great place for hiking. The sea is easily accessible so you could go diving or surfing. Just walking around the island was pleasant. You can experience amazing scenery, untouched beaches, mountains, sea, peace and serenity. At night, we went out to hunt the Northern Lights and both the nights, we got to see some intense display of colors.

Lofoten

After spending a couple of days in Lofoten islands, I headed down to Bodo by ferry. Bodo has the northernmost train station in Norway. From Bodo I took a train to Trondheim, one of the largest cities in Norway. There are quite a few museums and churches. I really liked the Nidaros Cathedral. The crowd is mostly dominated by students and there is decent nightlife as well. My main purpose of visiting Trondheim was to drive on the Atlantic Ocean road. If you like driving, I would strongly suggest you to rent a car and drive to Alesund. It’s a 600km roundtrip drive through the beautiful Norwegian landscape, the fjords, the Atlantic ocean road and the under sea tunnel. Definitely one of the best road trips in the world.

Atlantic Ocean Road
Image above is not owned by me

From Trondheim, I took a train south to Oslo, the capital and largest city in Norway. Oslo has a big city feeling with modern buildings, a metro system and quite a few good museums. I specially liked the Viking ship museum which houses the Vikings Age findings from 1000 years ago. Other interesting places to visit are the Vigeland museum park and the National Opera hall.

Viking Museum

After spending a day in Oslo, I left for Flam. The train route between Myrdal and Flam is beautiful. Flam is worth a visit but I did find it a little overrated considering the hype. I did not intend to spend the night in Flam and left for Bergen.

Bergen is a beautiful city surrounded by mountains and fjords. Even though it is the second biggest city in Norway, it doesn’t feel big. With picturesque houses and alleys, it has a unique flavour and feels cozier than Oslo. Like most other Norwegian cities, Bergen is nestled in nature with many outdoor and hiking opportunities.

The stunning landscape, pristine environment and untouched nature of Norway made it well worth a visit.

simplypoll – An open source online polling app built with Meteor

Last week I was trying my hands at Meteor, a full-stack javascript based framework for building web apps. It’s built on top of nodejs. Unlike the traditional way of building web apps, the client and the server are truly integrated here and share most of the code as well. I was greatly impressed by the power Meteor can bring to real-time app development. Although Meteor is not the only framework going this route, it’s the most popular and matured at the moment.

The best part about Meteor is that it is quite simple to begin with. Ofcourse you need some amount of expertise in javascript, but the concepts are easy to understand and it definitely helps if you are already a full-stack developer. After spending a few hours of digging through Meteor, it took me another few hours to come up with simplypoll. I spent some more time later to polish it. The app is open source and you can have a look at the code here.

Overall Meteor looks very interesting and I am definitely going to spend more time on it. If you wish to learn Meteor, I’d recommend Discover Meteor.

Building a Simple Quiz App using AngularJS

AngularJS has been out there for quite a while now and is getting increasingly popular. It is a very powerful Javascript MVC framework for building well-structured and maintainable web applications.

This tutorial is not an introduction to AngularJS but to demonstrate how quickly one can build a simple well-structured web application. This is targeted towards people who are already familiar with the basics of AngularJS.

The app will have a very simple structure – a single page app, one question at a time on the screen with four options, a submit button and score. For simplicity, there is no database of questions, instead we define a set of questions in the app itself. This will be the final output.

Let’s start building.

We need two html files for markup, one will have the main markup and the other will have the template for our quiz section. Let’s call them index.html and template.html. We also need an app.js file which will have our app logic and a style.css.

The markup in index.html is straightforward.

<!DOCTYPE html>
<html ng-app="quizApp">
    <head>
        <meta charset="utf-8" />
        <title>QuizApp</title>
        <link rel="stylesheet" href="style.css" />
        <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
        <script src="app.js"></script>
    </head>
 
    <body>
        <div class="container">
            <h1 class="title">QuizApp</h1>
            <quiz/>
        </div>
    </body>
</html>

The only two interesting things here are the ng-app attribute and the quiz tag. We will define a custom directive for the quiz tag later. Let’s go to the template now. The quiz template will replace the quiz tag above. It consists of 2 sections: a quiz section when the quiz is in progress and an intro section when the quiz app is loaded initially.

<div class="quiz-area" ng-show="inProgress">
</div>
 
<div class="intro" ng-show="!inProgress">
	<p>Welcome to the QuizApp</p>
	<button id="startQuiz" ng-click="start()">Start the Quiz</button>
</div>

As you notice, we used two built-in directives here: ng-show and ng-click. inProgress and start() will be defined later but are self-explanatory. In the quiz area, we either show a question or a message when the quiz is over. We also need a section for score.

<div class="quiz-area" ng-show="inProgress">
	<div ng-show="!quizOver">
	</div>
 
	<div ng-show="quizOver">
		<h2>Quiz is over</h2>
		<button ng-click="reset()">Play again</button>
	</div>
 
	<div id="score">
	</div>
</div>

In app.js we defined a custom directive called quiz. It looks like below:

var app = angular.module('quizApp', []);
 
app.directive('quiz', function() {
    return {
	restrict: 'AE',
	scope: {},
	templateUrl: 'template.html',
	link: function(scope, elem, attrs) {
	    //TODO
	}
    }
});

Now we need some methods to start a quiz, get a question and check the answer.

var app = angular.module('quizApp', []);
 
app.directive('quiz', function(quizFactory) {
	return {
		restrict: 'AE',
		scope: {},
		templateUrl: 'template.html',
		link: function(scope, elem, attrs) {
			scope.start = function() {
			};
 
			scope.getQuestion = function() {
			};
 
			scope.checkAnswer = function() {
			};
		}
	}
});

Let’s implement these methods now.

scope.start = function() {
	scope.id = 0;
        scope.quizOver = false;
	scope.inProgress = true;
	scope.getQuestion();
};

Here scope.id is the id of the current question. We used inProgress in the template and it will be true while the quiz is running.

To get a question, we need a source. We create a factory to get the questions. The factory will return a question when a given question id is requested.

app.factory('quizFactory', function() {
	var questions = [
		{
			question: "Which is the largest country in the world by population?",
			options: ["India", "USA", "China", "Russia"],
			answer: 2
		},
		{
			question: "When did the second world war end?",
			options: ["1945", "1939", "1944", "1942"],
			answer: 0
		},
		{
			question: "Which was the first country to issue paper currency?",
			options: ["USA", "France", "Italy", "China"],
			answer: 3
		},
		{
			question: "Which city hosted the 1996 Summer Olympics?",
			options: ["Atlanta", "Sydney", "Athens", "Beijing"],
			answer: 0
		},
		{	
			question: "Who invented telephone?",
			options: ["Albert Einstein", "Alexander Graham Bell", "Isaac Newton", "Marie Curie"],
			answer: 1
		}
	];
 
	return {
		getQuestion: function(id) {
			if(id < questions.length) {
				return questions[id];
			} else {
				return false;
			}
		}
	};
});

Now we can implement the getQuestion() method in our quiz directive.

scope.getQuestion = function() {
	var q = quizFactory.getQuestion(scope.id);
	if(q) {
		scope.question = q.question;
		scope.options = q.options;
		scope.answer = q.answer;
	} else {
		scope.quizOver = true;
	}
};

Now we can go back to our template and fill the details.

<div class="quiz-area" ng-show="inProgress">
	<div ng-show="!quizOver">
		<h2 id="question">{{question}}</h2>
		<ul id="options">
			<li ng-repeat="option in options">
				<label>
					<input type="radio" name="answer" value="{{option}}">
					{{option}}
				</label>
			</li>
		</ul>
		<button ng-click="checkAnswer()" ng-show="answerMode">Submit</button>
 
                <div ng-show="!answerMode">
			<button ng-click="nextQuestion()" class="next-question">Next</button>
			<span ng-show="correctAns">That is correct!</span>
			<span ng-show="!correctAns">Sorry, that is an incorrect answer.</span>
		</div>
	</div>
 
	<div ng-show="quizOver">
		<h2>Quiz is over</h2>
		<button ng-click="reset()">Play again</button>
	</div>
 
	<div id="score">
		Score: {{score}}
	</div>
</div>

The checkAnswer() method needs to compare the selected option with the correct answer. We also need answerMode so we display the options or the result of current question accordingly. When the user clicks ‘Next’, we need to go to the next question. nextQuestion() does that. Our quiz directive looks like below now:

app.directive('quiz', function(quizFactory) {
	return {
		restrict: 'AE',
		scope: {},
		templateUrl: 'template.html',
		link: function(scope, elem, attrs) {
			scope.start = function() {
				scope.id = 0;
				scope.quizOver = false;
				scope.inProgress = true;
				scope.getQuestion();
			};
 
			scope.reset = function() {
				scope.inProgress = false;
				scope.score = 0;
			}
 
			scope.getQuestion = function() {
				var q = quizFactory.getQuestion(scope.id);
				if(q) {
					scope.question = q.question;
					scope.options = q.options;
					scope.answer = q.answer;
					scope.answerMode = true;
				} else {
					scope.quizOver = true;
				}
			};
 
			scope.checkAnswer = function() {
				if(!$('input[name=answer]:checked').length) return;
 
				var ans = $('input[name=answer]:checked').val();
 
				if(ans == scope.options[scope.answer]) {
					scope.score++;
					scope.correctAns = true;
				} else {
					scope.correctAns = false;
				}
 
				scope.answerMode = false;
			};
 
			scope.nextQuestion = function() {
				scope.id++;
				scope.getQuestion();
			}
 
			scope.reset();
		}
	}
});

As we see, within 100 lines of javascript code we built a simple but fully functional quiz app. Also the markup is pretty expressive and anybody going through it can grasp the logic fairly quickly. That’s the beauty of AngularJS 🙂

You can see the implementation here.
The full source code can be viewed at my GitHub repository.

Slot machine in Javascript

Recently somebody talked to me about creating a slot machine. I looked on the web and could not find any good slot machine implementation in javascript. So I decided to write a quick one. My implementation uses jquery and a couple of jquery plugins for animation. Spritely is a wonderful jquery plugin for background animation. I also used a plugin for animating background-position since jquery does not support it natively.

Lets start building the slot machine. Demo here

First of all we need a sprite for our slot machine. This sprite is basically a reel which in motion simulates a slot. Its preferable to have blurred copy of this reel too, to show the effect of motion. For the purpose of this demo I got the sprite from internet.

The markup is very straightforward. We just need placeholders for 3 slots and a button as controller.

Lets got through the javascript now. First we need a class for a slot. Our 3 slots will be objects of this class.

function Slot(el, max, step) {
    this.speed = 0; //speed of the slot at any point of time
    this.step = step; //speed will increase at this rate
    this.si = null; //holds setInterval object for the given slot
    this.el = el; //dom element of the slot
    this.maxSpeed = max; //max speed this slot can have
}

Why do we need so many paramaters for a slot machine? That’s because each slot of an ideal slot machine should have different acceleration and speed. Also its good to have different max speeds.
Our Slot class will have 4 member functions:

  • start() – starts a slot
  • stop() – stops a slot
  • finalPos() – finds the final position of the slot when its stopped
  • reset() – Resets a slot for another run

How it works?

Initially we create an object for each slot of the slot machine. We pass different values for the max-speed and speed-stepper to the constructor.

var a = new Slot('#slot1', 30, 1),
    b = new Slot('#slot2', 45, 2),
    c = new Slot('#slot3', 70, 3);

When a user presses ‘Start’, start method is called for each slot. This method kicks off the slot and increments the speed at regular intervals. This can be done using setInterval. Code below:

Slot.prototype.start = function() {
    var _this = this;
    $(_this.el).addClass('motion');
    $(_this.el).spStart();
    _this.si = window.setInterval(function() {
        if(_this.speed < _this.maxSpeed) {
            _this.speed += _this.step;
            $(_this.el).spSpeed(_this.speed);
        }
    }, 100);
};

Once all the slots reach their maximum speeds, the ‘Stop’ button is enabled. When the user presses ‘Stop’, the speed of the slots start decrementing.

Slot.prototype.stop = function() {
    var _this = this,
        limit = 30;
    clearInterval(_this.si);
    _this.si = window.setInterval(function() {
        if(_this.speed > limit) {
            _this.speed -= _this.step;
            $(_this.el).spSpeed(_this.speed);
        }
        if(_this.speed <= limit) {
            _this.finalPos(_this.el);
            $(_this.el).spSpeed(0);
            $(_this.el).spStop();
            clearInterval(_this.si);
            $(_this.el).removeClass('motion');
            _this.speed = 0;
        }
    }, 100);
};

Once the speed comes below a certain threshold, the final position is calculated for each of the slots based on their current position and the slots are rotated to reach the final position.

Slot.prototype.finalPos = function() {
    var el = this.el,
        pos,
        posMin = 2000000000,
        best,
        bgPos,
        i,
        j,
        k;
 
    el_id = $(el).attr('id');
    pos = document.getElementById(el_id).style.backgroundPosition;
    pos = pos.split(' ')[1];
    pos = parseInt(pos, 10);
 
    for(i = 0; i < posArr.length; i++) {
        for(j = 0;;j++) {
            k = posArr[i] + (imgHeight * j);
            if(k > pos) {
                if((k - pos) < posMin) {
                    posMin = k - pos;
                    best = k;
                }
                break;
            }
        }
    }
 
    best += imgHeight + 4;
    bgPos = "0 " + best + "px";
    $(el).animate({
        backgroundPosition:"(" + bgPos + ")"
    }, {
        duration: 200
    });
};

Demo
You can see the implementation here.
The full source code can be viewed at my GitHub repository

Trie implementation in Javascript

A trie, or prefix tree, is a multi-way tree structure useful for storing strings over an alphabet. It is very efficient and handy and can be used for various purposes like auto-complete, spell-check, dictionary search, etc.

The basic idea of a Trie goes as below:

  • We have a root node which represents an empty string.
  • Every other node either represents a word or a prefix of one or more words.
  • Each node can have atmost as many children as the size of the alphabet.

Trie example

The above diagram shows a trie which stores the words “A”, “to”, “tea”, “ted”, “ten”, “i”, “in”, and “inn”.

Below is my implementation of Trie in javascript:

At each node of Trie, I store the word-count, prefix-count and the link to children.

Trie = function() {
    this.words = 0;
    this.prefixes = 0;
    this.children = [];
};

To insert a word, I recursively traverse through the trie nodes if they already exist, else I create new nodes. While traversing the nodes, I keep on storing the information in the nodes as I encounter each character in the given string.

insert: function(str, pos) {
    if(str.length == 0) { //blank string cannot be inserted
        return;
    }
    var T = this,
        k,
        child;
    if(pos === undefined) {
        pos = 0;
    }
    if(pos === str.length) {
        T.words ++;
        return;
    }
    T.prefixes ++;
    k = str[pos];
    if(T.children[k] === undefined) { //if node for this char doesn't exist, create one
        T.children[k] = new Trie();
    }
    child = T.children[k];
    child.insert(str, pos + 1);
}

Removing a word follows the similar idea as insertion.

To update, I simply remove the existing word and insert the new word.

Searching a word is trivial as we just need to check if the word count at the terminating node of the input string is greater than zero or not.

find: function(str) {
    if(str.length == 0) {
        return false;
    }
    if(this.countWord(str) > 0) {
        return true;
    } else {
        return false;
    }
}

You can get the full source code in my GitHub repository

Meanwhile you can see the auto-complete demo using my trie implementation

Links:

Snake in Javascript

This weekend I spent a few hours to write the classic game of Snake in javascript. There are already many versions of Snake available on the web. This was just some fun way to practice javascript. I used YUI 2 for event and dom handling. I have already written a few games in other languages like C++ and Basic during school/college days but this is my first game in Javascript. Will try to write better games in the future probably using HTML5 which can give a much better experience.

The game can be played at http://odhyan.com/snake/

The javascript code can be viewed at http://odhyan.com/snake/snake.js

Caching in Javascript (YUI Cache)

Today I read about YUI 3 Caching Utility. It allows to cache frequently used data in javascript memory (Basic caching) or HTML5 localStorage object (Offline caching). Although we can implement our own caching mechanism in javascript, the YUI caching is general purpose and also provides a set of events. Moreover it can be easily integrated with YUI Datasource which can be very beneficial.

I’ll show you how useful YUI caching utility can be using a very standard example, Factorial. Here I’ll only cover basic caching.

Let’s write a factorial program in javascript without any caching/memoization:

YUI().use('node', function() {
    // method to calculate factorial
    var factorial = function(n) {
        if(n === 0 || n === 1) {
            return 1;
        } else {
            return n * factorial(n-1);
        }
    }
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

Try increasing the value of MAX and you’ll see that your browser may get very slow/crash. My firefox keeps on running the script and then shows a dialog box to stop the script. I assume all must be familiar with factorial and should be able to understand why this program is highly inefficient.

Now lets write another factorial program using our own caching mechanism:

YUI().use('node', function() {
    // create a cache class
    var MyCache = function() {
        this.memo = [];
    };
    MyCache.prototype.add = function(key, val) {
        this.memo[key] = val;
    };
    MyCache.prototype.retrieve = function(key) {
        return this.memo[key];
    };
    // a new cache object
    var cache = new MyCache();
    // method to calculate factorial
    var factorial = function(n) {
        var ret;
        if(n === 0 || n === 1) {
            return 1;
        } 
        ret = cache.retrieve(n);
        if(ret !== undefined) {
            return ret;
        } else {
            ret = n * factorial(n-1);
            cache.add(n, ret);
            return ret;
        }
    };
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

The above code runs smoothly even if we increase the value of MAX(even 5000 should be fine although 5000! doesn’t make sense). That’s because we cache the value of every factorial we calculate and then reuse it for the next calculation.

Now lets write the same program using YUI caching utility:

YUI().use('cache', function(Y) {
    // create a yui cache object
    var cache = new Y.Cache({
        max:100
    });
    // method to calculate factorial
    var factorial = function(n) {
        var ret;
        if(n === 0 || n === 1) {
            return 1;
        }
        ret = cache.retrieve(n);
        if(ret !== null) {
            return ret.response;
        } else {
            ret = n * factorial(n-1);
            cache.add(n, ret);
            return ret;
        }
    }
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

This also runs smoothly for large values of MAX.

For this particular example, implementation 2 (using our own caching) will be slightly more efficient than the YUI version due to the simplicity, but in more complex examples, YUI caching utility can be quite useful.

You can read more about the YUI Cache here.

Related links:

YQL – Yahoo! Query Language

Recently I have been reading about YQL. YQL is a great idea that came out of Yahoo! and is an awesome tool for developers. Basically YQL allows you to fetch information from the web using SQL like syntax. Yahoo! provides a good number of open data tables and many more are contributed by the open source community. Check out the community page at http://datatables.org.

I was just playing around with the stuff and built a small example application as a YQL demo. This app fetches movie information from IMDB. I used the open data table created by CerealBoy. The way it works is it scrapes the HTML from IMDB and extracts the needed information. In this example, YQL acts as a proxy and easily solves the cross-domain AJAX problem.

Checkout the demo here: http://odhyan.com/yql/movies/

Links:

ACK – Better than GREP

One of the most useful tools in unix is grep. Almost every unix/linux user use it frequently. But not many know about a tool which is better then grep – ack. It makes life so easy for you. Some of the features that made me switch to ack:

  • Lot faster than grep.
  • Default recursive search.
  • Ignores most of the crap you don’t want to search: SVN, CVS, binary files, etc.

So instead of doing

grep -r ‘string’ . | grep -v ‘\.svn’ | grep -v ‘FreeBSD’

I can do

ack ‘string’

  • By default searches only the files that it recognizes. You can edit the list of files so that ack can recognize them or use a flag to search all files.
  • Color highlighting of search results.

Since ack is written in perl, it has ports for both mac and windows.

So if you haven’t used ack yet, give it a try. Trust me, you’ll love it.