Featured Post

Exceptions vs Failure Return Codes

http://codeutopia.net/blog/2010/03/11/should-a-failed-function-return-a-value-or-throw-an-exception/ Quick read on when to use exceptions vs when to use return codes.  I think the author does a good job of making something that is a gray area for some developers a little more black and white.

Read More

Memoization

Posted by Garrett | Posted in Public | Posted on 26-07-2011

0

I was recently cleaning up a snippet of JavaScript that did something like the following.

var run = function(){

	var links = document.getElementById('results').getElementsByTagName('a');

	// some more code dealing with the DOM
	// bla bla bla.....

	// test for host and make decision based off or it
	if (document.location.host === 'google.com') {
		//...
	} else if (document.location.host === 'bing.com') {
		//...
	} else if (document.location.host === 'yahoo.com') {
		//...
	}

};

window.addEventListener('load', run, false);
window.addEventListener('hashchange', run, false);

While this does get the job done, it’s a bit repetitive, especially when being invoked multiple times. Once the page loads, we know what the host is, why should our functions be forced to do branching logic on something we already know? We could clean this up a good deal if we could just remember what our decisions the first time our function was called. This is a concept known as memoization.

var run = (function(){

	var links = document.getElementById('results').getElementsByTagName('a');

	// some more code dealing with the DOM
	// bla bla bla.....

	// test for host and make decision based off or it
	if (document.location.host === 'google.com') {
		return function() {
			// ...
		};
	} else if (document.location.host === 'bing.com') {
		return function() {
			// ...
		};
	} else if (document.location.host === 'yahoo.com') {
		return function(){
			// ...
		};
	}

})();

window.addEventListener('load', run, false);
window.addEventListener('hashchange', run, false);

Since JavaScript is awesome, we can simply just return another function from our function into a variable when the page initially loads, and from there on out, we will only be invoking a function that cares about the context which we are in. This also forms a closure, so our function still has a reference to the links variable.

No more waiting precious milliseconds figuring out something we already know. Yay for smarter code!

The 10 Commandments of Programmers

Posted by Mardochee | Posted in Public | Posted on 25-07-2011

Tags: , , ,

0

Over the years of programming, most of these commandments came naturally to me and I didn’t even realize there was a term for some of them.  Code is not something you just write and it gets executed by the machine. Ok, yeah, it’s something that you just write and gets executed by the machine. But, Code is poetry. I always want it to be a beautiful piece to write, a joy to refactor and a pleasure to be executed by the machine. Technically, it’s me talking to the machine, right…? (E.T phone home?)

So after walking thru long miles in the desert, splitting the Red Sea, coming back from the Mount Sinai, I bring you the 10 Commandments of Programmers.  (For those who don’t know, I’m referencing Moses in the bible)

DRY: (Don’t repeat yourself)

It’s fundamental in programming that allows you to not repeat yourself. When the DRY principle is applied successfully, a modification of any single element of a system does not change other logically-unrelated elements

http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

KISS: (Keep it Simple Stupid)

A common problem among software engineers and developers today is that they tend to over complicate problems. Simplicity (and avoiding complexity) should always be a key goal. Simple code takes less time to write, has fewer bugs, and is easier to modify.

http://people.apache.org/~fhanik/kiss.html

Separation of Concerns

Separation of concern is the process of separating a computer program into distinct features that overlap in functionality as little as possible.

http://developers.redventures.com/2011/02/on-the-to-changes-separation-of-concerns/

Open/Close Principle

Software entities (classes, functions, etc.) should be open for extension, but closed for modification. In other words, don’t write classes that people can modify, write classes that people can extend. This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn’t change when it is extended, and therefore needs no such effort.

http://en.wikipedia.org/wiki/Open_Closed_Principle

Abstraction Principle.

Related to DRY is the abstraction principle “Each significant piece of functionality in a program should be implemented in just one place in the source code.”

http://en.wikipedia.org/wiki/Abstraction_principle_(programming)

Single Responsibility Principle

In object-oriented programming, the single responsibility principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

The reason it is important to keep a class focused on a single concern is that it makes the class more robust. Continuing with the foregoing example, if there is a change to the report compilation process, there is greater danger that the printing code will break if it is part of the same class.

http://en.wikipedia.org/wiki/Single_responsibility_principle

Code Reuse

Related to the DRY principle. Code reuse is the idea that a partial or complete computer program written at one time can be, should be, or is being used in another program written at a later time. The reuse of programming code is a common technique which attempts to save time and energy by reducing redundant work.

http://en.wikipedia.org/wiki/Code_reuse

Maximize Cohesion:

Code that has similar functionality should be found within the same component. Cohesion is a measure of how strongly-related or focused the responsibilities of a single module are. As applied to object-oriented programming, if the methods that serve the given class tend to be similar in many aspects, then the class is said to have high cohesion. In a highly-cohesive system, code readability and the likelihood of reuse is increased, while complexity is kept manageable.

http://en.wikipedia.org/wiki/Cohesion_(computer_science)

Minimize coupling:

Any section of code (code block, function, class, etc) should minimize the dependencies on other areas of code. This is achieved by using shared variables as little as possible. “Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability”

http://en.wikipedia.org/wiki/Coupling_(computer_programming)

POLA: Principle of Least Astonishment

Code should surprise the reader as little as possible. The means following standard conventions, code should do what the comments and name suggest, and potentially surprising side effects should be avoided as much as possible.

http://en.wikipedia.org/wiki/Principle_of_least_astonishment

Follow these commandments and your code will be like heaven…

The Rise of NoSQL

Posted by Mardochee | Posted in Public | Posted on 06-05-2011

Tags: , , ,

0

SQL databases have been rocking the programming world since the 70’s.  Lots of stuff have changed since, we have something called “internets”  and it’s revolutionizing how stuff was done before.  We buy, sell, contact, write, play, entertain, watch movies (in 3D heck yeah!), get scammed by Nigerian, tweet about cat, download music for free on the INTERNETS etc.  And some people have been jailed, sued,  reprimanded because of the INTERNETS. So, “I like turtle”. Yeah!  Famous quotes can make you become an internet sensation.  “So hide your wife, hide your kids and hide your husband, ….  ”, because there is a bed intruder out there.

Because of the internet, data has grown to a point where relational databases are not the right fit . Not all data are relational. Hence several companies (Google, Facebook, Amazon…) start building their own datastore.

2010, in my opinion,  was the year of scalability, big data, and the rise of the NoSQL movement.

NoSQL was first defined as NO to SQL. But later was changed to Not Only SQL, because SQL still excels in some area while NoSQL DB will kick SQL’s derriere in some.  The term “NoSQL” typically refers to non-relational, distributed databases that do not require fixed-table schemas.

NoSQL databases are schema-less, schema-full,  schema-mixed.  And the best part, they don’t require any JOINs.  What? Yes sir! No JOINs.

Most modern relational databases have shown poor performance on certain data-intensive applications, including indexing a large number of documents, serving pages on high traffic websites and delivering streaming media.  NoSQL on the other side provides heavy read/write workloads. It allows rapid application development and your schema lives within your application.

Some people will find it really hard to understand how the NoSQL DB work.  One thing I will suggest first, is not to think like SQL (UNSQL yourself);  But unfortunately after  writing  “SELECT * FROM TABLE” so many times, it’s hard to get out of there.  But I’m going to try my best to break it down…. But on some real “shizzle”, one should make his/her own extended  research on the NoSQL DB to know more.

Let’s get to know some of the most popular, and we’ll leave the best,  for last (playing african drum in your head and sing: Mongo, Mongo, Mongo…)

Classes of NoSQL DB

There are three main classes of NoSQL DB.

Key/Value Store. It holds data as Key-Value pair such that values are indexed to be retrieved by keys. Key/Value Store DB can hold structured and unstructured data.  In this family of DB there are Riak , Redis.

Column-Oriented DB.  It contains one extendable column of closely related data rather than sets of information in a strictly structured table of columns and rows as is found in relational databases.  In this family there is Cassandra, HBase.

Document  Based DB. Data is stored and organized as a collection of documents. Users are allowed to add any number of fields of any length to a document. They tend to store JSON-based documents in their database. In this class, there is MongoDB, CouchDB.

For a full list of NoSQL DB, CLICK HERE (you see what I did here?)

Of course before choosing  a database from  any of these classes one should make their due diligence, tests and benchmarks. So many people jumped from relational to NOSQL  just to go back to relational again because they were doing it wrong or didn’t know what they were doing.

Anyway…

MongoDB is the Tiger Blood of Database. When you use it, it’s #Winning.

Now among all the NoSQL db, I prefer Mongo. Well, MongoDB makes sense. It is the scripting language of the databases.  I’ve been working with it for more than a year now.  While it may not solve all relational database issues, putting the right thought in your application and your database schema will make you kick relational databases’ butt (and it’s fun to do).

Installing and running MongoDB is super easy. You just download, and launch the mongod file.  Upgrading to the latest version is as easy as making coffee after 2pm. You just replace the old binaries with the new one and you are up to date and MongoDB comes with replication and sharding.

Like most NoSQL DB, MongoDB is Webscale, you can use it for MapReduce, you can store files in it. You can make it “Like Turtle” technically do anything. It is just a versatile storage engine.  Whenever you feel like looking at a NoSQL database that have a similarity to your favorite relational database, check out MongoDB.

How would a document look like in Mongo?

MongoDB Documents are like JSON, and is trongly typed. It can hold: String, Array, Integer, Float etc…

The collection below holds three documents.


{
 "compID": 1111, // Holds integer

 "companyName": "RedVentures", // holds string

 "isLive": true, // hold boolean

 "uniqueContactFields":["Address","PhoneNumber"], // Holds array

 "avgLoadTime":0.17, // holds float
}

{
 "compID": 2222,

 "companyName": "DirectTV",

 "isLive": true,

 "uniqueContactFields":["LastName","HomePhone","Zip"],

 "avgLoadTime":0.15,
}

{
 "compID": 333,

 "companyName": "NurfSquad",

 "isLive": false,

 "uniqueContactFields":["LastName","Zip","PhoneNumber"],

 "avgLoadTime":0.12,
}

Let get some terminology before we go into more codes.

10Gen, the company behind MongoDB, made sure there are some similarities between SQL and Mongo while keeping it NoSQL in a non relational world.

In MongoDB a database is just like a database in relational db. “Duh!”

Collections in MongoDB can be like Tables and Documents are like Rows.

So a Document is in a Collection, and the Collection is in the Database. And of course a Collection will have more than one Document, and a database can have more than one Collection.

So the similarities are there except it’s bananas fun!

Now let’s connect to the DB:


$Mongo = new mongo();

$MongoCorpDB = $Mongo->selectDB(“RVWins”)

$Companies = $MongoCorpDB->selectCollection(“Companies”);

Get all the companies:


$allCompanies = $Companies->find();

Now, get all companies that are live


$allCompanies = $Companies->find(array(“isLive”=>true));

It will return the documents having companyName: RedVentures & DirectTV All companies that are not live


$allCompanies = $Companies->find(array(“isLive”=>false));

It will return the documents having companyName: NurfSquad.

Now let’s find documents based on criteria having values in an array. All Companies where uniqueContactFields = PhoneNumber


$allCompanies = $Companies->find(array(“uniqueContactFields”=>”PhoneNumber”))

It will return the documents having companyName:  RedVentures and NurfSquad. As you can see, uniqeContactFields is an array, and Mongo can find documents matching a criteria in an array. Now let’s get all the documents again. It will sort all document by avgLoadTime from highest to lowest, and return only 10.


  $allCompanies = $Companies->find()->sort(array("avgLoadTime"=>-1))->limit(10);

  foreach($allCompanies as $company){

      print("{$company[companyName]} average load time: {$company[avgLoadTime]}");

      print("<br>");

  }

As you ca see, working with MongoDB is like working with your own classes in your own projects. That’s #bi-winning.

And what if I want to update some data. Well let’s change the avgLoadTime for the compID: 2222 to 0.25


$Companies->update(array(compID:222),array('$set'=>array("avgLoadTime":0.25)));

That was easy right? Now let’s say someone wants to add one extra field for only the companyName NurfSquad. Let’s add a field hasHaitian, where it’s a boolean.


$Companies->update(array(compID:333),array('$set'=>array("hasHaitian":true)));

Now the NurfSquad document has a field called hasHaitian, while the others don’t have it. Now let’s look at our final db data. I also added a members fields, where it holds an object of all members with their properties

{

                "compID": 1111,

                "companyName": "RedVentures",

                "isLive": true,

                "uniqueContactFields":["Address","PhoneNumber"],

                "avgLoadTime":0.17,

}

{

                "compID": 2222,

                "companyName": "DirectTV",

                "isLive": true,

                "uniqueContactFields":["LastName","HomePhone","Zip"],

                "avgLoadTime":0.25,

}

{

                "compID": 333,

                "companyName": "NurfSquad",

                "isLive": false,

                "uniqueContactFields":["LastName","Zip","PhoneNumber"],

                "avgLoadTime":0.12,

                "hasHaitian":true,

                "members":[

                                                {

                                                  "name":"Colin",

                                                  "seat":"2-W-123"

                                                },

                                                {

                                                  "name":"Brandon",

                                                  "seat":"2-V-12"

                                                },

                                                {

                                                  "name":"Mardix",

                                                  "seat":"1-V-34",

                                                  "isHaitian":true

                                                },

                                                {

                                                  "name":"Ryan",

                                                  "seat":"3-A-13"

                                                },

                                                {

                                                  "name":"Deny",

                                                  "seat":"4-P-235"

                                                },

                                                {

                                                  "name":"Kyle",

                                                  "seat":"1-W-123"

                                                },

                                                {

                                                  "name":"Stephens",

                                                  "seat":"2-Q-12"

                                                },

                                ]

}

That’s how the document database look like. As simple as it is, as simple you get the data. I hope you get a good idea, and this can spin your imagination to the world of NoSQL.

Next time you have a project and you can decide which database to pick, take a look at MongoDB, you will be #winning!

"compID": 1111, "companyName": "RedVentures", "isLive": true, "uniqueContactFields":["Address","PhoneNumber"], "avgLoadTime":0.17, } { "compID": 2222, "companyName": "DirectTV", "isLive": true, "uniqueContactFields":["LastName","HomePhone","Zip"], "avgLoadTime":0.25, } { "compID": 333, "companyName": "NurfSquad", "isLive": false, "uniqueContactFields":["LastName","Zip","PhoneNumber"], "avgLoadTime":0.12, "hasHaitian":true, "members":[ { "name":"Colin", "seat":"2-W-123" }, { "name":"Brandon", "seat":"2-V-12" }, { "name":"Mardix", "seat":"1-V-34", "isHaitian":true }, { "name":"Ryan", "seat":"3-A-13" }, { "name":"Deny", "seat":"4-P-235" }, { "name":"Kyle", "seat":"1-W-123" }, { "name":"Stephens", "seat":"2-Q-12" }, ] }

Cookie Curiosity

Posted by Kyle | Posted in Public | Posted on 27-04-2011

0

While I was reading HTTP RFC information (everyone reads this stuff right?), I came across a section labeled ‘Implementation Limits’. Like most poeple, I don’t think there there is such a thing as too many cookies (assuming you have a glass of milk), but apparently browsers feel differently. According to the RFC documentation on the Set-Cookie header, there is a minimum amount that a browser should set the maximum amount to be. That’s a bit confusing, so I’ll state it differently, according to the documentation, a browser should accept at least 300 cookies total (for all visited sites), at least 20 cookies per hostname, with 4096 bytes of space per cookie.

PHP Design Pattern

Posted by Mardochee | Posted in Developers Only | Posted on 16-03-2011

0

Sorry, this is a private post meant only for Red Ventures Developers. If you are a developer, log in here: http://developers.redventures.com/wp-admin/

On The Road To Changes: Separation of Concerns

Posted by Mardochee | Posted in Public | Posted on 21-02-2011

Tags:

0

The goal of this article is to promote and give an overview of Separation of Concerns.

So, when I first started to make websites, I would have one HTML page that had all the CSS and JS. Looked great, awesome!

Then ten years ago I started to learn PHP, I was in 10th/11th grade.  I started to create dynamic websites. A PHP file would have PHP, HTML, CSS, JS code in it.    Some of you is probably saying “ok what’s wrong with it?”  Well, when you dived in the codes, it was like an Olive Garden restaurant, pasta everywhere, spaghetti was the only dish served.  Now,  just say  I had five php files, wow, imagine when I had to make a change and I had to edit all of them.  Then I started to “include()” header and footer, but still, PHP,CSS,HTML, JS were everywhere.

One of the growing problem, as the site was getting bigger, I had to maintain each part. But sometimes, I didn’t even need to encounter with a CSS or JS line. But what if I wanted to change a JS section? ARRRRR!!!!!  Mixing everything is just a bad design.  Maintaining and extending part of the codes became a burden.  As the application became bigger and bigger, more trouble was coming ahead. So to solve this issue, I had to rely on a concept called Separation of Concerns.

Separation of Concerns, a concept probably coined by Edsger W. Dijkstra in his 1974 paper “On the role of scientific thought”, is the process of separating a computer program into distinct features that overlap in functionality as little as possible.

Translating this into a web application, we now have, for a super basic one page site:
- mysite. JS
- mysite.CSS
- mysite.PHP  (contain PHP & HTML)

The main advantage of having such structure,  I can concentrate my attention at updating one piece of functionality at a time, instead of running through the HTML,CSS, JS all at once trying to see what’s going.

That was pretty easy, wasn’t it? Now, what about separating our PHP logic from our View?  We can now add a view file:
- mysite. JS
- mysite.CSS
- mysite.PHP
- mysite.HTML (View)

Now mysite.PHP has only  the PHP logic. It processes data to be sent to the view, while mysite.HTML (the view) will only have my HTML.

Now what do we get here? We’ve just separated our application into maintainable “concerns”,  piece of interest.

If I have a JavaScript error, I would just edit mysite.JS. Oh lord, I just saw a PHP parse error, well I go straight to mysite.PHP. But I forgot to add the company’s  logo, well I’ll add the image tag in the mysite.HTML.

At its best, Separation of Concerns allow us to organize an application where each part fulfill a meaning and intuitive role while maximizing its ability to adapt to change. It allows us to maintain and debug our application with class. And extend any part of it without sacrificing the purpose of any.

What other benefits does the Separation of Concerns have?

It allows designers and developers to stay in their turf and not disturbe the flow of the other .

Imagine you’ve got some HTML page well laid out, all your elements well arranged, just for a php developer to come in and do this <? IPutMyCodesInYourCodes(); ?>.  Or do you want a designer to start messing with your PHP codes, just to add a new DIV?

Separation of Concerns separates your application into distinct features that overlap in functionality as little as possible.

I practice the “Separation of Concerns” in all of my applications. While there may be more files in my applications, I do have greater flexibility to update, maintain and extend my application.

So, On the Road to Changes, “Separation of Concerns” is going to lead us to  Model-View-Controller (MVC) concept. But until then, C Ya!

Awesome examples on how to unit test XML with PHPUnit

Posted by James | Posted in Public | Posted on 15-02-2011

Tags: , ,

0

Not only can this be used to test XML but it can also be used to test HTML output from things like render methods and such. Using cURL you could even use some of these techniques to automatically test output on remote sites. All kinds of fun stuff.

http://qafoo.com/blog/007_practical_phpunit_testing_xml_generation.html

jQuery 1.5 Changes Part I

Posted by Garrett | Posted in Public | Posted on 20-01-2011

0

jQuery’s Ajax module was completely rewritten for the up and coming 1.5 release by Julian Aubourg. It added a new signature, new options, pluggable dataTypes, and a completely new architecture for what is returned by Ajax calls. The new signature for $.ajax is now:

	$.ajax(url, options);

But it is completely backwards compatible, so no worries. I personally like the new signature as it aligns up nicer with $.get and $.post. I will come back to the other features such as new options, and custom dataTypes in the next post, for now were going to skip ahead to the new underlying architecture. Prior to this release ajax calls in jQuery simply returned and passed around the raw XHR object, it was not all that handy in my opinion. However, starting at 1.5 an augmented XHR object has replaced it. You may see it referred to as the jXHR object or a promise.

So what does the promise allow us to do? Well to sum it up, we can bind callbacks to an object whose current task will eventually complete.

	var jxhr = $.ajax('/foo.php', {type:'get', dataType:'json'});

	jxhr.success(function(response){
		// do something with the resposne
	});
	jxhr.error(function(jxhr){
		// do something with jxhr
	});

	console.log('whats up?');

Or you could accomplish something similar using the “then” binding which takes a done and fail callback.

	$.getJSON('foo.php').then(function(response){
		console.log(response);
	}, function(jxhr){
		console.log(jxhr);
	});

	console.log('whats up?');

Or you can even chain the bindings and/or conditionally add new bindings which is a huge advantage of nesting tons callbacks in previous versions.

	var jxhr = $.ajax('foo.php', {
			type: 'get',
			dataType: 'json',
			success: function (response) {
				console.log('1');
				jxhr.success(function(r){
					console.log('4');
				});
			}
	});

	jxhr.success(function(response){
		console.log('2');
	});

	jxhr.success(function(response){
		console.log('3');
		if (response[0] === 'one') {
			jxhr.complete(function(response){
				console.log('5');
			});
		}
	});

	console.log('whats up?');

So let’s say in the previous examples foo.php took 4 seconds to respond, it doesn’t matter, the ajax call will return a promise to us that will let us go ahead and bind a set of predefined events to it (success, done, complete, error and fail). It will later resolve based on what happened once the asynchronous task as completed and it will invoke the correct callbacks. As you can imagine there are a million ways to Sunday that you could formulate these calls. I personally like calling the success and error manually, at least in the case of Ajax. Check out https://github.com/jquery/jquery/blob/master/test/unit/Ajax.js for the various ways they are doing it. I would love to see what most people consider to be the “correct” way.

Another important thing to note is they have exposed the underlying deferred mechanics for your own use. So you can easily create promise like objects for your own asynchronous programming needs.

	var def = new $.Deferred(), data = [1,2,3,4,5];

	setTimeout(function(){
		def.resolve(data);
	}, 5000);

	def.then(function(data){
		console.log(data);
	});

	console.log('whats up?');

So just like our ajax calls, we can bind a set of predefined callbacks to run once an asynchronous task has resolved. So check out $.Deferred and see what kind of asynchronous magic you can do. The whole concept of deferred/promises can puzzle many developers, including me. So check out the links below for more information, they were quite helpful in writing this post and correct me if you notice some incorrect information in this post.

Working with xpath with Firebug

Posted by James | Posted in Public | Posted on 06-12-2010

Tags: , ,

0

from: http://blog.browsermob.com/2009/04/test-your-selenium-xpath-easily-with-firebug/

The author goes on to suggest Firebug as a great tool for doing this kind of work, which we tend to agree with and have covered previously. But they missed one of the most important functions: the ability to easily test XPath expressions from within Firebug!

Very few Firebug users know about this, so take note: Firebug adds a $x function that can be called from the console. It takes an XPath in the form of a String and will spit out the HTML elements that it evaluates to directly back in the console. You can then mouse over the elements and check that the XPath is working correctly:

$x(“//input[@class='cart-domain-pr-option'][1]“);

Also worth a read:

http://www.chinhdo.com/20080829/web-scraping-htmlxml-parsing-and-firebugs-copy-xpath-feature/

Find the last monday before a date in MySQL

Posted by James | Posted in Public | Posted on 16-11-2010

Tags:

0

DATE_SUB(O.ScheduledDate, INTERVAL WEEKDAY(O.ScheduledDate) DAY) AS LastMonday