New Year Resolution: deep dive in JavaScript

My New Year resolution is to become a master in JavaScript. This blog post will serve more as a reference to me where I can come back to and review things that I have written. Also the act of writing helps me fossilize in my brain these concepts.

I will start by reviewing the concepts I know about Objects, Arrays and Functions.

Update: Jan 20th Adding Nested data, Scope notions as well.

Arrays and objects are ways to organize data in Javascript(JS).


JS allows us to create objects in object literal notation, such as:

var Santa = {};

This Santa is a bit empty so let’s add some properties. Properties are the keys in a key-value data structure.
It looks like this:

 {username: "hack_thon", age: 23} //where 'username' and 'age' are the properties

Continue reading “New Year Resolution: deep dive in JavaScript”

A Simple But Effective Way to Contribute to Open Source Projects

I use open source code every day. Be it Rails or the myriad of Ruby gems out there, open source is part of my life and work.

To show gratitude to those who volunteered thousand of developing hours to these projects, I often search ways in which I can contribute to them too. Until recently I simply didn’t know how my contribution could be meaningful. But I may have found a simple but effective way to contribute to open source projects.

It all started when I used the MetaInspector gem in one of my projects. After using it, I thought about the amount of time it saved me in developing a url scraping feature I had to do. So I decided to check the gem repo to see if I could add anything to it. I had a look at the issues, looked at the documentation, forked the repo and ran the tests. It was when I noticed that that was some deprecation warnings showing in RSpec. The most recent RSpec is 3.0 so I saw a chance there to update Rspec and to include the new RSpec syntax in the gem tests.

Once I updated the tests, I submitted a pull request and added my comments.
Screen Shot 2015-01-30 at 12.02.13 AM

Jaime Iniesta, the maintainer of the gem, replied to me within minutes.
Screen Shot 2015-01-30 at 12.01.55 AM

I was exhilarated! A simple but relevant contribution was well on its way. I made the modification he suggested and again within minutes I received a feedback.
Screen Shot 2015-01-30 at 10.52.20 PM

My own small but meaningful contribution to an open source project. It made me feel great that day! This experience also made me realize that contribution can be something such as updating tests in gem, adding some CSS to redesign a gem website or write documentation. I hope this post inspires you to contribute something simple but effective in its own way.

It Is Not Who you Influence, It Is How You Influence

Robert White worked at the same company in New York City with me. This was my first job after college and I did sales support. During my three years stint at this corporation, Robert worked there part-time. We immediately took a liking to each other after we met. We shared the trait of not taking the American corporate work environment too seriously.

We would laugh and crack jokes at our more-often-than-not boring and time wasting tasks. We spent a good amount of time talking about culture, world languages and memories from 20th century USA. He was in his 60s and had lived a great life. He was an extraordinary person and my great friend. The kindness and support he gave me during the time I met him was a source of inspiration to me. For this, he’s made a positive impact in my life.

Before I left this company, I asked him if he could write a letter of recommendation so I could apply to a fellowship program in Germany. He did it gladly even during a turbulent period of his life. I didn’t know this then but he had cancer and was about to start chemotherapy for a tumor that had spread to his bones.

It has been a little over a year since Robert passed away and I miss him dearly. As a German language enthusiast as he was, he would be glad to know that the letter of recommendation he wrote ended up helping me getting the research fellowship I so coveted in Germany. Today I am here enjoying the fruits of the kindness and love that he selflessly poured onto a friend.

Robert’s acts and virtues have influenced my life. I am better human being due to this.

Danke schön fur alles Liebster Freund.

What does Memoization mean?

I was watching a screencast the other day and the person mentioned in the video: “… and this gives you an mm(…) array”. The (..) means that I did not understand what I had just heard. I admit that I rewinded the video a few times and I could only grasp something along the lines of ‘memorized array’. It was then that I googled this and was autocorrected to “memoization”. WAT?

It turns out that memoization is recording the results of earlier calculations so that we don’t have to repeat the calculations again. It simply means caching the output.

An example may clarify this further. Say I have method that tells me how many Twitter followers a user has:

def total_twitter_followers

This is perfectly valid, however, every time we call this method during one request it always calls the Twitter API for the result. By memoizing the call, you store the value thus avoiding expensive fetches again:

def total_twitter_followers
  @current_user_total_followers ||= current_user.twitter_followers

The ||= operator is a so-called conditional assignment that only assigns the value on its right to the variable on its left if the variable is not true. Since pretty much everything in Ruby evaluates to true when coerced into a boolean (except nil and, of course, false, as well as a couple of other things) this is exactly what we want: The first call returns the actual string and from the second time on, no matter how often the method is called on the same object, the “cached” result will be used.

Hope you learned something today.

Stacked Solution

I love when I get exposed to new ideas and concepts that enhance my work or expand my intellectual acumen. That is one of the reasons why I picked software development as a career: each day I learn something in the job. It is never boring.

Especially people like me that did not acquire a traditional Computer Science degree (I actually learned programming through this public-private initiative.), chance upon concepts of CS that both better our overall programming understanding and explain the theory behind our coding practices.

I had the opportunity to work on a computer science problem with Tim Mansfield, a very knowledgeable programmer and, as it could be noticed from the short interaction we had, a great guy.

The problem we worked together is called Balanced parenthesis. Later I learned that balanced parenthesis is one of the tasks done by a compiler. It verifies if parentheses in a source code have their counterpart or not. For example you would want that each opening ‘{‘ or ‘(‘ in a source code must have a corresponding closure ‘}’ or ‘)’. So if the code is not put properly, i.e. if they are not balanced ‘{(})’, the compiler should throw an error.

Here is the problem at length:

Write a function to determine if a string is
‘balanced’. Balanced means that opening and closing
brackets match each other in the proper order. Other
characters are possible and should be handled. The
possible characters for balancing are {}, (), and []

Example Input:

‘{}’ -> True
‘{[]}’ -> True
‘{5}’ -> True
‘{[}’ -> False
‘[A]{}d()’ -> True
‘a’ -> True
‘a}’ -> False
‘([)]’ -> False
‘([])’ -> True
‘{‘ -> False
‘{{{{}}}’ -> False

The best way to solve this is to break down the problem at hand by writing in plain English.

  #split the string into an array of characters
  #loop through the array
  #if open symbol i.e. '{','[','(' then store them in a list
  #if closing symbol then remove last opening symbol in list
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced symbol.

Therefore delving now into the code we have:

def is_balanced(input)
 #split the string into an array of characters
  array_chars = input.chars

  open_brackets = []
 #loop through the array
  array_chars.each do |char|
    #if open symbol i.e. '{','[','(' then store them in a list
    if char =~ /[\[|\{|\(]/
      open_brackets << char
    elsif char =~ /[\]|\}|\)]/
      #if closing symbol matches an its opening symbol then remove last opening symbol in list
      bracket_matching = { ']' => '[', '}' => '{', ')' => '('}
      bracket = bracket_matching[char]
      return false unless open_brackets.include?(bracket)
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced parenthesis.

is_balanced('{{}}’) #=> true
is_balance('[(])') #=> false

We notice in this code that there is always inserting and removing one element from the end of the array. What is entering last, it is actually coming out first.

The implemented solution to this problem is called a Stack data structure. Thinking again, I remember implemented something similar when I worked on a linked-list problem months ago. There you go. I learned something that has already an impacted on my programming skills and for that it made my day.

Role-Based Authorization with Rails 4 Enum

I have started creating an employee engagement application recently. Its purpose is to allow companies to engage their employees in volunteering activities around social projects. For this application I need to create 3 different roles and access levels.

I am using Ruby on Rails and I discovered that you could do this with gems such as ActiveAdmin and Rolify. But I decided to give Rails 4 Enum a try.

In my application each User will have one role: a super_admin(that takes care of the whole application), company_admin(an person that administers employee engagement with this application), and employee(user from a company that uses the application). Therefore these are single-defined roles. Now if the User had the possibility to have more than a role, for instance a company_admin could also be a super_admin then this would be a bit more complex. It is indeed multiple role based authorization and the gem Rolify would do a better job at this.

Anyways, below is one way one can implement three different access levels using Enum.

An enumerated-type or enum in Rails is a hash where the values reference to integers in the database. Example

User.access_level # => {"employee"=>0, "company_admin"=>1, "super_admin"=>2}

More info about enum methods here

Assuming that you installed Devise and have a User table or similar, first add the access_level column to the users table

 rails g migration AddAccessLevelToUsers access_level:integer
class AddAccessLevelToUsers < ActiveRecord::Migration 
 def change
   #adding the default to zero will automatically set the user access level to the first Enum attribute
   add_column :users, :access_level, :integer, default: 0

Now in the User Model add:

class User < ActiveRecord::Base
  # you can also explicitly define enum as:  enum access_level: [:employee => 0, :company_admin => 1, :super_admin => 2}
  enum access_level: [:employee, :company_admin, :super_admin]

Migrate the changes to database and create three users in Rails console. Assign them access levels

 # by default the user access_level is employee
 user1.access_level #=> employee 
 # below we are assigning access_level to user2 and user3 rather the default employee

For sanity check, let’s use some conditionals on a page view of your choice to see if it worked.

<% if current_user.super_admin? %>
  <h3>Welcome Super Admin</h3>
<% elsif current_user.company_admin? %>
  <h3>Welcome, Company Admin</h3>
<% else %>
<% end %>

If you sign up as a user3 you should see “Welcome Super Admin” on that page.

This is a simple implementation of single-role-based authorization using Rails 4 Enum. I hope you learned something.

Postgresql Did Not Work After I Updated to OS X Yosemite(With Solution)

This morning, I tried to start up an application on Rails with a Postgresql server and had this error:

PG::ConnectionBad: could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; (::1) and accepting
&gt;       TCP/IP connections on port 5432?
&gt;     could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; ( and accepting
&gt;       TCP/IP connections on port 5432?

Checked server.log and it showed me what directories it was looking for. I also went to where postgresql gets stored to confirm the suspicion.

cd /usr/local/var/postgres

The directories pg_tblspc pg_twophase pg_stat_tmp were missing. These directories are empty anyways but when you boot up your pg server the server looks for them. I think the Yosemite update got rid of these directories. So I created them again anyways.

mkdir pg_tblspc pg_twophase pg_stat_tmp

And added a .keep file in them so that I don’t have this problem in future OS updates.

touch pg_tblspc/.keep pg_twophase/.keep pg_stat_tmp/.keep