Yet another Javascript library – React

Let’s say hello to yet another popular library in the Javascript world – React. In the last few weeks, I wanted to pick up something new and was wondering between learning React or Angular.

But, as I was reading doing more research into this topic, I found out that Angular 1.4 was going to be eclipsed in the near future by Angular 2 – which kind of makes learning Angular 1.4 rather unappealing. So, React it was.

Here, I am going to show you a rather simple app I built with React and RefluxJS. The idea behind the app is rather basic – we’re going to find out the weather of a city given the zipcode and country.

If you’re interested in how it looks like, check it out here.

The app is broken down into a few small components.

  • Form component – zipcode and country fields
  • Preview component – weather data
  • Both of the components above will be encompassed by the weather app.

On top of using React, I also used RefluxJS, which is another library that uses the Flux architecture pattern proposed by Facebook. If you’re wondering about Flux, find out more via the link above.

So, following the Flux pattern, I needed to define stores and actions for my app. I only had a single store, that is the WeatherStore that stored all the weather data pertinent to my application.

The first interesting thing to note here is the code for the WeatherStore. I have added a lot of comments to each method for a better idea on what is being done.

The next code we’re going to look at is WeatherActions. You might be surprised at the length of this file, but it’s very succinct.

Now, on to the React portion. This is the first component we’re going to be building. This component houses the preview and the form. If you’re someone who is used to separating the presentation layer from the logic, this might seem a little hackish. But as usual, give sometime for new ideas to simmer and you might just see how this could make development easier.

The next portion is the form the user will be using to enter the zipcode and country. This data will be passed on to the WeatherStore.

In this portion, we will be using the data received from WeatherStore to show a preview of the weather.

This final one shows how the code will be rendered to the page.

Testing the waters with Python’s list comprehension

You might have seen those cryptic code in Python where someone does something peculiar in a list like this. When you first encounter this, you brain just goes into a spin cycle, wondering what the heck is going on.

[x*x for x in list]

Rest assured, I am going to try my best to help you decipher the code above. The cryptic code above is simply the more concise way of doing this

squares = []
for x in list:
return squares

Before we jump into the examples, lets break down the process by taking a look at the simple diagram.
Basic list comprehension

The diagram breaks out the list comprehension into 2 parts, the first part is the result we want, the second part is the list being iterated over. This list comprehension is pretty simple and it does not contain any conditional clauses.

The next diagram will show you how we can add conditional clauses to list comprehension to make it even more powerful.

Screenshot from 2015-05-20 22:29:00

Now, let us jump into some examples. I got the exercises here and I solved it to the best of my abiliIties to get a better grasp of list comprehension.

Provide an implementation for zip function using list comprehensions.
zip([1, 2, 3], [“a”, “b”, “c”])
[(1, “a”), (2, “b”), (3, “c”)]

Provide an implementation for map using list comprehensions.

def square(x): return x * x
map(square, range(5))
[0, 1, 4, 9, 16]

Provide an implementation for filter using list comprehensions.

def even(x): return x %2 == 0

filter(even, range(10))
[0, 2, 4, 6, 8]

Write a function enumerate that takes a list and returns a list of tuples containing (index,item) for each item in the list.

enumerate([“a”, “b”, “c”])
[(0, “a”), (1, “b”), (2, “c”)]

Write a function array to create an 2-dimensional array. The function should take both dimensions as arguments. Value of each element can be initialized to None:
a = array(2, 3)
[[None, None, None], [None, None, None]]

Min and max the hard way

In this mission you should write you own py3 implementation (but you can use py2 for this) of the built-in functions min and max. Some builtin functions are closed here: import, eval, exec, globals. Don’t forget you should implement two functions in your code.

Yet another solved puzzle from Checkio. I commented the code pretty heavily to indicate why I decided to go down the path I did. There are probably tons of better ways to solve this.

Numbers to Roman Numerals

I have to admit that I didn’t really know how to build a string of Roman numerals before. I knew how numbers 1-10 were represented, but otherwise, not a clue. So, when I had a chance to work on this problem, it was really intriguing to find out that the logic behind it was not too complicated. Take a look at the code below on how to easily produce Roman numerals from a number. Again, this problem is courtesy of

Do I know you?

This is the problem highlighted by

Sophia’s drones are not soulless and stupid drones; they can make and have friends. In fact, they already are working for the their own social network just for drones! Sophia has received the data about the connections between drones and she wants to know more about relations between them.

We have an array of straight connections between drones. Each connection is represented as a string with two names of friends separated by hyphen. For example: “dr101-mr99″ means what the dr101 and mr99 are friends. Your should write a function that allow determine more complex connection between drones. You are given two names also. Try to determine if they are related through common bonds by any depth. For example: if two drones have a common friends or friends who have common friends and so on.

The journey towards becoming a Pythonista

My latest job requires me to do Python day in and out. As I have only mostly used Python for scripting and data analysis, I don’t really know the ins and outs of Python as much as I would like. So, as an exercise, I decided I will take a look at and start playing for real. The journey has been interesting so far and I hope to be a better Python coder through these exercises.

As part of my learning journey, I am going to share the code here on my blog with heavy annotations so that others can understand my approach and perhaps offer better solutions.

Prototypal inheritance in Javascript

When you hear about inheritance in Javascript, you most likely think about how inheritance works conventionally in other languages like Java. Class B inherits from Class A and so on…

In Javascript, classes aren’t really part of the language, however much you might want it to be. Although ECMAScript 6 will introduce the notion of classes, it will merely be syntactic sugar on top of the prototype based inheritance we will be going through.

So, here, I want to run through an example that will be a little more than, “hey, a Cat inherits from Animal” example and show a little more elaborate example in how we can utilize prototypal inheritance in Javascript. Since I currently work in an industry surrounded by all types of coupons, I am going to use coupons as the basis of the example. So, let’s go.
Continue reading

Taking map reduce for a fun ride

Last year, I began a serious foray into data. Armed with Murach’s SQL book, I took an intense one week deep dive into SQL as I needed to do something critical at work with it and had no time to dawdle. Along with the book, I spent countless hours in Coursera on a SQL class that had old lecture materials online. That was my first exposure to fun ways of making sense of data.

Then came a hack day where I teamed up with several exciting individuals to begin another phase of data – big data. That in turn has led me to the Data Science course that is currently being offered in Coursera. The class so far has been an eye opener to my rather limited experience in big data.
Continue reading

Using jQuery.Deferred to control UI flow

I’ve seen tons of examples on the web about how to use promises. Most invariably show how to use in Ajax requests to handle callbacks which although very useful in that context, makes me think that is all it’s useful for.

Then, I picked up this slim book, Async Javascript by Trevor Burnham that showed how I can use promises to model user interface flows. This piqued my interests as I could really see how this could be useful.

Continue reading

Design Pattern: State in PHP

Next on from the Head First Design Patterns is the “State Pattern”. The State Pattern allows an object to alter its behavior when its internal state changes. By altering its behavior, the object can perform a different set of operations. To truly understand this pattern, let’s take a look at an example. A sales order can have many different states such as “New Order”, “Invoicing”, “Processing”, “Shipped”. Before the sales order can be moved forward to a different state, there are strict rules that need to be obeyed.
Continue reading

Design Pattern: Decorator in PHP

Now, on the next series from the Head First Design Patterns book – the decorator pattern. The decorator pattern is used to attach additional responsibilities to an object dynamically. This provides a more flexible alternative to subclassing in order to add on more functionality.

When does this get used? Say for example you’re writing an point of sale system for a pizza store. Customers can choose from a variety of toppings to be added on to the pizza. You could have a super class that identifies all the toppings, but as new toppings get added or old toppings get removed, that super class is going to be going through a lot of changes. The decorator pattern comes to the rescue here by allowing us to add just a new class for the new topping.
Continue reading

Design Pattern: Facade in PHP

Continuing with the Head First Design Patterns book is the facade pattern. Facade is another design pattern in PHP. The facade pattern is used to provide a simplified interface and to hide the complexity of the actual work going on behind. When does the facade get used? The most basic example is your computer. Say you have Windows 7. Windows 7 provides an interface for you to find your files, to change your background and so forth. But beneath Windows 7, there are multiple independent applications that actually do the work, but Windows 7 provides a unified theme for all these interactions.
Continue reading

Design Pattern: Adapter in PHP

The next part in the Head First Design Pattern series covers the “Adapter Pattern”. Say for example you worked on an API. The API is out in the wild and is being used widely. Then the changes for the API come rolling in and you have to redesign the implementation. But, since you already have users using the API, you need to resort to a less disruptive solution. What do you do? Rewrite the old functions? An easier way would be to create an interface that would convert the old public interface of your API to the new interface.
Continue reading

Design Pattern: Command in PHP

The next pattern from the Head First Design Patterns book is the Command Pattern. The command pattern allows decoupling of an action’s requester and the actual object that performs the action.

The command pattern can be broken down into three parts:

  • invoker – is the link between commands and receiver. It also houses the receiver’s and each command as they are sent.
  • command – object that encapsulates request send to receiver.
  • receiver – component that is acted upon by each request

Continue reading

Design Pattern: Singleton in PHP

This is the third of my Head First Design Patterns post. This time, I am going to be porting the Singleton pattern from Java to PHP.

The Singleton pattern is used to create one of a kind object where there should only be a single instance. i.e. thread pools, logging, caching and etc. It also gives a global point of access to the rest of the application to access the instance, but without polluting the global namespace.

The example below shows how the singleton pattern works. Although two chocolate boilers are requested, the code ensures only one instance gets created.

Continue reading

Design Pattern: Observer in PHP

My second design pattern is the observer. As mentioned in the first design blog entry, the code comes from Head First Design Patterns.

When do we use the Observer pattern? The Observer pattern is responsible for communicating state changes to other classes that are assigned to observe them.
Continue reading

Design Pattern: Strategy in PHP

As part of my ongoing self education, I decided to delve more into design patterns to fully appreciate the art of software design. My book of choice for this learning process was “Head First Design Patterns“. As the code samples were in Java, I decided to port the code to PHP so that others who are interested in the book, but are more familiar with PHP can see how it could be achieved with equal ease.

When does the strategy pattern get used? If you have several objects that are almost similar, but only differ in behavior. For example, the sample code from Head First Design Pattern says there are many types of ducks, but each duck has it’s own special way of flying and quacking.
Continue reading

BoostMe: An HTML5 Goal Tracking App

In my day job, I have to be pragmatic. That means although I am eager to try out new things right away, I have to weigh the pros and cons and the impact it might cause my unsuspecting users. I need to think about backward compatibility, about supporting browsers as old as Father Time and the list never ends. Although those daily exercises provide challenging and intriguing ways of working with old and new technology, I admit I always dream about how it would be to work in a world where IE6 or even IE7 is merely a dream, where I could care less of using a library to achieve cross browser compatibility and blah blah blah …
Continue reading

Facebook App Authorization In A Tab (Javascript)

I have been working a lot recently with the Facebook API at work. Unfortunately, I have been encountering a steep learning curve for Facebook API due to the lack of documentation and good sample code. So, here I have decided to provide little snippets of code that will help someone in their Facebook journey. This will hopefully be the first of many installations.
Continue reading