## Playing with Reactive Programming

I want you to consider the following program and think about the output logged in the console,

 var a = 10; var b = a + 1; a = 20; console.log(b);

view raw
simple.js
hosted with ❤ by GitHub

Is it 11 or 21? As most of you would guess correctly, the answer would be 11. That’s because, once the value of b is computed, it is no longer dependent on the value of a. As a result,  changing the value of a does not change the value of b.

Suppose the value of a changes over time, e.g., it may be a user input from a webpage that can be modified by the user anytime. And we want b to be calculated as soon as a is changed. A new programming paradigm called Reactive Programming is used for such problems.

An example of Reactive Programming would be a spreadsheet. If you have used it before, you know that when you write a formula for a cell like “=A1+B1″, the value of the cell gets modified as soon as the value in either cell A1 or cell B1 is modified.

Let us now modify our example using Reactive Programming. The value of a is going to change every 3 sec, and as soon as it does, b will be modified. The resulting reactive program is following:

 var a = Rx.Observable.create(function(observer) { setInterval(function() { var curA = Math.floor((Math.random() * 100) + 1); console.log("Current value of a " + curA); observer.onNext(curA); }, 3000); }); var b = 0; a.subscribe(function(val) { b=val+1; console.log("Current value of b " +b); });

view raw
simple-rx.js
hosted with ❤ by GitHub

The above example is implemented using RxJs, a popular reactive library for JavaScript. Let’s define few terms before we analyze the example. An Event Stream generates events over time. In our case, a is an event stream that generates a new random value every 3 sec. An event stream can be subscribed to, meaning whenever a new event happens all the subscribers will be notified. In this example, we have a subscriber for a, which means whenever a is changed, i.e., it has a new value, b is modified. If you want to test this example, you can download it from here (for the sake of brevity this example does not include proper error handling and cleanup).

1. Jafar Husain (from Netflix) explains Reactive Programming based on known design patterns and how it is being used in Netflix. [video]
2. Why do we care about reactive systems – The Reactive Manifesto. [link]

## Override the Default Login to provide Customized Identities in Windows Azure Mobile Services

It is very easy to override the default login feature (accessible by /login/[provider] endpoints) of the Windows Azure Mobile Services and customize it according to the need of your app. In this blog post, I am going to discuss how to do that, in particular, we want to be able to do the following:

1. Add custom claims to the identity (the ability to provide authorization after authentication). In this example, we will add custom claims to the facebook identity.
2. Add a new oAuth identity provider (in addition to the ones supported by the Windows Azure Mobile Services). In this example, we will add Foursquare as the new identity provider.
4. Add support for multiple apps using the same backend. It is necessary, if you have a public API exposed and other people are making apps using your backend.

In this post, I am going to use the oAuth flow described in my previous blog post, which is:

1. the app verifies the identity of the user elsewhere, i.e., native facebook app, and acquire an access_token,
2. this access_token is used to login to Windows Azure Mobile Services.

But, the examples are easily extendable to any standard oAuth flow.

## oAuth Flow for Mobile Apps with An External Identity Server

It is very common for mobile apps to depend on external login (like Facebook). In this article, we are going to discuss the oAuth flow for the following scenario:

1. The user’s identity is verified by an external server, i.e., external authentication.
2. The user’s access to a protected resource, i.e., an API endpoint, is determined by the internal server, i.e., internal authorization. In other words, the resource server and the authorization server in the oAuth 2.0 specification is the same server.

First, I will discuss the process and then I will give an example.

### The oAuth Flow for the above scenario:

1. The client, i.e., the mobile app, calls the external identity server and verifies the users identity. On a successful verification, it receives an token from the identity server. We will call it authorization_grant.
2. The client sends the authorization_grant to the internal authorization server. The authorization server has a trust relationship with the identity server. So, it sends the authorization_grant to the identity server. If the identity server cannot verify the authorization_grant, it sends back 401 unauthorized to the authorization server, which it propagates to the client. If, however, the identity server successfully verifies the authorization_grant, then it sends back the user info to the authorization server. The authorization server checks the permissions of the user (by querying the database database or some other methods) and generates a token. We will call it the access_token. A typical access_token contains the user’s identity, permissions, and an expiry time. The authorization server sends back this access_token to the client.
3. The client embed this access_token with each request for the protected resource, i.e., calling API endpoint. Depending on if the user is allowed to access the resource, he either gets it or receives 401 unauthorized.

## Building your own API and Securing it with oAuth 2.0 in ASP.NET WebAPI 2

Objectives:

1. Make a true RESTful Web API (enable CRUD functions by HTTP POST, GET, PUT, and DELETE).
2. Enable Cross-Origin Resource Sharing, i.e., CORS (the accessibility of the API by JavaScript can be controlled).
3. Enable Secure Authorization for API calls (use the OAuth 2.0 authorization framework).
4. Enable Transport Layer Security, i.e., SSL (reject every non-HTTPS request).

## Getting started with Apache Thrift

[Prereq: Windows, Visual Studio, Eclipse]

How it started:
Recently I have been introduced with a very cool technology called Apache Thrift. It is originally developed by Facebook and later open-sourced in Apache Software Foundation. It is one of the core building block of the Facebook technology. The technical paper introducing Thrift can be found here.

What is it:
In layman’s terms, Thrift allows an application written in one language (e.g., Java) to exchange data with an application written another language (e.g., C#). Probably the most popular technology in this area is SOAP. Although SOAP is more general, but Thrift has less overhead. In technical terms, Thrift is a Remote Procedure Call (RPC) framework that can be used to develop scalable cross-language services. Thrift is an interface definition language, i.e., you can only write interfaces or pure abstract classes by Thrift. The Thrift compiler can generate corresponding classes and interfaces for any particular language (e.g., C#) from the Thrift interface. The server (e.g., C#) should implement these interfaces and start a service, and the client (e.g., Java) can call the functions of these interfaces by communicating with the service.

## A crack at Dynamic Programming

Dynamic Programming is a discrete optimization technique. It means, the variables we want to calculate using this method are discrete. As an example, if x is one such variable then $x\in\{1,2,3,4\}$ is acceptable, but ‘x is a real number between 0 and 1′ is NOT acceptable since there are infinitely many real numbers between 0 and 1. In math terms, we can say that the domain of the variable x is a countable set.

Problems that are solved by dynamic programming are recursive nature. Let’s look at the problem that ask us to calculate the sum up to a number, i.e., if $f_s$ is such a function then $f_s(5)=0+1+2+3+4+5$. The recursive definition (assuming i is non negative) is following:

$f_{s}(i)=\begin{cases}0 & ,i=0\\i+f_{s}(i-1) & ,i\geq1\end{cases}$

## A Simple AS3 Logging Library using the Chain Of Responsibility and Singleton Pattern

Few years back, I wrote a simple logging library in ActionScript3 using the Chain of Responsibility pattern. Recently, I dug up the old codes, made some modifications, and put it in github for other people to use and contribute. In this post, I will mainly focus on how to use the library and do some project specific modifications, but  I will also briefly discuss my reasons for using the Chain Of Responsibility and the Singleton Pattern. I started writing this library with the following 4 goals in mind:

1. It should be easily accessible to all of the classes of a project.
2. It should be able to write logging information to different output sources, i.e., file, database, console, etc., and additional output sources can be added easily.
3. It should be able to handle different levels of logging like FATAL_ERROR or INFO (as different actions may be needed for handling different levels), and additional levels can be added easily.
4. It should require minimal setup.

## Legends of the C Pointers

When people ask me what my first language is, I sometimes playfully answer, “C”. C taught me what it meant to be a programmer. Few days back when I decided to start hacking the linux kernel again, I realized how much I miss programming in C. Playing with the pointers was undoubtedly the best part! So, I thought I would write this post.

If you have irrational fear of pointers or preparing for a C interview or just want to have fun, you should read this post! I am assuming you know the basics of pointers, but just cannot get a total hold on them.

I will start by stating a quote by Joel Spolsky:

I don’t care how much you know about continuations and closures and exception handling: if you can’t explain why while(*s++ = *t++); copies a string, or if that isn’t the most natural thing in the world to you, well, you’re programming based on superstition, as far as I’m concerned: a medical doctor who doesn’t know basic anatomy, passing out prescriptions based on what the pharma sales babe said would work.

## Limits of the Effeciently Computable: Rise of the Quantum Computers

“I don’t believe in Computer Science.”~ Richard Feynman at Bell Labs (1985).

Feynman argued that science is the study of the behavior of the nature. He pointed out the limitations of classical computers for simulating the nature, which is very difficult because nature is quantum mechanical. At his lectures at Caltech, Feynman talked about the limitations of computation due to mathematics, noise, thermodynamics, reversible computing (where it is possible to compute and un-compute), and quantum mechanics. He predicted a new type of computer that is not a Turing machine, which he called a quantum computer. Continue reading

## Super-rational Pirates

“There has not been a king since the first brethren court, and that is not likely to change!”, Captain Chevalle sighed. Elizabeth Swann wondered, “Why not?”. “Because the pirate king is elected by popular vote…”, as Mr. Gibbs started to explain, Captain Barbossa finished the sentence, “…and each pirate only votes for himself.”~Pirates of the Caribbean.

Yesterday I was having lunch with my friends Jocelyn, Johnson, and Adrian. One thing lead to another, we started talking about pirates. In one of her interviews, Jocelyn came across a question about how a senior pirate would divide some gold coins among 4 other pirates so that they would not vote to kill him. It was immediately apparent that the senior pirate would not give any gold to 2 of the pirates, but how much he should give the other 2 pirates was not obvious to me. It was stuck in my mind. I concluded that there must be some missing pieces of the question. It turns out that this problem is of a significant theoretical interest to many people. Let’s define the problem first.

There are 5 pirates of different ranks in a ship and they have a treasure of 100 gold coins. The current highest ranking pirate will divide the coins, and all 5 pirates will vote for or against it. If half or more of the pirates vote for it, then the coins will be divided that way. Otherwise, the pirate proposing the scheme will be killed, and the process is repeated with the pirates that remain. The most important thing for a pirate is his life. After that he wants to get as much coins as possible. As every pirate is bloodthirsty, if voting for or against will give him the same number of coins, he will vote against so that the pirate who proposed the plan will be killed. All 5 pirates are intelligent, rational, and good at math. How will the highest ranking pirate divide the coins?