Recent posts

Object-orientated development: a lesson in PHP5

PHP has been given a major stabbing and bashing in the last few years. Mainly due to inconsistency, non native support for UTF8 and the fact that only from v5 has it been “object-orientated capable”. However, PHP just works. Out of the box. It delivers on a promise to produce dynamic web pages.

Below is a best practice guide on using PHP in an Object Orientated (OO) manner.

Why Object-Orientated (OO) Programming

  • Objects can store data internally. Therefore variables don’t need to be passed from function to function like in procedural programming.
  • Better organization, portability and reuse of code. You can place common functionality in a Class inside its own separate file using a common naming convention that can be reused in other applications by using an include. Think DRY (Don’t Repeat Yourself) principle.
  • Maintainability is improved. Code is easier to spot and alter in the 1st place. Another DRY principle.
  • Gets you building sites using MVC (Model-view-controller) framework like CodeIgniter, Zend Framework et al.. which are built around PHP5 OO and enforce good coding standards, practices and patterns.
  • Allows you to experience Convention over Configuration (CoC) principles in your MVC application.

Ok, so hopefully you are now convinced that OO is the way forward.

Object-Orientated (OO) Paradigms

Before I begin, let’s cover some basics of OO. That is, a Class represents an object, with associated methods and variables. Therefore all the functionality we will build will be wrapped in Classes. Think of them as blueprints for an object.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. Note, since objects can be passed as arguments to a function they are by default “copied” unless you specify the argument as a reference variable &$variable.

Here’s a run down of some fundamental OO Paradigms you should be considering and even using to write kick ass OO code.

These paradigms are all used in my sample code below.

Inheritance

Inheritance extends a Class (base) to bring additional functionally to your Class (child). This allows you to create a hierarchy of interlinked classes. In PHP5 only 1 Class can be inherited.

For example, if we have a parent Class “Dog” which holds common Dog like behavior like “bark” we can extend that into our child Classes say “Poodle”, “Husky” etc… Therefore Poodle and Husky can both inherit the same method called “bark” which specifies the shared functionality without having to repeat it across other children Classes.

More on inheritance is covered here: http://www.php.net/manual/en/language.oop5.inheritance.php

Constructor and destructor methods

These are methods called upon creation or destruction of Class object. Typically if you want to initialize a certain property on the creation of an object or cleanup post use.

More on these methods is covered here: http://php.net/manual/en/language.oop5.decon.php

Member privacy (visibility)

This defines who has access to members and methods.

<strong opinion>I believe visibility is a lot of hog wash in PHP. PHP was designed by Rasmus Lerdorf for “web development to produce dynamic web pages” (ref: wiki). Member privacy is largely important when building components that are used by 3rd parties. Like something you would do in Java/C++ with dll/com objects. There is absolutely no good reason I know of why you’d want to hide certain Class functionality from your own developers. Use Interfaces if you must “guide” them on what they can and cannot use. Python got this right!</strong opinion>

More on member privacy is covered here: http://www.php.net/manual/en/language.oop5.visibility.php

Encapsulation

Encapsulation is a reference to well-defined interface to a set of functions in a way which hides their internal workings. The benefit here is it can reduce complexity for another developer by not exposing the whole inner workings of a class. This is achieved using member privacy (discussed above).

More on encapsulation here: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Interfaces

Allows you to specify a Class templates for other developers to showing which public methods can be implemented without exposing how these methods are handled. Only methods can be declared in an Interface, not variables. More than 1 Interface can be extended in a Class.

More on interfaces can be found here: http://en.wikipedia.org/wiki/Object-oriented_user_interface

Overloading

Overloading allows you to dynamically create or extend public properties or methods. These dynamic entities are processed via magic methods.

More on overloading here: http://www.php.net/manual/en/language.oop5.overloading.php

Patterns

Factory: The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for “manufacturing” an object. A Parameterized Factory receives the name of the class to instantiate as argument. And;
Singleton: The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Often implied in Database Classes, Loggers, Front Controllers or Request and Response objects.

More on Patterns here: http://www.php.net/manual/en/language.oop5.patterns.php

Now let’s look at how all of this would fit into code.

Note that I have tried to fit all these practices into the 1 sample of code below. Read the internal comments I put in to understand what is going on. Any mistakes or questions please use the comments section below to let me know.

The CODE – in PHP

// Interface implementation
interface BaseInterface
{
	function method0();
}

// Class definition with keyword "implements" to implement BaseInterface interface above.
class BaseClass implements BaseInterface
{
	// property declaration
	private $attribute3 = "This is PHP5";

	// method declaration, by default this is public
	function method0() {
		print "This is Method0";
	}
}

// Always use Upper camel case naming notation for class names
// Inheritance is achieved by using the "extends" keyword with class you want to extend.
class ChildClass extends BaseClass
{
	// This variable is accessible without needing an instantiation of the class.
	public static $attribute0 = "Yes I'm visible";

	// This variable can only be accessed within this class
	// This is also an encapsulated attribute never exposed outside the class.
	private $attribute1;

	// This variable can be accessed outside this class
	public $attribute2;

	// Note the above visibility of the attributes.
	// There are 3 types and can be accessed - public (everywhere), protected (class & inherited) or private (only by class).

	// A class can only have 1 constructor
	// Suitable for any initialization that the object may need before it is used.
	function __construct($arg1, $arg2, …) {
		// Use operator arrow to access class variable
		// Note the lack of $ in front of attribute1. This is valid and also a common mistake among newbies.
		$this->attribute1 = "ABC";
	}

	// A class can only have 1 destructor
	// Called when the object is explicitly destroyed.
	private function __destructor($arg1, $arg2, …) {
		$this->$attribute1 = "";
	}

	// This method has no "visibility" declared so by default it becomes "public".
	function method1() {
		print "This is Method1";

		// Access to base class method / attribute using parent::
		// This call docent automatically evoke base class contractor / desconstructor unless called via parent::
		print "From BaseClass: " . parent::$attribute3;
	}

	// "final" stops this method from being overridden.
	final public function method2($a) {
		$this->attribute2 = $a;

		// Displays to screen the "encapsulated" attribute
		print $this->attribute1;
	}
}

// Accessing static attribute without instantiating a class
print ChildClass::$attribute0;	// Output: 'Yes I'm visible'

// Creating new instances of the child class
// Note that since ChildClass has arguments in the constructor function those need to be passed during this object's instantiation.
$foo = new ChildClass(1, 2, ...);
$bar = new BaseClass();
// Like functions, this instantiated object will have its own "class scope" so any method/variable is different to say $bar object.
$soap = new BaseClass();

// Accessing object members
$foo->attribute1;		// Output: 'ABC'
$foo->method1();		// Output: 'This is PHP5'
$bar = method0();		// Output: 'This is Method0'

I think that is enough to digest for now. If you want to read more on Object-Orientated PHP5 I recommend you visit PHP.NET here: http://www.php.net/manual/en/language.oop5.basic.php

Hope this post has shed more light on OO in PHP and you are ready to crank out some clean and usable OO code.

~ Ernest

ECMAScript: The history of JavaScript

JavaScript is a very interesting language that has caught my eye in the last year. Previously I blogged about the power of the Module Pattern in JavaScript; why it’s powerful and how to make sure your site complies to this great pattern. The language has come a long way and is growing up fast to be the defacto language of choice for all front-end UI/behavioral functionality. Flash, the old heavy dog, is on its way out. JavaScript, part of the HTML5 stack, is looking the most promising.

This post isn’t about how great JavaScript is, it’s about its history. Before one delves into anything one should always understand the basics. So let’s begin with some basics and then its history. The history is rather interesting.

What is JavaScript anyway?

JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions.

For the business guy

  • JavaScript is client-side language. Meaning anyone with a browser can view it in its entirely. Nothing is hidden. This is how we have access to any site’s code. Right click on any webpage and select “View Source” – Bingo!
  • JavaScript is downloaded via your browser and then executed within the browser. This is where performance bottlenecks are experience and browser compatibility issues.
  • JavaScript’s real name is actually ECMAScript.

For the tech guy

  • JavaScript is a “prototype-based scripting language” meaning it is object-oriented where classes are not present, and inheritance is performed via a process of cloning existing objects that serve as prototypes.
  • JavaScript is “dynamic”; meaning that it executes at runtime.
  • JavaScript is “weakly typed”; meaning you can cast memory to any type and
  • JavaScript has “first-class functions”t meaning it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

History of JavaScript

There are many stories online but I think this one below (source) explains it nicely.

Here is something else you should know about Javascript that seems like it was almost designed to be confusing as possible:

  • There is a programming language called Javascript.
  • There is a programming language called Java.
  • There is an interpreter (‘thing that makes it go’) for the programming language Javascript built into most web browsers
  • There is an interpreter for the programming language Java that is sort of built in to most web browsers, or was.
  • THESE TWO PROGRAMMING LANGUAGES HAVE ALMOST NOTHING TO DO WITH EACH OTHER

Back in the olden days, there was a company called Sun that had invented a programming language they decided to call Java. It was very trendy and exciting. There was a company called Netscape that made the trendiest and excitingest web browser. Sun wanted Netscape to include the magical crap that would make Java work with their browser, because everyone was gonna get Netscape, so everyone would also automatically have the stuff that makes Java programs work. On the other hand, Netscape was saying, “but lets also make our own tiny programming language that runs right in the browser so instead of having to make up new html tags like ‘blink’, web authors can make annoying shit we haven’t even thought of yet!” So they said, “Sun, we’ll ship your ‘Java’, but we want to be allowed to call our other programming language, which has absolutely no relationship to yours and is intended to do completely different things, JavaSCRIPT.” And Sun said, “OK, swell. go nuts. That won’t matter to us. ONCE JAVA TAKES OVER THE WORLD!”

So Netscape said to a guy named Brendan, who worked at Netscape, “Please make us a programming language. Also, you have to call it Javascript. Also, if you can make some of it kind-of sort-of look a bit like Java, that would be even better. Also, you have only 10 days to do this so get cracking!”

Fortunately, it turned out that Brendan was a cool genius and he secretly designed a cool programming language and dressed it up in some vaguely Java-looking disguises, kind of like how children will sometimes wear a huge cloak and stand on top of one another in order to get into R-rated films.

But Brendan’s disguise worked too well! People were like “wtf is with this crap version of Java? IT SUCKS!” Also, even a cool genius like Brendan has some some limits, so he did make a few mistakes when he was making his programming language in only 10 days. Also, because Netscape had basically thrown down the gauntlet and said, “You think the blink tag is annoying? Marquee makes you want to rip your eyeballs out? YOU HAVEN’T SEEN NOTHING!” people did manage to find insanely annoying things to do with Javascript. All the cool people installed special software on their web browser JUST TO MAKE JAVASCRIPT NOT WORK. So it took many years before people started to figure out that Brendan’s language was wrapped in an elaborate disguise and that it was actually cool.

Weirdly, some of the main people who did this were people at Microsoft, who had tried to confuse this whole mess out of existence by coming out with programming languages named stuff like J++ and JScript. Netscape, at the time, was threatening to rip Microsoft apart, like a crab rips up a cuttlefish with his claws. So Microsoft, adopting the strategy of the cuttlefish, made a million confusing “J” programming languages, hoping to escape intact. A prophet by the name of Douglas started saying, “guess what nerds, it turns out Javascript is actually sort of awesome.” He managed to attract a fair number of acolytes, who fiddled with Brendan’s invention and realized that it was rather elegant and could certainly be made to do all sorts of useful, non-annoying things on webpages, if only people would stop blocking it.

And so the era now known as Web 2.0 began. There are a lot of things people associate with Web 2.0, but for people who make the internet, one of the biggest things was seeing sites like Flickr or Oddpost do cool stuff with Javascript and other technologies that had been previously considered lame.

And then, in a sort of poetic irony that makes this story almost seem like it was pre-scripted to Teach us a Lesson, JAVASCRIPT succeeded in doing what JAVA had intended to do. Microsoft, Java, Sun, Netscape, all were brought low by their hubris. But humble Javascript, the throwaway, ‘you get 10 days to make this’, blink-tag-replacing runt of a language was able to sneak onto every computer in the world thanks to its clever disguise. Servers are written in Javascript. Databases are built to talk Javascript. The people who build browsers and operating systems move heaven and earth to make Javascript just a tiny bit faster. Java’s still out there, of course. In various forms. It probably makes sure your account is updated when you pay your water bill. It’s making the underpinnings of your android phone work. It’s figured out a way to play host to a zillion new trendier programming languages. But Javascript won the original prize.

Anyway, I’m just pointing this out because I remember the time when I didn’t know the difference between Java and Javascript and I’d find a tutorial for one or an article about the other and I was like “wtf, how do these go together.” The answer is, “they don’t. Marketing people just tried to name them as confusingly as possible.”

JavaScript today is..

  • Used in every website you visit online.. like 99.9999% of them.
  • At the core of famous server-side Node.js, an evented I/O framework.
  • If you heard of beautiful frameworks like jQuery, YUI, and more recently SproutCore and Cappuccino (Objective-J).. all JavaScript.
  • HTML5? replacement for Flash and other slick interface functionality, yap you guessed it.. JavaScript.
  • It is the most important language today!

What next

Plenty more informative & juicy articles on this front are being lined up. Not to mention I am starting a fun project with few smart software engineers in the valley which aims to give back to the community around this most important language today, JavaScript. Stay tuned to find out more on what’s next!

~ Ernest

Aussie founders in Silicon Valley

There are over 17,000 Australians living in San Francisco and the Bay Area (Silicon Valley). And some of these Aussies are making their presence felt in the Valley’s high-tech scene.Back in March 2009, when I arrived in the Valley full-time, I had no clue about the extent of the Aussie footprint here. As time ticked on and I got familiar & orientated around the tech scene the area has to offer I got fired up and inspired. I started to see what fellow Aussies were up to, the impact they were/are leaving and great opportunities this area provides.

Below is a list of these Super Aussies and the companies they are running (have run & sold) in the high-tech scene of Silicon Valley.

Founder/s Company Notes
Mike Cannon-Brookes & Scott Farquhar Atlassian Known for Jira, Confluence etc. 26K customers from 144 countries use Atlassian tools. Operates in Oz & SF.
Andrew Lacy Tapulous Acquired by Disney.
Bardia Housman & Adam Broadway Business Catalyst Acquired by Adobe. Bardia is soon to launch and soon to launch StartupHouse.
Elias Bizannes StartupBus Also runs Silicon Beach OZ & The DataPortability Project, blog and soon to launch StartupHouse.
Ryan Junee, Simon Ratner & Julian Frumar Omnisio Acquired by Google.
Ryan Junee Inporia See Omnisio above + also a mentor at 500 Startups and StartMate.
Andrew Roberts Ephox Operates in Oz, Palo Alto & Europe.
Sam Chandler NitroPDF Operates in Oz & SF.
James Nicol Fundly
Ben Keighran Chomp
Mick Johnson GasBag & Whereoscope
Lars Rasmussen Google Maps & Google Wave Recently moved from Google (Sydney) to Facebook in Silicon Valley.
Gower Smith Zoom Sytems
Leigh Jasper Acconex
Upcoming startups from my aussie mates.
Denis Mars Player.ly Currently in stealth-mode. Y-combinator alumni.
Vincent Turner PlanWise Aims to empower consumers with tools for planning and forecasting your finances. Presented at Finovate NYC.
Last updated: Sept 2011

Advance.org – Global Australians. Global Networks.

Advance.org helps create opportunities for Australians living abroad. They organise events/forums in and around San Francisco / Bay Area to help Aussies to connect together, share ideas, spark mentorship & marketing programs. More here: advance.org

Aussie incubator for Australian start-ups – The Startup House

Bardia Housman (see above ref Adobe) has purchased a 36,000 sq foot building (at 880 Harrison Street, San Francisco, CA 94107),  in the heart of San Francisco, to transform it into an incubator for Australian start-ups. It’s currently being built up but will most definitely be a kick ass place for Aussies enterprunrs. More on this project with Elias Bizannes (see above ref StartupBus) in the video below. All the best guys! Looking forward to paying a visit.

Media coverage: Recently published in the Sydney Morning Herald (SMH)

Gold diggers: Aussies strike it rich in Silicon Valley
By Asher Moses, September 15, 2011

  • Tony George from Austrade in Los Angeles helps Australian start-ups get a foothold in the US.
  • Austrade provides grants, helps entrepreneurs with research, advice about market entry, referrals to service providers such as lawyers and accountants, and most importantly hooking them up directly with potential customers.
  • Pollenizer and Startmate are helping the Australian tech start-up scene grown. But the conventional wisdom is still that start-ups needed to go to the US to raise funds and be exposed to the movers and shakers in the tech industry.

If you know of other Aussies in Silicon Valley/SF that are steaming ahead with their product/s please let me know and I will add them to this list above. Thanks!

Aussie Aussie Aussie, Oi Oi Oi!

~ Ernest

Hiring, Tips on finding rockstar software engineers

Another great day at Hacker Dojo and another great discussion on startups and finding talent in the bay area. So I was asked by a founder of a mobile startup company in the bay area on my experience hiring engineers. Here’s the jist of this discussion.

The big 3 – finding rockstar engineers

1. Utilize your network to find rockstar engineers.

There is nothing like finding the right person through your professional or personal network. Those are usually qualified leads; especially if the person you found them through you know well and is also a great engineer. Great engineers like to hang out with other great engineers.

So hit up your LinkedIn, Facebook and Twitter to let your network know you have an amazing opportunity open for the right person. And, if you need to develop a custom software, you may visit the Emergent Software homepage for more info.

If you are on a budget, stay away from external recruiters. They are expensive and hungry to get a sale through the door. They work on commission so will flood you with resumes. My experience has showed me from that flood only 3-5% of the talent is what I would class as rockstar engineers. If you must use one, detail & finecomb your requirements to them so the flood of resumes is more like a filtered clean stream of decent talent. You may also read some resources from sites like https://ursusinc.com/blog/ to find useful tips on how to hire a reliable and skilled tech employee.

2. Rockstar engineers are not looking for a job.

It is your role to convince them to come and work on your idea with you because it is better for them. Better for them because of growth (financial & personal) opportunities (*Mastery) and that they will be “changing the world” (*Purpose). Read my previous post on Compensation 101 so you nail this right. Most of all, if you can also offer flexibility (*Autonomy) you will be on a winning hiring streak.

(*) = if you haven’t yet read Daniel Pink’s book Drive: The Surprising Truth About What Motivates Us.. then I highly recommend you do. The key 3 points marked with * above are paramount to getting these rockstar engineers on board your train.

3. Attitude over skills.

Engineers with great attitude can be relied on. Their great attitude allows them to be in constant growth phase. Open to change. Positive attitude. And be able to move with the changing times. This is actually Talent. Talent is the ability to learn new things. Skills get outdated fast in this fast changing landscape while talent is something which stays with one forever.

Bonus – how to kick off an interview

So you got a rockstar engineer to come in and have a chat with you.. what next?

  • Interviewing is a 2 way street. You are interviewing the candidate and the candidate is interviewing you. This especially applies for rockstar engineers. Don’t forget this and try to make their experience as pleasurable (and memorable) as possible.
  • Start the process by asking the candidate “What is your most proudest moment in your professional career”. This gets the candidate talking and you can listen, gauge and ask specific questions to drill down into topics that might not have made to their resume.
  • Draw a mindmap as the candidate talks about their proudest moment. This is there to help you understand, navigate and ask better questions. Also shows to the candidate you are paying attention. Remember, your interviewing a rockstar engineering.

More on hiring

If you found this post useful and are now thirsty for more hiring hacks, check out my extensive list of posts (notes) from events I attended where the likes of Auren Hoffman (Rapleaf), Russell Fradin (Dynamic Signal), Dan Arkind (JobScore) etc… shared their experiences.

Have questions? use the comments section below or contact me.

Are you a rockstar engineer?

Then I want to speak to you. We are hiring for many exciting positions at coupons.com.

Coupons.com is located in Silicon Valley (California) and is the leading provider of consumer-printed coupon marketing and technology solutions leading the shift from print based couponing to Internet delivery, a $6.6 billion per year industry. Coupons.com recently got valued at $1 billion company.

~ Ernest

Free Education: Learn almost anything for Free

“Wisdom is not a product of schooling but of the lifelong attempt to acquire it” ~ Albert Einstein

“We now accept the fact that learning is a lifelong process of keeping abreast of change. And the most pressing task is to teach people how to learn.” ~  Peter F. Drucker

These quotes should come as no surprise to you. They state the obvious. But how many people forget to put this into practice. They finish up school and hit the workforce thinking that learning is behind them. That was school right. Wrong! The problem lies with wrongly associating pain to learning. Learning definitely require a level of discomfort. Just like exercise. You need to expel energy (strain) and this puts you out of a comfort zone. But this is the only way to do it to push that bar forward and bring change.

Once you understand that everything in life requires exerting energy (pushing the bar) to bring change (growth), your thinking changes dramatically and learning becomes a beautiful & peaceful (sometimes obsessive) process bound with fruitful outcomes of wisdom and enlightenment. We didn’t get this far in human civilization without education. An urge to understand more. And we will get further, inspire others and make a change in this world by education.

You are lucky

There has never been a great time in human history when education was so freely available and accessible to such a large population of people! Information is now free. Well a lot of it is is anyway. And more will become available – this is the trend. The old days when the few (rich) had access to it are over. Education (in 1 form or another) is now available to everyone. Public libraries, Internet, People et al. All you need now is the craving to learn. A will, drive, yearnings, fire inside to self-educate and expand your mind.

Free Education – General

Below is a list of great free online tech resources available to anyone willing to exert their energy and learn something new.. and change you forever.

Khan Academy

An organization on a mission. A not-for-profit with the goal of changing education for the better by providing a free world-class education to anyone anywhere.
Learn now: http://www.khanacademy.org/

  • Holds a library of around 2,400 education videos created by Khan. And growing everyday!
  • Topics covered on Algebra (inc Linear), Arithmetic, Banking and Money, Biology, Brain Teasers, Calculus, Chemistry, Math, Computer Science, Cosmology and Astronomy, Credit Crisis, Currency, Current Economics, Finance, Geometry, History, Physics, Probability, Statistics, Trigonometry, Valuation and Investing, Venture Capital and Capital Markets etc…
  • Sal (the founder) presents the topics using low-tech conversational tutorials, step-by-step doodles and diagrams on an electronic blackboard. And it works! Sal is a great teacher. He know how to break complex topics into simple, understandable and elegant ways of looking at them. It makes you smile because you will just get it! Learning couldn’t be easier. I have learnt heaps here.
  • Sal has built an amazing team of smart folks from McKinsey & Fog Creek Software including John Resig (the father of jQuery).

Hacker Dojo

A community center for hackers and thinkers. Located in Mountain View (California) at the heart of Silicon Valley next to Y Combinator and a host of other high-tech companies.
Discover: http://events.hackerdojo.com/

  • Free weekly Python classes ran by Karl Krueger (Googler). My favorite at the moment (Aug/2011).
  • Other events worth mentioning include iOS Developer Study Group, Machine Learning, Startup Monthly and many more. Visit events page for a full list.
  • And other times you will be sitting listening to a CEO / CTO talk about new high-tech innovation in their space or helping address common industry problems. Not to mention the many smart folks you can chat with and bounce ideas from during and post a meetup.
  • Hacker Dojo also has a nice library where you can kick back to read a book on a love sac or in a private cubby.

Google Code University

Provides sample course content and tutorials for Computer Science (CS) students and educators on current computing technologies and paradigms.
Discover: http://events.hackerdojo.com/

  • Topic covered include Programming Languages, Web Programming, Web Security, Algorithms, Android, Distributed Systems, Tools 101 andGoogle APIs & Tools.
  • Learn here one of the hottest languages today – Python.

Free Education – University

Harvard CS50 Computer Science

Introduction to the intellectual enterprises of computer science and the art of programming. It was ran last year so the content is fresh.
Take course: http://cs50.tv/2010/fall/#l=lectures&r=about&v=lectures/0/week0f

  • This course teaches students how to think algorithmically and solve problems efficiently.
  • Topics include abstraction, encapsulation, data structures, databases, memory management, software development, virtualization, and websites. Languages include C, PHP, and JavaScript plus SQL, CSS, and XHTML. Problem sets inspired by real-world domains of biology, cryptography, finance, forensics, and gaming. Designed for concentrators and non-concentrators alike, with or without prior programming experience.
  • The instructor David J. Malan is friggin amazing! I wish I had him teaching me Computer Science in my undergrad. His full of energy and uses many examples to back up the theory.

Stanford’s Introduction to Artificial Intelligence (AI) – Fall 2011.

Artificial Intelligence is the science of making computer software that reasons about the world around it. This is a bold experiment in distributed education organized by Stanford University in Palo Alto, CA.
Sign up for free course: http://www.ai-class.com/
Follow: http://twitter.com/#!/aiclass

  • Class begins October 10. Register using the link above!
  • From Humanoid robots, Google Goggles, self-driving cars, even software that suggests music you might like to hear are all examples of AI. In this class, you will learn how to create this software from two of the leaders in the field.
  • Sebastian Thrun and Peter Norvig – both top guns at Stanford University Computer Science with backgrounds from Google.
  • The course will (note Oct 10, 2011 start) include feedback on progress and a statement of accomplishment. The curriculum draws from that used in Stanford’s introductory Artificial Intelligence course. The instructors will offer similar materials, assignments, and exams.
  • Peter’s book AI, a modern approach, is a good read: http://aima.cs.berkeley.edu/ with Python (Yipeee) code samples

Stanford Engineering

SEE programming includes one of Stanford’s most popular engineering sequences.
Take course: http://see.stanford.edu/see/courses.aspx

  • Three-course Introduction to Computer Science taken by the majority of Stanford undergraduates, and seven more advanced courses in artificial intelligence and electrical engineering.
  • I haven’t gone through these but they look great! and all course material like Video Lectures, Syllabus, Handouts, Assignments, Exams and Software is provided.

Introduction to Databases – Stanford University

Databases are incredibly prevalent — they underlie technology used by most people every day if not every hour. Databases reside behind a huge fraction of websites; they’re a crucial component of telecommunications systems like those used in https://www.circles.life/au/plans, banking systems, video games, and just about any other software system or electronic device that maintains some amount of persistent information.

Take course: http://www.db-class.org/

  • Class is ran by Professor Jennifer Widom, the Fletcher Jones Professor and Chair of the Computer Science Department at Stanford University.
  • Students will have access to lecture videos, lecture notes, receive regular feedback on progress, and receive answers to questions. When you successfully complete the class, you will also receive a statement of accomplishment.

Machine Learning – Stanford University

Machine learning is the science of getting computers to act without being explicitly programmed.
Take course: http://www.ml-class.com/

  • Class is ran by Professor Andrew Ng is Director of the Stanford Artificial Intelligence Lab, the main AI research organization at Stanford.
  • Students will have access to lecture videos, lecture notes, receive regular feedback on progress, and receive answers to questions. When you successfully complete the class, you will also receive a statement of accomplishment.
  • This is the original Stanford AI course which the one in Fall 2011 is being based on.

MIT OpenCourseWare

MIT OpenCourseWare (OCW) is a web-based publication of virtually all MIT course content. OCW is open and available to the world and is a permanent MIT activity.
Explore & take courses: http://ocw.mit.edu/index.htm

  • Talk about Unlocking Knowledge and Empowering Minds. Free lecture notes, exams, and videos from MIT. No registration required.
  • I haven’t gone through this site yet but it was highly recommended. No prices for guess what MIT is… Massachusetts Institute of Technology. A private research university where six MIT students who were trained to become experts in card counting and subsequently took Vegas casinos for millions in winnings. Watch the movie 21 and you will learn about this MIT Blackjack Team.

No excuses!

There you have it. No excuses for not being able to afford or attend to university commuter science courses. If you have others which you feel should make this list please contact me and I will list them here.

… and just remember this famous quote by Napoleon Hill …

“Whatever the mind of man can conceive and believe, it can achieve.”
— Napoleon Hill

Happy learning!
~ Ernest

If you read this far you must like my notes,
subscribe here and never miss a single post.

JavaScript: made better using the Module Pattern

I’ve just finished reading JavaScript Patterns by Stoyan Stefanov and boy has it opened up my mind and inspired me to write better, faster, cleaner and more modular JavaScript code using the Module Pattern.

Stoyan’s book covers many patterns and anti-patterns (the common old approach to JavaScript coding).

Stoyan provides detailed explanations why and where to use each pattern inc. module pattern. Since there is so much content in this book I decided to write about what I believe will add immediate value to any developer working with JavaScript, how to make JavaScript better using the module pattern.

No hacks around poor JavaScript

JavaScript is unlike back-end server-side code where if the code becomes a bottleneck you just throw more boxes (hardware) at it to speed thinks up. JavaScript downloads & runs within the user’s browser. So if you got lazy or just didn’t know better to follow Convention over Configuration (CoC) or the rapid development principle of Don’t Repeat Yourself (DRY) and you hacked something together.. the user will get poor experience and even limited to a single browser. This is where JavaScript Patterns play an important role and understanding them is the 1st step in becoming a JS Ninja.

JavaScript – what you need to know

Let’s shake some old grounds and cover the what you need to know about JavaScript in 2011.

  • There are no classes in JavaScript. You create a blank object when you need one and then start adding members to it.
  • Sometimes when people say “Singleton” in a JavaScript context, they mean the Module Pattern – covered below and discussed in detail in Stefanov’s Chapter 5. Every time you create an object using the object literal, you’re actually creating a Singleton. And there’s no special syntax involved.
  • When you think about objects in JavaScript, simply think about hash tables of key – value pairs. Similar to what are called associative arrays in other languages.
  • Use literal notation patterns instead of object definitions. Literal is more concise, expressive and less error-prone. See Appendix 1.1 at the end of this post for examples.

Module Pattern – organize your code

Let’s start with what’s most common out there on the internet. You may have seen (or even do) this.

Code sample – anti pattern

Declaring:

var array_string = "[object Array]";
var ops = Object.prototype.toString;
var MAX_NUM = 123;

function inArray (haystack, needle) {
    for (var i = 0, max = haystack.length; i < max; i += 1) {
        if (haystack[i] === needle)
            return i;
    }
    isEnabled = false;
    return −1;
}

function isArray (a) {
    return ops.call(a) === array_string;
};

var pageTitle = "New title";

Calling:

isArray(arr_user);

The problems here are:

  • All these are global (variable and functions) are shared among all the code in your application living in the global namespace. High chance of naming collisions between your and other developer’s code (think maintenance).
  • isEnabled above has no var declaration so automatically becomes chained to the global namespace outside the function.
  • When something in your code is chained to the top of the prototype it takes longer time to be found then if it’s within a module. I will discuss the JavaScript Prototype in another post and show examples with performance differences.
  • Some best practices are broken – see below what these best practices should be.

Module Pattern – the solution, organize your code

There are many great patterns described in JavaScript Patterns by Stoyan Stefanov but my preference today is to use the Module Pattern. The Module Pattern is widely used because it provides structure and helps organize your code into self-contained de-coupled pieces of code. If you look at the source of jQuery you will find a similar pattern being used.

The Module Pattern is a combination of several patterns described in Stoyan’s book.
They include:

  • Namespaces (Stefanov’s pg.87)
  • Immediate functions (Stefanov’s pg.73)
  • Private and privileged members (Stefanov’s pg.92) and
  • Declaring dependencies (Stefanov’s pg.90)

And here’s how the same sample of code above would look when the Module Pattern was followed.

Module Pattern code sample – the pattern

Declaring:

var MYCOMPANY = MYCOMPANY || {};

// note the use of namespacing - similar to jQuery.
MYCOMPANY.Page = (function () {
    'use strict';

    // [ private properties ]
    // note the chaining of var declarations vs a var on each line
    var pageTitle    = "blank",
        isEnabled    = false,
        array_string = "[object Array]",
        ops          = Object.prototype.toString,
        MAX_NUM      = 123; // constants always are in capital case
    // end var

    // [ private methods ]
    // note the use of literal patterns vs constructor functions
    function inArray(haystack, needle) {
        var i   = 0,
            max = 0;
        for (max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
                return i;
            }
        }
        return -1;
    }
    function isArray(a) {
        return ops.call(a) === array_string; // end var
    }

    // [ public methods ]
    return {
        init: function (title, enabled) {
            pageTitle = title;
            isEnabled = enabled;
        },
        isArray: isArray,
        indexOf: inArray
    };
}());

Calling:

MYCOMPANY.Page.init('Page title', true);
MYCOMPANY.Page.isArray(arr_user);

Code is now modularized and less prone to collisions.

JSLint: The JavaScript Code Quality Tool

Once you have written your new modularized code it’s a best practice to run it past JSLint. JSLint is a free JavaScript program that looks for problems & violations of some of the patterns in your JavaScript code. It is a code quality tool. Check it out here: http://www.jslint.com/

JavaScript best practices

  • Curly brackets should always be used even if there is 1 expression. Code is then more readable and maintainable.
  • Use 4 space indentation – also JSLint default. This way no matter what editor engineers use it is always displayed in the same manner.
  • Like curly brackets, always use semicolons, even when they are implied by the JavaScript parser. Why slow down the compiler to clean up the mess during runtime.
  • Naming convention for constructors is typically UpperCamelCase, functions lowerCamelCase, variables lowercase_separated_by_underscore and constants UPPER_CASE.
  • Use whitespace as much as possible by separating all operators and their operands with spaces.
  • Use Google’s Closure Compiler to minify your code before production AFTER you have passed it via JSLint (above).

Appendix

1.1 Constructors and their corresponding and preferred literal patterns.

Built-in constructors (avoid) Literals and primitives (prefer)
var o = new Object(); var o = {};
var a = new Array(); var a = [];
var re = new RegExp( “[a-z]”,”g”); var re = /[a-z]/g;
var s = new String(); var s = “”;
var n = new Number(); var n = 0;
var b = new Boolean(); var b = false;
throw new Error(“uh-oh”); throw { name: “Error”, message: “uh-oh” };… or throw Error(“uh-oh”);

And that is it for now. Have I missed something or gotten something wrong above? If so please let me know and I will correct it. How is your JavaScript looking? Need help to get it fixed? Post below or contact me.

~ Ernest

MongoDB office hours in Mountain View

You may recall my previous post on MongoDB and how powerful it is as an alternative to a relational database. Since then I’ve had a bunch of discussions with other software engineers around this space and even met up with MongoDB core engineer Chris Westin from 10gen at Red Rock to gain further insights into MongoDB.

MongoDB Leaf

New kick ass GUI for MongoDB

Chris introduced me JMongoBrowser written by Antoine Girbal (10gen engineer). It’s written in Java so you can run it on Linux, Windows and Mac OSX. So far this GUI has proven to be a success and fills the holes where MongoHub couldn’t. Out goes MongoHub and in goes JMongoBrowser.

JMongoBrowser - MongoDB GUI admin tool.

Fast crash recovery using Journaling

MongoDB uses memory 1st to write data to vs directly to file/store. This is where huge performance gains are attained. It also has Journaling, a write-ahead for operations to facilitate fast crash recovery in the storage engine. This means the stuff in memory is stored in a log incase your server goes down without affecting MongoDB’s performance.

So what happens if your box goes down? .. a common question amongst new engineers to MongoDB. Does this data also gets lost? The answer lays somewhere in between how you balance your performance needs against the risks you are willing to take with your data.

The journal is synced to disk every 100ms. So the maximum that can be lost is up to 100ms worth of changes. At the cost of additional performance degradation, you can make your application proof against even that.  The j option to getLastCommand will cause the application to block until the journal entries with the last change have been written to disk.  See http://www.mongodb.org/display/DOCS/getLastError+Command .  Of course, if you use this, your call to getLastCommand can wait up to 100ms, depending on where in the flush cycle you are. Therefore, this is left up to the user to change this default of 100ms.

Therefore, always load MongoDB with Journaling enabled, like this:

mongod --journal

This also auto cleans up crashes and puts crashed data back into MongoDB.

Don’t be alarmed when you see this

I found this in the /Journal (1GB files):

-rw------- 1 root root 1.0G 2011-06-23 02:26 prealloc.0
-rw------- 1 root root 1.0G 2011-06-23 02:25 prealloc.1
-rw------- 1 root root 1.0G 2011-06-23 02:26 prealloc.2

With Journaling enabled the server always creates those three 1GB files.  It rotates through them, recycling them.  They won’t grow any more.  But they are always that size, regardless of the size of your database. If the server dies unexpectedly, the files remain, and contain the material necessary for the automated recovery that happens when you restart the server.

More here:

Checking server memory usage

As mentioned above, Memory is used by Mongo to speed things up. The more memory you have the better and MongoDB will use your RAM as it sees need for it taking into consideration other server resources.

It’s always a good practice to check memory usage.
Details here: http://www.mongodb.org/display/DOCS/Checking+Server+Memory+Usage

Your MongoDB configuration file

Here’s a recommend set of switches to have enabled in your mongodb.conf.

sudo nano /etc/mongodb.conf

add or update your settings to these:

journal=true
directoryperdb=true
logappend=true
  • journal = as discussed above to enable fast recovery from crashes.
  • directoryperdb = creates a new physical directory for each new database. Clean way to seperate your databases.
  • logappend = Whether the log file will be appended or over-written. Always have true else after a reboot your old logs will be overwritten and you may lose important crash specific data.

More detail here: http://www.mongodb.org/display/DOCS/File+Based+Configuration

MySQL to MongoDB

Finally, I found this fantastic chart illustrating the difference in commands between MySQL and MongoDB. Should help the transition for us MySQL folks. Click the image below to download a large PDF version (Size: 213Kb).

There is also mapping chart SQL to Mongo located on the MongoDB website here.

Have more questions? Attend the weekly MongoDB Office Hours in Mountain View Red Rockhttp://www.meetup.com/San-Francisco-MongoDB-User-Group/events/16985746/ or post a question/comment below.

~ Ernest

Mercurial: how-to guide to distributed version control

Mercurial is one of the 2 famous free / open source, distributed source control management tools. You may also have heard of Git, another great tool. Both Mercurial & Git are the front runners in distributed version control systems. 2 nice articles compare Mercurial to Git. One called Git vs. Mercurial: Please Relax comparing Git to MacGyver and Mercurial to James Bond. The other article The Differences Between Mercurial and Git. The conclusion was both are great tools so stop worrying and start using the one which you are most comfortable with. I went down the Mercurial route.

Mercurial - Work easier, Work faster

Mercurial is a distributed version control systems (DVCS) which keeps track of software revisions and allows many developers to work on a given project without necessarily being connected to a common network. This is a peer-to-peer approach, as opposed to the client-server approach of centralized systems like Subversion or CVS. It is a more cleaner, faster and refined way of working. More on this is explained on Wiki here.

Let’s get started with Mercurial

As explained above you Mercurial is a DVCS. So you will have a “local” version of Mercurial which may have a number of “repositories” on your development machine. A repository is essentially a package which identifies your application. One for each application. Your code will get “committed” to this local version daily as you work. When you have a working piece of functionality only then you will “push” it to “central”. Central is typically hosted on a remote server (hosted in-house or via a 3rd party like BitBucket) where everyone else in your team can push or clone code to. Typically “central” is hooked up to a continuous integration tool to facilitate nightly builds. More on that in another post. So whatever code you push there make sure it is working!

Local (dev) install or Mercurial

1. Download Mercurial on your development box from here: http://mercurial.selenic.com/

2. Run the install file and follow through with the default questions.

3. Your done.

Quickstart – starting your 1st Mercurial Repository

Source: http://mercurial.selenic.com/

In your terminal / dos window, navigate to a folder where you will either clone a project to or create one and do the following.

Clone a project and push changes

$ hg clone http://selenic.com/repo/hello
$ cd hello
$ (edit files)
$ hg add (new files)
$ hg commit -m 'My changes'
$ hg push

Create a project and commit

$ hg init (project-directory)
$ cd (project-directory)
$ (add some files)
$ hg add
$ hg commit -m 'Initial commit'

Let’s look at each command in more detail:

hg init

Run this 1st time in your working directory to mark that folder as your project repository which you want Mercurial to version control. Mercurial will create a hidden folder there called “.hg”. This is where all the detail (changesets and manifests) on your commits is stored.

hg clone http://(my-domain)/hg/(project-repository)

Run this in your working directory where you want to drag code down from central Mercurial (See below on Central).

hg status

To see what is not yet added & committed yet to the repository.

hg add

If you have new files this command adds them to your repository.

hg commit

Commit your changes to “local” Mercurial. Make this a habit of doing it frequently (at least once a day). Mercurial will ask you to put in comments with your commit. Also make this a habit to put in as much detail into your comments as possible to help others understand your changes + if you have a reference to Jira case / other Agile tracker add this in as well.

hg pull -u

To pull changes and update.

hg push http://(my-domain)/hg/(project-repository)

To push your local repository changes to a central repository.

Tools for Mercurial

Netbeans – IDE Integration

If you are using Netbeans for development and have pointed it to a project where you “hg init” was ran, Netbeans will automatically recognize this and integrate Mercurial into your workflow. In Netbeans, do this by right clicking on your project folder and look under “Mercurial” sub-folder. Get it from here: http://netbeans.org/

MacHG – GUI for managing repositories on the Mac

This is the nicest GUI for Mercurial that I could find for the Mac. It allows you in a nice graphical way to manage a collection of files, to add things to the collection, to save a snapshot of the collection, to restore the collection to an earlier state and in general to work with the files. Get it from here: http://jasonfharris.com/machg/
Alternatively go through a list of other tools here: http://mercurial.selenic.com/wiki/OtherTools

“Central” – home of all repositories

The following is only required if you want to setup Mercurial “central”. A single place (mothership) for all developers to push working code to for storage & versioning. This is also the place where you would hook up a continuous integration tool to facilitate nightly builds.

Bitbucket: free Mercurial code hosting

If you do not have enough resources to run Mercurial “central” in-house or want someone else to manage that for you then use one of the hosted solutions on the internet. Bitbucket from Atlassian (kick ass Aussie firm) can provide you with unlimited private code hosting, free. Yes I use it and I love it. Less maintenance & headaches and everything you learnt above can be applied here.

BitBucket by Atlassian - free Mercurial code hosting

Get your free account here: http://bitbucket.org/

Home solution: In-house Mercurial code hosting

Ok the following will require Ubuntu terminal access to the Ubuntu box where you want to install Mercurial “central”. All of the code below can be highlighted and pasted to run directly in your terminal window to make this process fast.

The following is based on the steps I followed from Emran Hasan’s Blog with some changes to the configuration to make it work on Ubuntu 10.10 based additional input from Stack Overflow.

1. Install Mercurial

sudo apt-get update
sudo apt-get install mercurial

2. Create a store for Mercurial configuration & repository files

cd /var/
sudo mkdir hg
sudo mkdir hg/repos
sudo chown -R www-data:www-data hg/repos

3. Creating a configuration file to host multiple repositories on this server & use CGI to serve the files through Apache:

cd /var/hg
sudo cp /usr/share/doc/mercurial/examples/hgweb.cgi .
sudo chmod a+x hgweb.cgi

4. Configure Mercurial (also refered to as “hg”) to point to point to our new config file:

sudo nano /var/hg/hgweb.cgi

and update the config like this:

config = "/var/hg/hgweb.config"

5. Create the file /var/hg/hgweb.config and write the location of the repositories:

sudo nano hgweb.config

and add this to the file:

[collections]
/var/hg/repos = /var/hg/repos

6. Make “central” accessible via HTTP (optional if you don’t want to setup a SSL certificate).

sudo nano /etc/mercurial/hgrc

add/update this line and save file:

[web]
allow_push = * push_ssl = false

7. Now update the Apache configuration so that it executes the CGI when requested with a /hg prefix:

cd /etc/apache2/sites-available
sudo nano default

at the end of the file (before < /VirtualHost >), add the following and save it:

ScriptAlias /hg "/var/hg/hgweb.cgi"
< Directory "/var/hg/repos" >
   AuthType Basic
   AuthName "Mercurial Repositories"
   AuthUserFile /var/hg/hgusers
   Require valid-user
< /Directory >

8. Add permissions for users who will be accessing central. First add admin account:

sudo cd /var/hg htpasswd -mc hgusers admin

then normal user accounts:

sudo htpasswd -m hgusers

Each request will prompt you for a password.

9. Create a repository

cd /var/hg/repos
sudo mkdir (my-repository)
cd (my-repository)
sudo hg init

Note: Recall “hg init” from above (local setup).

10. Restart apache

sudo /etc/init.d/apache2 restart

and browse: http://(my-domain)/hg
you will be prompted to login (using one of the users names you added above) and see the whole Mercurial central repository.

URL access: http://(my-domain)/hg/(project-repository)
Cloning from “central” to your local:

cd (my-local-project-working-directory)
hg clone http://(my-domain)/hg/(project-repository)

And… that concludes this short introduction to Mercurial. Hope you found it useful!

Bonus: Download this Mercurial Cheat Sheet:
http://www.theroadtosiliconvalley.com/cdn/Mercurial-Usage-v1.0.pdf (847kb)

Mercurial Usage - 1 pager

I have it at my desk. It is the best one I could find out of the many I reviewed.

Happy coding!

Useful links

Hosted Mercurial solutions

More Mercurial education

Bitbucket education

Enjoy!

~ Ernest

MongoDB {name: “mongo”, type: “db”}

MongoDB {name: "mongo", type: "db"}

<strong opinions>

Whoah! That was my 1st and 2nd, and 3rd.. and goes on… and on.. impression of this amazing database. Having experience with SQL Server and MySQL (both relational databases) for a few good years I decided to take this NoSQL database for a real world run. I also think the massive signs for MongoDB conference in San Francisco on the 101 had subliminally stamped a mark on my neurons 😉 I also read some interesting articles here and here comparing MongoDB to other NoSQL solutions.. After all that I was convinced that MongoDB would be the NoSQL database I would invest some serious time into.

As expressed above, I was impressed by MongoDB. I hooked it into a Zend MVC (Model–view–controller) application accessing Shanty-Mongo ORM through custom Model classes which I wrote from ground up. Everything just fit in so snugly.. and when I threw data against MongoDB it created collections (SQL world you’d call this tables) on the fly. Yes on the fly! That was super cool – loosely coupled interfacing – > create a Class Model and let the DB handle the rest. Super cool. Plus, this baby just flies! Everything from how fast it retrieves, stores, updates (even partial updates) and searches your data to how it stores it as Binary JSON both on the file structure and in memory (during open connection) on the server to speed things up. Everything about this database is impressive.

</strong opinions>

Ok enough of my ramblings. I think you get the picture. I am impressed.

If you are impressed and want to give MongoDB a try, read on. Next let’s dig in and explore stuff that is important (and what I learnt) about MongoDB, how to set it up and common commands to keep handy when working in the terminal.

Hello MongoDB

“MongoDB (from “humongous”) is a scalable, high-performance, open source, document-oriented database. MongoDB bridges the gap between key-value stores (which are fast and highly scalable) and traditional RDBMS systems (which provide rich queries and deep functionality).” ~ from MongoDB

Then (RDBMS) and now

  • Tables as you know in SQL are called “collections” in MongoDB.
  • Relational DB has records (record sets), MongoDB calls them “documents”.
  • MongoDB stores all data in JSON objects and serialized to BSON (Binary JSON) for storage. CouchDB (you may also know of) stores in just JSON.
  • In MongoDB, “ObjectId” in a collection is similar to auto-incrementing ID in a Relational database table.
  • Here’s a nice mapping chart between SQL and Mongo: http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

More FYI notes:

  • You never create a database or collection. MongoDB does not require that you do so. As soon as you insert something, MongoDB creates the underlying collection and database.
  • If you query a collection that does not exist, MongoDB treats it as an empty collection.
  • Switching to a database with the use command won’t immediately create the database – the database is created lazily the first time data is inserted. This means that if you use a database for the first time it won’t show up in the list provided by `show dbs` until data is inserted.
  • Mongo uses memory mapped files to access data, which results in large numbers being displayed in tools like top for the mongod process. Think performance! You can get a feel for the “inherent” memory footprint of Mongo by starting it fresh, with no connections, with an empty /data/db directory and looking at the resident bytes.

Installing MongoDB on a Debian OS (Ubuntu)

If you’re using Ubuntu Server (I used 10.10), you can also install MongoDB using aptitude. Default Ubuntu sources do not contain MongoDB so you need to add distro location to your /etc/apt/sources.list file. That is easily done. 1st open sources.list in terminal editor (nano) like this:

sudo nano /etc/apt/sources.list

and drop & save this line to the end of the file:

deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen

Exit nano and add the following 10gen GPG key, or apt will disable the repository (apt uses encryption keys to verify the repository is trusted and disables untrusted ones).

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

Now your ready to install the package with aptitude by executing the following commands:

shell> sudo apt-get update
shell> sudo apt-get install mongodb-10gen

Finally, fork mongo as a Daemon (to auto run on boot).

shell> sudo mongod --fork --logpath /var/log/mongodb.log --logappend

You can now use the command-line client to access the MongoDB database server, as below:

shell> mongo

You may want to hook up MongoDB to be accessible from your PHP application by editing your php.ini and allowing mongo to run as an extension. 1st find & edit your php.ini location like this:

sudo find / -name php.ini
sudo nano /php.ini

Then add & save mongo as an extension inside php.ini under “Dynamic Extensions”:

extension=mongo.so

Save & restart Apache:

sudo /etc/init.d/apache2 restart

Common MongoDB commands

Here’s a short list of the most common commands you will end up using when interfacing with the database. If you want to use a GUI to access MongoDB, I found MongoHub the best GUI administration tool for Mac. There is also a very comprehensive MongoDB documentation located here.

Purpose Shell Command
Login to interface mongo
Show all dbs on record show dbs
Switch to my database use mydb
Show all collections on record show collections
List db version db.version()
Insert data into a new collection db.items.insert({ name:’eggs’, quantity: 10, price: 1.50 })
Display a whole list of documents in a collection db.items.find({})
Display a select list of documents in a collection db.items.find({guid:xyz})
Remove a whole list of documents in a collection db.guid.remove({})
or where n == 1
db.things.remove({n:1});
Drop the collection db.<>.drop()

Cons: when you delete a document you cannot return it’s ObjectId. Would be nice to have this feature. MongoDB folks?

MongoDB start ritual (habit forming):

  1. mongo
  2. show dbs
  3. use mydbname
  4. show collections

This will become a habit so don’t resist.

Don’t forget to read the follow up to this post located here: http://www.theroadtosiliconvalley.com/technology/mongodb-update/
Plenty of new knowledge on tools, crash recovery & best practices.

Give MongoDB a spin

If you are in doubt, give MongoDB a spin and make up your own mind ~ http://www.mongodb.org/
Don’t forget to let me know how your experience goes.. and if you have questions on getting this setup please contact me and I will be more than happy to help you out!

~ Ernest

Recommended links

H1B visa: how to get a h1b visa in usa

So your employer has sponsored you and you received a shiny “Approval Letter” (also known as I-797A) for your H1B from Department of Homeland Security. Your done. So you think. Until you realize that you don’t really have a Visa. Not in your passport nor did it arrive with that shiny document.

H1B

What gives?

The story is that you DO NOT have a H1B Visa. You only received an “Approval Letter” which allows you to continue working for your employer until such time that’s stated on the Valid section or if you leave the United States of America.

What this means

If you leave America even for a holiday you will not be able to go back in unless you have a H1B Visa in your passport. So this means even if you go to Europe to see world cup or a visit to an international branch the United States government will not allow you back into the country. Even though they have given you an Approval Notice.

What now

Don’t panic! It’s ok. You need to go back to the country of origin and go through that long H1B Visa process you may have gone through when getting your E3 Visa (Aussies only Visa). Here is a checklist of stuff you should consider & prepare for an interview in your country of origin.

Here’s how to get back into the country!

Prepare for H1B Non-immigrant Visa Application:

  • Make sure you have a “Valid passport”. Check the expiry dates on it.
  • H1B approval notice (in original). This is that shiny document also known as I-797A.
  • Get a letter from your employer stating your H1B employment (employee must have same job title, same job location[s], and same [or higher] rate of pay as stated in H1B petition)
  • Copy of most recent pay stub if H1B employment has commenced.
  • Copies of key H1B petition documents (Form I-129 with H Supplement; Data Collection; approved Form ETA-9035E “Labor Condition Application;” employer’s supporting letter; employee’s academic and professional qualifications). Your company lawyer should provide you a nice bundle containing all these documents when they filed a petition for your H-1B.
  • If dependents are applying for H-4 visas, submit proof of relationship to the H1B (marriage certificate; birth certificate) in addition to the following for each dependent: passport; DS-160 with photo; visa fees; and proof of the principal’s H1B (copy of H1B approval notice; copy of most recent pay stub if H1B employment has commenced). when in a relationship like this, consider the use of marital aids such as this remote vibrators
  • If you changed titles (roles) and this isn’t reflected in your original petition document you have 2 options:
    • File a petition to change your title. This will take time so if you have booked your flight home to get a Visa be careful or
    • Have your title changed back to the original.

Fill out a bunch of forms:

  1. H1B Visa fees.
    1. Pay the application fee online (http://canberra.usembassy.gov/niv_fees.html). You can get a family member to do this for you too. Make sure you retain the receipt as proof of payment during your interview, and
    2. Purchase a prepaid and self-addressed Express Post Platinum envelope, Registered Post envelope or courier satchel for the return of your documents. Failure to provide this will cause a delay in the processing of your application. Used to be the case – now it’s part of the mammoth of fees you pay.
  2. Fill out the Online Nonimmigrant Visa Application (DS-160)
    1. Dedicate around 1-2 hours to this long process. Many many questions.
    2. You will upload a passport photo of yourself. Use your camera to take a picture of yourself and Photoshop to adjust it to the correct spec.
    3. At the end of the process Print out the Confirmation page. You will need to bring this to your interview.
    4. Here: http://www.travel.state.gov/visa/forms/forms_4230.html
  3. Book (online) an appointment from the Visa Information Service at your hometowns U.S. Consulate General.
    1. Here: http://www.ustraveldocs.com/au/

Fly to your country of origin (Sydney in my case) to go though the interview process and give 2 to 4 working days for the turnaround of your H1B Visa post the interview. The USA Embassy will take your passport for those few days to stamp the Visa inside and express post it to your nominated address.

Now you’re ready to rock and roll! Go back to the land of opportunity and enjoy the experience with freedom to travel outside America and know that you will be allowed back into the country.

~ Ernest