Posts Tagged 'Code'

How many languages can you speak (sorry, fellow geeks; I mean human languages, not programming)?

Every day people across the globe depend more and more on the Internet for their day-to-day activities, increasing the need for software to support multiple languages to accommodate the growing diversity of its users. If you work developing software, this means it is only a matter of time before you get tasked to translate your applications.

Wouldn't it be great if you could learn something with just a few key strokes? Just like Neo in The Matrix when he learns kung fu. Well, wish no more! I'll show you how to teach your applications to speak in multiple languages with just a few key strokes using Watson’s Language Translation service, available through Bluemix. It provides on-the-fly translation between many languages. You pay only for what you use and it’s consumable through web services, which means pretty much any application can connect to it—and it's platform and technology agnostic!

I'll show you how easy it is to create a PHP program with language translation capabilities using Watson's service.

Step 1: The client.

You can write your own code to interact with Watson’s Translation API, but why should you? The work is already done for you. You can pull in the client via Composer, the de-facto dependency manager for PHP. Make sure you have Composer installed, then create a composer.json file with the following contents:

We will now ask Composer to install our dependency. Execute one of the following commands from your CLI:

After the command finishes, you should have a 'vendor' directory created.

Step 2: The credentials.

From Bluemix, add the Language Translation service to your application and retrieve its credentials from the application's dashboard (shown below).

Step 3: Put everything together.

At the same level where the composer.json file was created in Step 1, create a PHP file named test.php with the following contents:

Many companies today are leveraging new tools to automate deployments and handle configuration management. Ansible is a great tool that offers flexibility when creating and managing your environments.

SoftLayer has components built within the Ansible codebase, which means continued support for new features as the Ansible project expands. You can conveniently pull your SoftLayer inventory and work with your chosen virtual servers using the Core Ansible Library along with the SoftLayer Inventory Module. Within your inventory list, your virtual servers are grouped by various traits, such as “all virtual servers with 32GB of RAM,” or “all virtual servers with a domain name of softlayer.com.” The inventory list provides different categorized groups that can be expanded upon. With the latest updates to the SoftLayer Inventory Module, you can now get a list of virtual servers by tags, as well as work with private virtual servers. You can then use each of the categories provided by the inventory list within your playbooks.

So, how can you work with the new categories (such as tags) if you don’t yet have any inventory or a deployed infrastructure within SoftLayer? You can use the new SoftLayer module that’s been added to the Ansible Extras Project. This module provides the ability to provision virtual servers within a playbook. All you have to do is supply the build detail information for your virtual server(s) within your playbook and go.

Let’s look at an example playbook. You’ll want to specify a hostname along with a domain name when defining the parameters for your virtual server(s). The hostname can have an incremental number appended at the end of it if you’re provisioning more than one virtual server; e.g., Hostname-1, Hostname-2, and so on. You just need to specify a value True for the parameter increment. Incremental naming offers the ability to uniquely name virtual servers within your playbook, but is also optional in the case where you want similar hostnames. Notice that you can also specify tags for your virtual servers, which is handy when working with your inventory in future playbooks.

Following is a sample playbook for building Ubuntu virtual servers on SoftLayer:

By default, your playbook will pause until each of your virtual servers completes provisioning before moving onto the next plays within your playbook. You can specify the wait parameter to False if you choose not to wait for the virtual servers to complete provisioning. The wait parameter is helpful for when you want to build many virtual servers, but some have different characteristics such as RAM or tag naming. You can also set the maximum time you want to wait on the virtual servers by setting the wait_timeout parameter, which takes an integer defining the number of seconds to wait.

Once you’re finished using your virtual servers, canceling them is as easy as creating them. Just specify a new playbook step with a state of absent, as well as specifying the virtual server ID or tags to know which virtual servers to cancel.

The following example will cancel all virtual servers on the account with a tag of tomcat-test:

New features are being developed with the core inventory library to bring additional functionality to Ansible on SoftLayer. These new developments can be found by following the Core Ansible Project hosted on Github. You can also follow the Ansible Extras Project for updates to the SoftLayer module.

As of this blog post, the new SoftLayer module is still pending inclusion into the Ansible Extras Project. Click here to check out the current pull request for the latest code and samples.

I highly recommend reading part one of the series. I outlined many HTML5 techniques that had never been possible with anything but Flash or jQuery before. In this blog I’ll continue with additional techniques that I couldn’t fit into the first blog.

I stand by my previous statement that if we forget what we’ve done and scripted for over two decades with previous versions of HTML and return to the basics with HTML5, we can re-learn a whole new foundation that is sure to make us stronger developers and smarter engineers.

IV. No More Declaring Types!

The sole purpose to develop better scripting and tagging languages is to improve efficiency. I think we can all agree that a smarter language should be able to detect certain attributes and tags automatically . . . well now, HTML5 has taken a huge step toward this.

Now <scripts> and <links> can be FREE of the type attribute!

Instead of:

<link type=”text/css” rel=”stylesheet” href=”css/stylesheet.css” />

Or

<script type=”text/javascript” src=”js/javascript.js”></script>

We can now just simply declare:

<link rel=”stylesheet” href=”css/stylesheet.css” />

And

<script src=”js/javascript.js”></script>

Something so little . . . yet so awesome!

V. SEMANTICS! Well . . . partial semantics anyway!

HTML5 supports some semantic tags—the most popular being the header and footers.

Whoo! That’s an AWESOME change. Of course there could be a LOT more semantic changes, but we all know those will be coming soon! Until then, we can enjoy what we have.

VI. Video Support without Third-Party Plugins

Many browsers are jumping on board with providing support for the <video> tag, which allows native playback of videos. Gone are the days of having to use javascript/jQuery or *shudder* Flash to embed videos into your pages.

You’ll notice there are TWO <source> tags; this is because browsers like IE and Safari have already started supporting advanced video formats such as mp4. Firefox and Chrome are still in the process, but for now we still need to provide ogv/ogg videos. It’s only a matter of time before all the browsers will support mp4, but this is definitely a huge step forward from third-party plugins!

You should also notice there are two attributes listed in the <video> tag: controls and preload. Controls embed native video playback controls in the video player while preload allows the video to be preloaded, which is GREAT if you have a page just dedicated to viewing the video.

Thanks for tuning in, and let us know what YOUR favorite new features of HTML5 are! And if you’re interested in a gaming series with HTML5, holla at us, and I’ll get on it! I’ve been dying to write a blog series dedicated to teaching HTML5 gaming with the <canvas> tag!

If you guys have read any of my other blogs, I’m sure you’ll notice a pattern: rather than discussing opinions or news of new technologies, more often than not, I like to write more in the form of tutorials and hands-on exercises that demonstrate either fundamentals or new tips and tricks that I have learned.

In this blog, I’d like to discuss HTML5. I know, I know, it’s not exactly a subject that’s brand new. However, with as many HTML5 implementations as there are out there, and throughout many discussions, I’ve realized that many of the most talented Web developers have had to return to the basics of HTML5 features and techniques in order to redesign projects the same way they developed them.

Simply put: If we forget what we’ve done and scripted for over two decades with previous HTML versions and return to the basics, we can re-learn a new foundation that is sure to make us stronger developers and smarter engineers.

I. Declaration of Independence … or at least a declaration you don’t have to spend hours memorizing!

One of the most raved about features of HTML5 (and yet one of the simplest new features) is the new Doctype. How many of you had to Google the standard Doctype every single time you started a new project? Or perhaps you kept the tag in a code bin for easy copy/pasting? Well, no more!

Of course the actual strict/transitional or html/xhtml would vary depending on your page, but they pretty much worked the same way.

The new HTML5 way:

<!DOCTYPE html>

Done. I know it seems like such a simple thing, but returning to the foundation of what we learned so many years ago and re-learning them in the new HTML5 way will not only strengthen our sites, but it will also build a brand new foundation of flexibility and efficiency. Technology evolves at such a rapid pace that if we don’t keep up, we’re going to be left chasing the wagon of the future.

II. Editable content WITHOUT JavaScript!

HTML5 has added so many advanced features that our need for jQuery can be cut by nearly a third (depending on our requirements of course), which in turn greatly reduces the overhead of the browser’s need to process a ton of jQuery functions. If we utilize just a few of HTML5’s awesome new jQuery-like features, we can speed up our site and keep our .js scripts smaller!

Just for giggles (if you’re not familiar with HTML5’s editable content), give this a try:

Put that into an .html file, and open it up in your favorite browser. You’ll see what should look like this:

A simple list of course. In the years of your career I’m sure you’ve made tens of thousands of these. What’s cool about this list, if you’re not familiar with all of HTML5’s neat little tricks, is that this list is editable. Go ahead and try clicking on the list item and replace the names; even add your own name!

As you can see, I didn’t have the heart to remove any of our most frequent bloggers, so I just appended my name to Mark Quigley (of course, that’s not my true SoftLayer Blog ranking, but one day soon … it shall be!)
This feature may not save the user’s edits, but if you add in some nifty HTML5 storage abilities (local or session), you could have yourself a pretty robust application!

III. Beautiful placeholders to hold a place for my heart.

One of my biggest gripes every time I’d either design or program a user interface (registration, account functionality) was the fact that I would have to integrate a jQuery function just to add a little bit of extra help with the text boxes. Placeholders never worked as they should. Sometimes we just didn’t have enough real estate on the page for the amount of instruction as we needed, which meant another placeholder maker for jQuery.

HTML5 now comes equipped with beautiful support for placeholder text (well, I suppose it depends on your POV on designing/developing forms. If you do it as much as I do, the new placeholders are the holy grail of usable forms!). A very simple preview of what HTML form life was like before HTML5 (without the jQuery function to add text to just one input box):

The fact is: Sometimes we don’t always have the real estate that we would like to provide the user enough instructions to clarify what needs to be done!

This simple form could end up being very confusing for the user. It’s so simple, yet there are several ways to enter a phone number, and depending on the backend, it may only accept one format.

Just by adding the simple placeholder attribute, we have now cleared up exactly what format we need the phone number! Now let’s have a look:

It’s funny how a simple, light-colored demonstration of acceptable input can really beautify a form and increase usability. With the placeholder attribute in place in this example, I’m not even sure it’s necessary to have the instruction text on the right, as we can clearly see we need 10 digits, with parenthesis and dashes.

Well my friends, looking at the word count of this document, it looks like this blog is coming to a close, and I’ve only gone over three of my favorite foundational features of HTML5, so you know what that means … Part 2!

If you guys have read any of my past blogs, you know how much I LOVE jQuery, but every good developer knows that if there’s an easier or more efficient way of doing something: DO IT. With all the new developments with CSS3, HTML5, etc. etc., sometimes we have to get back to basics to relearn how to do things more efficiently, so here it goes!

Nearly every website has some form of 2.0/dynamic/generated content nowadays, and if your site doesn’t… well, it probably should catch up! I’ll show you how with some new CSS tricks and how it can reduce a lot of overhead of including the entire jQuery library (which would save you approximately 84kb per page load, assuming you have no other asynchronous/client side functionality you need).

I’ll start off with an easy example, since I know most of you take these examples and let your creativity run wild for your own projects. (Note to self: start a “Code Gone Wild” series.)

Usually this is the part where I say “First, let’s include the jQuery library as always.” Not this time, let’s break the rules!

FIRST, start off your document like any other (with the basic structure, set your DOCTYPE appropriately, i.e. strict vs transitional):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>

Wow, you can already tell this generated content’s going to be a TON easier than using jQuery (for those of you whom aren’t already jQuery fans).

Now let’s add in a div there; every time we hover over that div, we’re going to display our generated content with CSS. Inside of our div, we’re going to place a simple span, like so:

As you can see, the span content contains a simple question and the data-title attribute contains the answer to that question.

Now let’s just make this div a little bit prettier before we get into the fancy stuff.

Add some style to the <head> section of our document:

<style>
.slisawesome {
/* Will TOTALLY be making another blog about the cool CSS gradients soon */
background:linear-gradient(to bottom, #8dd2d9 , #58c0c7);
padding: 20px; /* give the box some room to breathe */
width: 125px; /* give it a fixed width since we know how wide it should be */
margin: 100px auto; /* move it away from the top of the screen AND center it */
border: 1px solid black; /* this is just a little border */
position: relative; /* this is to help with our generated content positioning */
}
</style>

Now you should have something that looks like this:

This is good; this is what you should have. Now let’s make the magic happen and add the rest of our CSS3:

<style>
.slisawesome {
/* Will TOTALLY be making another blog about the cool CSS gradients soon */
background:linear-gradient(to bottom, #8dd2d9 , #58c0c7);
padding: 20px; /* give the box some room to breathe */
width: 125px; /* give it a fixed width since we know how wide it should be */
margin: 100px auto; /* move it away from the top of the screen AND center it */
border: 1px solid black; /* this is just a little border */
position: relative; /* this is to help with our generated content positioning */
}
.slisawesome span::before {
content:attr(data-title); /* assigning the data-title attribute value to the content */
opacity: 0; /* hiding data-title until we hover over it */
position: absolute; /* positioning our data-title content */
margin-top: 50px; /* putting more space between our question and answer */
/* Fancy transitions for our data-title when we hover over our question */
/* which I’m TOTALLY going to write another blog for ;) If you guys want, of course */
-webkit-transition:opacity 0.4s; /* determines the speed of the transition */
transition:opacity 0.4s; /* determines the speed of the transition */
}
</style>

Despite my anticlimactic adding of “the magic,” we just added a :hover that will show full opacity when we hover, so refresh your page and try it out! You should see something like this when you hover over THE QUESTION:

Of course you could REALLY start getting fancy with this by adding some php variables for the logged in user, or perhaps make it dynamic to location, time, etc. The possibilities are endless, so go… go and expand on this awesome generated content technique!

"What is SoftLayer doing with OpenStack?" I can't even begin to count the number of times I've been asked that question over the last few years. In response, I'll usually explain how we've built our object storage platform on top of OpenStack Swift, or I'll give a few examples of how our customers have used SoftLayer infrastructure to build and scale their own OpenStack environments. Our virtual and bare metal cloud servers provide a powerful and flexible foundation for any OpenStack deployment, and our unique three-tiered network integrates perfectly with OpenStack's Compute and Network node architecture, so it's high time we make it easier to build an OpenStack environment on SoftLayer infrastructure.

To streamline and simplify OpenStack deployment for the open source community, we've published Opscode Chef recipes for both OpenStack Grizzly and OpenStack Havana on GitHub: SoftLayer Chef-Openstack. With Chef and SoftLayer, your own OpenStack cloud is a cookbook away. These recipes were designed with the needs of growth and scalability in mind. Let's take a deeper look into what exactly that means.

OpenStack has adopted a three-node design whereby a controller, compute, and network node make up its architecture:

Looking more closely at any one node reveal the services it provides. Scaling the infrastructure beyond a few dozen nodes, using this model, could create bottlenecks in services such as your block store, OpenStack Cinder, and image store, OpenStack Glance, since they are traditionally located on the controller node. Infrastructure requirements change from service to service as well. For example OpenStack Neutron, the networking service, does not need much disk I/O while the Cinder storage service might heavily rely on a node's hard disk. Our cookbook allows you to choose how and where to deploy the services, and it even lets you break apart the MySQL backend to further improve platform performance.

Quick Start: Local Demo Environment

To make it easy to get started, we've created a rapid prototype and sandbox script for use with Vagrant and Virtual Box. With Vagrant, you can easily spin up a demo environment of Chef Server and OpenStack in about 15 minutes on moderately good laptops or desktops. Check it out here. This demo environment is an all-in-one installation of our Chef OpenStack deployment. It also installs a basic Chef server as a sandbox to help you see how the SoftLayer recipes were deployed.

Creating a Custom OpenStack Deployment

The thee-node OpenStack model does well in small scale and meets the needs of many consumers; however, control and customizability are the tenants for the design of the SoftLayer OpenStack Chef cookbook. In our model, you have full control over the configuration and location of eleven different components in your deployed environment:

Our Chef recipes will take care of populating the configuration files with the necessary information so you won't have to. When deploying, you merely add the role for the matching service to a hardware or virtual server node, and Chef will deploy the service to it with all the configuration done automatically, including adding multiple Neutron, Nova, and Cinder nodes. This approach allows you to tailor the needs of each service to the hardware it will be deployed to--you might put your Neutron hardware node on a server with 10-gigabit network interfaces and configure your Cinder hardware node with RAID 1+0 15k SAS drives.

OpenStack is a fast growing project for the implementation of IaaS in public and private clouds, but its deployment and configuration can be overwhelming. We created this cookbook to make the process of deploying a full OpenStack environment on SoftLayer quick and straightforward. With the simple configuration of eleven Chef roles, your OpenStack cloud can be deployed onto as little as one node and scaled up to many as hundreds (or thousands).

To follow this project, visit SoftLayer on GitHub. Check out some of our other projects on GitHub, and let us know if you need any help or want to contribute.

Ever have a bunch of files to rename or a large set of files to move to different directories? Ever find yourself copy/pasting nearly identical commands a few hundred times to get a job done? A system administrator's life is full of tedious tasks that can be eliminated or simplified with the proper tools. That's right ... Those tedious tasks don't have to be executed manually! I'd like to introduce you to one of the simplest tools to automate time-consuming repetitive processes in Bash — the for loop.

Whether you have been programming for a few weeks or a few decades, you should be able to quickly pick up on how the for loop works and what it can do for you. To get started, let's take a look at a few simple examples of what the for loop looks like. For these exercises, it's always best to use a temporary directory while you're learning and practicing for loops. The command is very powerful, and we wouldn't want you to damage your system while you're still learning.

How did that simple command populate the directory with all of the letters in the alphabet? Let's break it down.

for cats_are_cool in{a..z}

The for is the command we are running, which is built into the Bash shell. cats_are_cool is a variable we are declaring. The specific name of the variable can be whatever you want it to be. Traditionally people often use f, but the variable we're using is a little more fun. Hereafter, our variable will be referred to as $cats_are_cool (or $f if you used the more boring "f" variable). Aside: You may be familiar with declaring a variable without the $ sign, and then using the $sign to invoke it when declaring environment variables.

When our command is executed, the variable we declared in {a..z}, will assume each of the values of a to z. Next, we use the semicolon to indicate we are done with the first phase of our for loop. The next part starts with do, which say for each of a–z, do <some thing>. In this case, we are creating files by touching them via touch $cats_are_cool. The first time through the loop, the command creates a, the second time through b and so forth. We complete that command with a semicolon, then we declare we are finished with the loop with "done".

This might be a great time to experiment with the command above, making small changes, if you wish. Let's do a little more. I just realized that I made a mistake. I meant to give the files a .txt extension. This is how we'd make that happen:

for dogs_are_ok_too in{a..z}; domv$dogs_are_ok_too$dogs_are_ok_too.txt; done;Note: It would be perfectly okay to re-use $cats_are_cool here. The variables are not persistent between executions.

As you can see, I updated the command so that a would be renamed a.txt, b would be renamed b.txt and so forth. Why would I want to do that manually, 26 times? If we check our directory, we see that everything was completed in that single command:

Now we have files, but we don't want them to be empty. Let's put some text in them:

for f in`ls`; docat/etc/passwd>$f; done

Note the backticks around ls. In Bash, backticks mean, "execute this and return the results," so it's like you executed ls and fed the results to the for loop! Next, cat /etc/passwd is redirecting the results to $f, in filenames a.txt, b.txt, etc. Still with me?

So now I've got a bunch of files with copies of /etc/passwd in them. What if I never wanted files for a, g, or h? First, I'd get a list of just the files I want to get rid of:

rasto@lmlatham:~/temp$ ls|egrep'a|g|h'
a.txt
g.txt
h.txt

Then I could plug that command into the for loop (using backticks again) and do the removal of those files:

for f in`ls|egrep'a|g|h'`; dorm$f; done

I know these examples don't seem very complex, but they give you a great first-look at the kind of functionality made possible by the for loop in Bash. Give it a whirl. Once you start smartly incorporating it in your day-to-day operations, you'll save yourself massive amounts of time ... Especially when you come across thousands or tens of thousands of very similar tasks.

Linux admins often encounter rogue processes that die without explanation, go haywire without any meaningful log data or fail in other interesting ways without providing useful information that can help troubleshoot the problem. Have you ever wished you could just see what the program is trying to do behind the scenes? Well, you can — strace (system trace) is very often the answer. It is included with most distros' package managers, and the syntax should be pretty much identical on any Linux platform.

First, let's get rid of a misconception: strace is not a "debugger," and it isn't a programmer's tool. It's a system administrator's tool for monitoring system calls and signals. It doesn't involve any sophisticated configurations, and you don't have to learn any new commands ... In fact, the most common uses of strace involve the bash commands you learned the early on:

read

write

open

close

stat

fork

execute (execve)

chmod

chown

You simply "attach" strace to the process, and it will display all the system calls and signals resulting from that process. Instead of executing the command's built-in logic, strace just makes the process's normal calls to the system and returns the results of the command with any errors it encountered. And that's where the magic lies.

Let's look an example to show that behavior in action. First, become root — you'll need to be root for strace to function properly. Second, make a simple text file called 'test.txt' with these two lines in it:

# cat test.txt
Hi I'm a text file
there are only these two lines in me.

Now that return may look really arcane, but if you study it a little bit, you'll see that it includes lots of information that even an ordinary admin can easily understand. The first line returned includes the execve system call where we'd execute /bin/cat with the parameter of test.txt. After that, you'll see the cat binary attempt to open some system libraries, and the brk and mmap2 calls to allocate memory. That stuff isn't usually particularly useful in the context we're working in here, but it's important to understand what's going on. What we're most interested in are often open calls:

open("test.txt", O_RDONLY|O_LARGEFILE) = 3

It looks like when we run cat test.txt, it will be opening "test.txt", doesn't it? In this situation, that information is not very surprising, but imagine if you are in a situation were you don't know what files a given file is trying to open ... strace immediately makes life easier. In this particular example, you'll see that "= 3" at the end, which is a temporary sort of "handle" for this particular file within the strace output. If you see a "read" call with '3' as the first parameter after this, you know it's reading from that file:

read(3, "Hi I'm a text file\nthere are onl"..., 4096) = 57

Pretty interesting, huh? strace defaults to just showing the first 32 or so characters in a read, but it also lets us know that there are 57 characters (including special characters) in the file! After the text is read into memory, we see it writing it to the screen, and delivering the actual output of the text file. Now that's a relatively simplified example, but it helps us understand what's going on behind the scenes.

Real World Example: Finding Log Files

Let's look at a real world example where we'll use strace for a specific purpose: You can't figure out where your Apache logs are being written, and you're too lazy to read the config file (or perhaps you can't find it). Wouldn't it be nice to follow everything Apache is doing when it starts up, including opening all its log files? Well you can:

strace-Ff-o output.txt -e open /etc/init.d/httpd restart

We are executing strace and telling it to follow all forks (-Ff), but this time we'll output to a file (-o output.txt) and only look for 'open' system calls to keep some of the chaff out of the output (-e open), and execute '/etc/init.d/httpd restart'. This will create a file called "output.txt" which we can use to find references to our log files:

The log files jump out at you don't they? Because we know that Apache will want to open its log files when it starts, all we have to do is we follow all the system calls it makes when it starts, and we'll find all of those files. Easy, right?

Real World Example: Locating Errors and Failures

Another valuable use of strace involves looking for errors. If a program fails when it makes a system call, you'll want to be able pinpoint any errors that might have caused that failure as you troubleshoot. In all cases where a system call fails, strace will return a line with "= -1" in the output, followed by an explanation. Note: The space before -1 is very important, and you'll see why in a moment.

For this example, let's say Apache isn't starting for some reason, and the logs aren't telling ua anything about why. Let's run strace:

strace-Ff-o output.txt -e open /etc/init.d/httpd start

Apache will attempt to restart, and when it fails, we can grep our output.txt for '= -1' to see any system calls that failed:

With experience, you'll come to understand which errors matter and which ones don't. Most often, the last error is the most significant. The first few lines show the program trying different libraries to see if they are available, so they don't really matter to us in our pursuit of what's going wrong with our Apache restart, so we scan down and find that the last line:

Our error couldn't be found in the log file because Apache couldn't open it! You can imagine how long it might take to figure out this particular problem without strace, but with this useful tool, the cause can be found in minutes.

Go and Try It!

All major Linux distros have strace available — just type strace at the command line for the basic usage. If the command is not found, install it via your distribution's package manager. Get in there and try it yourself!

For a fun first exercise, bring up a text editor in one terminal, then strace the editor process in another with the -p flag (strace -p <process_id>) since we want to look at an already-running process. When you go back and type in the text editor, the system calls will be shown in strace as you type ... You see what's happening in real time!

Whether you're new to software development or you've been a coder since the punchcard days, at some point, you've probably come across horrendous performance problems with your website or scripts. From the most advanced users — creating scripts so complex that their databases flooded with complex JOINs — to the novice users — putting SQL calls in loops — database queries can be your worst nightmare as a developer. I hate to admit it, but I've experienced some these nightmares first-hand as a result of some less-than-optimal coding practices when writing some of my own scripts. Luckily, I've learned how to use memcached to make life a little easier.

What is Memcached?

Memcached is a free and open source distributed memory object caching system that allows the developer to store any sort of data in a temporary cache for later use, so they don't have to re-query it. By using memcached, a tremendous performance load can be decreased to almost nil. One of the most noteworthy features of the system is that it doesn't cache EVERYTHING on your site/script; it only caches data that is sure to be queried often. Originally developed in 2003 by Brad Fitzpatrick to improve the site performance of LiveJournal.com, memcached has grown tremendously in popularity, with some of the worlds biggest sites — Wikipedia, Flickr, Twitter, YouTube and Craigslist — taking advantage of the functionality.

How Do I Use Memcache?

After installing the memcached library on your server (available at http://memcached.org/), it's relatively simple to get started:

<?php// Set up connection to Memcached$memcache=new Memcached();$memcache->connect('host',11211) or die("Could not connect");// Connect to database here// Check the cache for your query$key=md5("SELECT * FROM memcached_test WHERE id=1");$results=$memcache->get($key);// if the data exists in the cache, get it!if($results){echo$results['id'];echo'Got it from the cache!';}else{// data didn't exist in the cache$query="SELECT * FROM memcached_test WHERE id=1");$results=mysql_query($query);$row=mysql_fetch_array($results);print_r($row);// though we didn't find the data this time, cache it for next time!$memcache->set($key,$row,TRUE,30);// Stores the result of the query for 30 secondsecho'In the cache now!';}?>

Querying the cache is very similar to querying any table in your database, and if that data isn't cached, you'll run a database query to get the information you're looking for, and you can add that information to the cache for the next query. If another query for the data doesn't come within 30 seconds (or whatever window you specify), memcached will clear it from the cache, and the data will be pulled from the database.

So come on developers! Support memcached and faster load times! What other tools and tricks do you use to make your applications run more efficiently?

Many of us remember when Flash was the "only" way to enhance user experience and create rich media interactivity. It was a bittersweet integration, though ... Many users didn't have the browser compatibility to use it, so some portion of your visitors were left in the dark. Until recently, that user base was relatively small — the purists who didn't want Flash or the people whose hardware/software couldn't support it. When Apple decided it wouldn't enable Flash on the iPhone/iPad, web developers around the world groaned. A HUGE user base (that's growing exponentially) couldn't access the rich media and interactive content.

In the last year or so, Adobe released Flash Media Server to circumvent the Apple-imposed restrictions, but the larger web community has responded with a platform that will be both compatible and phenomenally functional: HTML5.

HTML5 allows us to do things we've never been able to do before (at least without the hassle of plugins, installations and frustration). Gone are the limitations that resigned HTML to serving as a simple framework for webpages ... Now developers can push the limits of what they thought possible. As the platform has matured, some developers have even taken it upon themselves to prototype exactly where this generation of scripting is heading by creating Flash-free browser games.

Yes, you read that right: Games you can actually play on your browser, WITHOUT plugins.

From simple Pong clones that use browser windows as the paddles and ball to adventure-based Zelda-like massively multiplayer online role playing games (MMORPGs) like BrowserQuest, it's pretty unbelievable to see the tip of the iceberg of possibilities enabled by HTML5 ... Though it does seem a bit ironic to say that a Pong clone is such a great example of the potential of the HTML5 platform. Click on the screenshot below to check out BrowserQuest and tell me it doesn't amaze you:

With an ingenious combination of CSS, JavaScript and HTML5, developers of BrowserQuest have been able to accomplish something that no one has ever seen (nor would ever even have thought possible). Developers are now able to generate dynamic content by injecting JavaScript into their HTML5 canvasses:

Look familiar? The game-making process (not syntax!) appears eerily similar to that of any other popular language. The only difference: You don't need to install this game ... You just open your browser and enjoy.

Using a popular port of Box2D, a physics simulator, making pure browser-based games is as simple as "Make. Include. Create." Here's a snippit:

We may be a few years away from building full-scale WoW-level MMORPGs with HTML5, but I think seeing this functionality in native HTML will be a sigh of relief to those that've missed out on so much Flash goodness. While developers are building out the next generation of games and apps that will use HTML5, you can keep yourself entertained (and waste hours of time) with the HTML5 port of Angry Birds!

HTML5 is not immune to some browser compatibility issues with older versions, but as it matures and becomes the standard platform for web development, we're going to see what's to come in our technology's immediate future: Pure and simple compatibility for all.