git flow

Source control is a must-have for any team working on a project. It provides so many things, including accountability, code reviews, blah blah, and so much more! IMO, the best part is working in branches that can be merged to other branches. In a typical project you have 2 main branches: master and develop. Master should reflect what is in production and develop is the current updates slated to go live at some point in the not too distant future. Beyond those main branches, you may have a hotfix branch with a bug fix that needs to be pushed ASAP, or a feature branch with some new feature. All of those branches can get tangled and complicated. Enter git flow.

Git flow is a command line tool to help with branches and branching for git repos. It’s really simple to setup gives you a few tools that make merging branches to master easier! To get started, install git flow and then run this in your repo root:

git flow init

This init process will ask some simple questions, most can be left as the default unless you have specific naming conventions for branches. Once that is done, you can do any of the following.

Create version 1.0.0

Let’s say you’d like to merge develop into master and tag it as version 1.0.0. Perform the following commands:

#Start Release 1.0.0, merging develop into master
git flow release start 1.0.0

#Update your version file
vim version

#Commit the version file update as the 'Version Bump'
git add version
git commit -m 'Version Bump'

#Finish Release 1.0.0
git flow release finish 1.0.0

#Push it, including tags
git push --follow-tags

Feature Branch

When creating a new feature that may not go to production for a while, you should do the work in a feature branch.

#Create a new feature branch from develop
git flow feature start report-xyz

#Make changes and commit
vim report-xyz
git add report-xyz
git commit -m 'Adding report-xyz'
git push

#Finish the feature, merging it into develop
#This can also be done via a PR for code reviews
git flow feature finish report-xyz

Hotfix Branch

There’s a bug on production! Going to have to fix it, based on the code in master. Once it’s fixed both master and develop need to have that update.

#Create a new hotfix branch from master
git flow hotfix start bad-profile-image

#Make your changes
vim profile
git add profile
git commit -m 'Fix for profile image'
git push

#TODO Verify that all is well

#Once all is good, do a 'Version Bump'
vim version
git add version
git commit -m 'Version Bump'

#Finish the hotfix, merging it into develop and master
#This can also be done via PRs for code reviews
git flow hotfix finish bad-profile-image

That’s all for today. Happy Coding!!

Node Callback Hell

I may be a little late, but I’m hopping aboard the node train! Having a more than a decade under my belt of php and roots in C/C++ helps tremendously in seeing the bigger picture with node. IMO, it’s a great platform! Having said that, there are quite a few caveats that you must address. I’ll be covering a few this month and the first is: Callback Hell!

Callbacks are great, but they can quickly cause your code to be 5 levels deep. Here’s an example:

const verifyAuth = function( token, callback ) {
  var token_query = 'SELECT * FROM users WHERE token = ?';
  var roles_query = 'SELECT * FROM user_roles WHERE user_id = ?';
  mysql.query( token_query, [token], function(err, rows) {
    if ( err ) {
      callback(err);
    } else {
      if ( rows.length == 0 ) {
        callback('User not found');
      } else {
        var user = rows[0];
        mysql.query( roles_query, [user.user_id], function(err, rows) {
          if ( err ) {
            callback(err);
          } else {
            callback( null, user, rows );
          }
        })
      }
    }
  });
};

Here, you see there are 2 separate db queries. An initial solution is to name and then split out the separate functions:

function lookupToken( token, callback ) {
  var token_query = 'SELECT * FROM users WHERE token = ?';
  mysql.query( token_query, [token], callback );
}

function lookupUserRoles( user, callback ) {
  var roles_query = 'SELECT * FROM user_roles WHERE user_id = ?';
  mysql.query( roles_query, [user.user_id], callback );
}

const verifyAuth = function( token, callback ) {
  lookupToken( token, function(err, user) {
    if (err) {
      return callback(err);
    }
    lookupUserRoles( user, callback );
  })
}

That’s a great first step! Now, let’s travel down the rabbit hole, with async. This allows you to load the 2 db calls in sequence:

const async = require('async');

const verifyAuth = function( token, callback ) {
  var token_query = 'SELECT * FROM users WHERE token = ?';
  var roles_query = 'SELECT * FROM user_roles WHERE user_id = ?';
  var user_record;
  var roles_records;

  async.series( function lookupUser(done) {
    mysql.query( token_query, [token], function(err, rows) {
      if ( err ) {
        return done(err);
      }
      if ( rows.length == 0 ) {
        return done('User not found');
      }
      user_record = rows[0];
      done()
    })
  }, function lookupUserRoles(done) {
    mysql.query( roles_query, [user.user_id], function(err, rows) {
      if ( err ) {
        return done(err);
      }
      roles_records = rows;
      done()
  }, function allDone( err ) {
    callback( err, user_record, roles_records );
  })
};

It doesn’t stop there! You can also iterate of an array in parallel. For example, if you want to update many records at once, you can use async.each:

const async = require('async');

const saveRecords = function( items, callback ) {
  var query = 'UPDATE item SET value = ? WHERE id = ?';
  async.each( items, function saveItem(item, done) {
    mysql.query( query, [item.value, item.id], done );
  }, function allDone( err ) {
    callback( err );
  })
};

While you can’t remove callbacks completely, my current rule of thumb is to not have any code with more than 5 indentations, so 2 space = 1 indent means no lines with more than 10 spaces at the beginning.

Re-using custom npm modules

From time to time, there will be a need to include a customized node module across multiple projects. This may be because the original has a bug and you know how to fix it, or simply creating a new re-usable module. Luckily, there’s an easy way to do this using github.┬áIf you’re new to github, I’d suggest reading up on it before proceeding.

Step 1: Push your module to github

Prepare your module, as usual. Instead of sending it to npm, just push it up to a new github repo. If you’re working on fixing or updating a module that already exists, you can just fork the module’s github repo and work in your fork!

Step 2: Installing from github

This is really easy:

npm install --save username/repo

Here’s a real example:

npm install --save barrygilbert/mysql-restapi

You can also reference a specific branch:

npm install --save barrygilbert/mysql-restapi#master

Step 3: Do your thing!

Now that you can install that module into multiple projects, go code it up!

Learn to program through Project Euler

About 6 months ago, I was surfing and came across a math/programming site that has fascinated me ever since, Project Euler. They have over 200 problems to solve and continue to add more. The problems start off very easy and get difficult rather quickly. Some of the beginning problems can even be solved using paper and pencil.

If you are just starting to learn computer programming, you should check out this site. The first problem can be solved fairly easily, and I will show you how I did it in perl.

First, let’s look at the problem. They want you to “Find the sum of all the multiples of 3 or 5 below 1000.” What the program will have to do is loop through all whole numbers from 1 to 999. Inside the loop, there is a check to see if the number is a multiple of 3 or 5. If it is, it is added to the sum. After the loop, print the sum to the screen.

Here’s the code:


$sum = 0;
$counter = 1;
while( $counter < 1000 ) {
if ( $counter % 3 == 0 || $counter % 5 == 0 ) {
$sum = $sum + $counter;
}
$counter = $counter + 1;
}
print "The answer is $sumn";

This program, just like every other computer program, uses flow control. Basically flow control tell the computer what to do and when to do it. There are 2 flow control structures here, a while loop and an if statement. Both of these are started by a comparison inside parenteses, then an opening curly brace. They are ended by the closing curly brace.

The while statement should be fairly straightforward, but the if statement is a little complex. The percent(%) sign means modulus(mod for short), which is simply the remainder of division. For example, 4 % 3 is 1, 4 % 5 is 4, and 9 % 3 is 0. The double pipe(||) means OR. When reading line 4, you say “If counter mod 3 equals 0 or counter mod 5 equals 0, then.”

Let’s go line by line.

Line:1 $sum = 0; Set a variable named “sum” to 0.
Line:2 $counter = 1; Set a variable named “counter” to 1.
Line:3 while( $counter < 1000 ) { Start a loop and continue the loop while counter is less than 1000.
Line:4 if ( $counter % 3 == 0 || $counter % 5 == 0 ) { Check to see if the remainder of counter divided by 3 is zero OR the remainder of counter divided by 5 is zero.
Line:5 $sum = $sum + $counter; Add counter to sum if so.
Line:6 } Close the if block.
Line:7 $counter = $counter + 1; Add 1 to counter.
Line:8 } Close the while loop.
At this point, the program will repeat the check at line 3 if check is true goto line 4.
Line:9 print “The answer is $sumn”; Print the answer to the screen.

You can download perl from perl.com. Once it is installed, you can copy and paste the source code into notepad and save it as euler-1.pl or whatever you want. To run the code, double click on the file.

Play around with the code. Poke it. Prod it. Change the while comparison so it only goes to 10, 100, 100000, etc. Changed the if to check for numbers divisble by 2 and 3. If you mess it up, copy and paste the code back into the file.

If you have any problems, leave a comment.

Web 2.0

When the internet first began, most of the pages were static and didn’t change unless someone manually edited the HTML. Recently, more and more sites have become dynamic. Blogs, Forums, Social Networks, and Wikis have contributed to a movement on the internet dubbed “Web 2.0”. Basically, Web 2.0 refers to website that allow regular users to read and write content to the web.

Forums were the first big step. Forums just let people post questions, answer questions, and share ideas with others. These have been around since the late 1980s when people did not have access to the internet.

Blogs are newer than forums. A blog is simply a self-publication for the web. You can create a blog for any topic you can think of. The blog writers create content and many blogs supply a comments section for feedback, so users can read the blog, then write their ideas.

Wikis, such as Wikipedia, are collections of content. A user can read, edit, and create articles. Then that information is out on the web for anyone to read. Wikipedia is the most popular wiki containing millions of articles on a variety of subjects. Because anyone can edit or create content, the content is almost guaranteed to be up to date.

Social Networks provide a way for real world and internet friends to communicate online very easily. These sites boil down to the simple fact that a user has a set of friends and can send them messages as well as having a profile page. Some sites serve a particular purpose, like delicious is only for bookmarks.

I hope this clears up any confusion about what Web 2.0 is.