Posts tagged "programming"

JavaScript Puzzlers @ VanJS

At Adobe MAX this year, I presented the first in a series of presentations that I call “Puzzlers“. Inspired by Joshua Bloch’s Java Puzzlers, my talk presented some peculiar, and sometimes seemingly wrong, behavior in the JavaScript programming language, all demonstrated through the use of clever puzzles! Anyways, the talk had some great feedback, and started some fantastic discussions, and so I thought I should keep going. I most recently finished presenting a variation of this talk to the fine folks at the Vancouver JavaScript Developer Group, VanJS. Below is the video…

Thanks to the awesome folks at VanJS for having me!


JavaScript Puzzlers – Puzzles That Make You Think (presented at Adobe MAX 2013)

I’ve just recently returned from Adobe MAX 2013, Adobe’s annual “Creativity Conference”.  I had the opportunity to host a session this year.  I ended up doing a presentation called “JavaScript Puzzlers”.  In short, my presentation presents the audience with short, code-based “puzzles” which the audience then has to solve.  The puzzles themselves are quite simple, anywhere from 2 to 20 lines of code.  The answers, however, more often than not, can be quite surprising.  Well, the video from the presentation has finally gone online and so here it is…

I’ve also made the full set of slides available here…

We had a great turnout, and some fantastic discussions!  Thanks to everyone who was able to attend!  I had a blast!




Javascript Puzzlers at Adobe MAX 2013!

Adobe MAX 2013 Banner

Come one, come all! Adobe MAX 2013 is just around the corner! For those of you attending, I’ll be presenting a session on the last day based on my “Puzzler” series! The session will be geared towards Javascript developers, particularly, helping you identify quirky behaviour and subtle nuances of the language. The goal of this presentation will be to give you some extra understanding around these scenarios to hopefully help you write better code, all presented in a series of fun “puzzles” :) The session is called “Javascript Puzzlers”, and here are the details…

What: JavaScript Puzzlers: Puzzles to Make You Think (and write fewer bugs)
When: Wednesday, May 8th from 3:30PM – 4:30PM
Where: Los Angeles Convention Center, Room 504, 1201 South Figueroa Street, Los Angeles, CA
Why: Because Javascript can be tricky!

For those of you who aren’t attending, that’s okay! You can register here to watch the keynotes and select featured sessions online live and for free!

Register to view keynotes online for FREE!

Finally, for those who are interested in registering to attend in person, there are still spots available! Register here!

Register to attend Adobe MAX 2013!

Hope to see you there!


Facebook Desktop! Open-Sourced!

Last year, I wrote about a side project of mine that I was working on at the time called “Facebook Desktop“.  In short, it is a real-time notification engine built for Facebook! I built it because I felt it filled a need that Facebook didn’t fill…

It kept me connected to Facebook (and my friends) without having to
keep a browser window opened to the entire time.

It ended up becoming quite a popular project, amassing over 500,000 downloads, over 2 million API calls PER DAY, written about by numerous blogs and publications around the world, used in over 30 countries, and localized into 20 different languages, all in the short 14 months since it was released!  Low-and-behold, Facebook had issue with my app (I think because I called it “Facebook Desktop”) and so they “asked” me to shut it down.  Rather than argue with the well-known startup company, I decided to comply. It was a wild ride, and I learned a LOT (perhaps I’ll write another blog post about this), but as the saying goes, “All good things must come to an end”.

However, there is always a silver lining!  To build Facebook Desktop, I had to write a lot of custom code (obviously).  I’ve already open-sourced a lot of the individual components that I wrote, including…

But, now that I’m moving on to other things, I’ve decided to go ahead and open-source the entire project!  Just as I’ve done with all of my other open-source projects, I’ve made Facebook Desktop available on GitHub.  You can download it and run it out-of-the-box!


Facebook Desktop is a notification engine that provides real-time updates of your Facebook friends straight to your desktop, without requiring a browser!  Here is a short list of some of the features that I’ve built in…

  • Real-time notification of Facebook activity
  • Language support for 20 different languages!
  • User-presence logic that detects when to display notifications
  • Operating-system detection that adapts interface to match native applications
  • Smart notification engine, including adaptive repositioning, individual notification settings, variable display length, and support for custom styling
  • Persistent user-settings, including preferred language, display length, appearance, and icon-click action
  • Ability to fully filter notifications by source and action
  • Support for updating status


Facebook Desktop is written with Adobe Flash Builder 4.5 using the Adobe Flex 4.5 SDK and the Adobe AIR 3.0 SDK.  It makes use of the following open-source libraries…

Code, please!

I’ve released the code under the Apache License, Version 2.0 and made it all available on GitHub! Please, fork and extend!

Facebook Desktop on GitHub

This marks the end of a fun-filled side-project for me, but perhaps the start for someone else :D  As always, I love hearing from you so let me know what you think! Until next time, happy coding =)



ActionScript Puzzler – Block Party!

Hi, everyone! It’s been a while, but it’s time now for another Puzzler! This time, we’ll do another ActionScript Puzzler! For those of you that don’t know what a Puzzler is, let me quickly explain. A Puzzler is essentially a short and simple programming problem that is used to demonstrate special cases or “features” of a programming language. See some of my old ones here, here, and here.

This time, I’ve decided to try something new. Rather than writing a blog post about it, I’ve made a video Puzzler instead! Watch below! And as always, feedback is always welcome!

If you like these video Puzzlers, let me know and I can do more! Or, if you prefer the blog-post style, let me know too. Until next time, happy coding!


OAuth 2.0 Library for ActionScript

Here at Adobe, we’ve been working really hard recently on our latest big project: Adobe Creative Cloud. For anyone that is unfamiliar or wasn’t able to attend our latest MAX conference, here is how we describe the project, straight from our press release

“Adobe Creative Cloud reinvents creative expression by enabling a new generation of services for
creativity and publishing, that embrace touch interaction to re-imagine how individuals interact with
creative tools and build deeper social connections between creatives around the world.”

-Kevin Lynch, CTO, Adobe Systems

In a nutshell, Creative Cloud is really an ecosystem that includes a multitude of applications for various devices that facilitate creative workflows, all backed by a cloud storage solution. Now that I’m done with the marketing, I can get to the good stuff :)

One of the major tasks that we’ve decided to undertake while doing this project was to switch from our current authentication system to a standards-based OAuth 2.0 authentication and authorization system. This was (is) a large undertaking and included building the likes of an OAuth 2.0 server, building and supporting new OAuth 2.0 compatible clients, as well as converting all existing systems to the new one. As part of this project, I ended up creating some OAuth 2.0 libraries that our touch-tooling applications use to interact with our system. While doing this, I realized that a lot of this work can easily be open-sourced and used with any OAuth 2.0 compliant service! And so, here we are!

Out in the Open
What I’ve created is exactly how it sounds: an OAuth 2.0 library for ActionScript. It abides by the OAuth 2.0 specification (version 2.15) and so is compatible with any OAuth 2.0 service! That includes services like Facebook Platform, Google APIs, Foursquare APIs, and many many more.

What it Does
If you are unfamiliar with the OAuth 2.0 workflow, it is really quite simple…

  1. Your application makes a request to the server to get an access token.
    • An access token is what is used to access a protected resource, say, an API to post a status update.
  2. The user authenticates and authorizes the use of said protected resource by the application on behalf of the user.
    • For example, the user logs in and allows your application to post a status update on their behalf.
  3. An access token is granted and returned back to your application.
    • The access token will be restricted for use with only the specific permissions that were authorized in Step 2.
  4. You use the access token for whatever you want!
    • Using the same example, your application then uses this token to make a call to update your status.

The library is only in charge of steps 1-3. It will just get you your access token. What you do with it, and what API calls you make with it, are up to you.

How to Use It
This library is designed for use in mobile devices using AIR. Because of that, it makes use of the StageWebView object to display the user consent page (the form that the user must log into and authorize your application in Step 2). I’ve created a very simple mobile demo application that does exactly this. Here is the important part of the code…

// set up our StageWebView object to use our visible stage
stageWebView.stage = stage;

// set up the call
var oauth2:OAuth2 = new OAuth2("", "", LogSetupLevel.ALL);
var grant:IGrantType = new AuthorizationCodeGrant(stageWebView, "INSERT_CLIENT_ID_HERE", "INSERT_CLIENT_SECRET_HERE", "", "");

// make the call
oauth2.addEventListener(GetAccessTokenEvent.TYPE, onGetAccessToken);

function onGetAccessToken(getAccessTokenEvent:GetAccessTokenEvent):void
	if (getAccessTokenEvent.errorCode == null && getAccessTokenEvent.errorMessage == null)
		// success!
		trace("Your access token value is: " + getAccessTokenEvent.accessToken);
		// fail :(
}  // onGetAccessToken

You’ll see that the code is quite simple. First, we set up the StageWebView object. Then, we prepare the OAuth2 object by invoking its constructor with the appropriate values. In the third step, we attach an event-listener and make the call. Finally, in the event handler function, we handle the response. That’s it!

I’ve created a sample demo application that demonstrates the usage of this library. Using the same sample code as above (with the appropriate values filled in), connecting to Google’s OAuth 2.0 APIs, the sample app looks like this…

Take it for a spin and let me know what you think!

ActionScript OAuth 2.0 Mobile Demo Application

Code, please!
I’ve released the code under the Apache License, Version 2.0 and made it all available on GitHub! Please, fork and extend!

ActionScript OAuth 2.0 Library

That’s it! Hopefully some of you will find this project useful. And as always, I love hearing from you so let me know what you think! Happy coding =)

Update: As requested, I’ve removed the dependencies on the Flex framework so this library is now a pure AS3 library. Enjoy!


ActionScript Notification Engine! Open-Sourced!

Last year, I posted about a side project that I was working on. Dubbed “Facebook Desktop“, it is essentially a notification engine that I built that would give you updates about your Facebook friends in real time! It became quite popular and I ended up building it out over the next year, pushing out 6 new releases in that time (0.80, 0.81, 0.82, 0.83, 0.84, and 0.85). Well, I’ve decided to contribute to the community and open-source the primary component in Facebook Desktop, the notification engine!

Project M6D Magnum Sidearm
That’s right, I codenamed my notification engine project “Project M6D Magnum Sidearm” (I have a weird naming convention for projects :p). Anyways, it is exactly how it sounds. It is a cross-platform, notification engine built on top of Adobe AIR. With a very simple interface, you can drop it into any AIR project and allow it to deliver messenger-style notifications to your users! Think Growl, but for all platforms :)

Mac:                                                                         Windows:

What can it do?
If you’re familiar with the Facebook Desktop project that this engine was built for, it supports all of the features that you see being used in that project, including…

  • Ability to display messenger-toast notifications as well as compact notifications.
  • Variable display length for notifications.
  • User-presence logic that detects when the user goes idle. If the user is away from the computer, notifications are held on-screen and queued for when the user returns.
  • Ability to replay the most five recent notifications.
  • Individual notification post settings, such as sticky, replayable, custom image, click URL, compact, etc.
  • Operating system detection to set logical default display locations for notifications for the various platforms (i.e. bottom-right on Windows, top-right on Mac).
  • Smart repositioning logic for extended length toasts.
  • Ability to see a summary notification when the user returns from idle after an extended period of time.
  • Support for changing notificaion images.
  • Custom styling which can be applied at run-time.
  • Optional notification sound.

These are just a few of the really cool features that we’ve built into this engine.
How can I use it?
Even though we’ve added a lot of powerful features to this library, using it is very easy! All you have to do is include the SWC (or source) into your project, and follow the patterns below…

// create engine with default settings
var notificationManager:NotificationManager =
	new NotificationManager("/assets/style/dark.swf",		   // default style
				"/assets/m6d-magnum-sidearm-50x50.png",	   // default notification image
				"/assets/m6d-magnum-sidearm-16x16.png",	   // default compact notification image
				"/assets/sounds/drop.mp3"		   // (optional) default notification sound
				NotificationConst.DISPLAY_LENGTH_DEFAULT,  // (optional) default display length
				NotificationConst.DISPLAY_LOCATION_AUTO);  // (optional) default display location
// now that we have an engine, let's create a notification and show it
var notification:Notification = new Notification();
notification.title = "Derek ► Jacobim";
notification.message = "What is this?  A center for ANTS?!";
notification.image = "/assets/images/profile/derek/avatar.png"; = "";
notification.isCompact = false;
notification.isSticky = false;
notification.isReplayable = true;
// we can also show notifications quickly using this API too"Derek Zoolander Foundation", "Now open!", "/assets/images/dzf-logo-50x50.png");

And that’s all it takes for you to add robust notifications to your application. You can even change many of the engines settings on the fly!

// let's change the default images, display length, and display location
notificationManager.defaultNotificationImage = "/assets/images/dzf-logo-50x50.png";
notificationManager.defaultCompactNotificationImage = "/assets/images/dzf-logo-16x16.png";
notificationManager.displayLength = NotificationConst.DISPLAY_LENGTH_SHORT;
notificationManager.displayLocation = NotificationConst.DISPLAY_LOCATION_TOP_RIGHT;
// we can even change the style and sound settings on the fly too!

For those of you that want all the details, you can check out the ASDocs here.
I’ve also created a sample demo application that you can install and see the engine work in real time! It has an interface like this…

…where you can quickly test out all of the features of the engine! Take it for a spin and let me know what you think!

Download Notification Engine Test Console

Code, please!
I’ve released the code under the Apache License, Version 2.0 and made it all available on GitHub! Please, fork and extend!

ActionScript Notification Engine on GitHub

That’s it for now! Hopefully some of you will find this project useful. And as always, I love hearing from you so let me know what you think! Until next time, happy coding =)


Diff Library for ActionScript

I was working on an interesting automation project here at Adobe recently. In short, we wanted to have a utility that shows a particular set of configurations and settings on our various servers and indicates to us if any of the servers are different from the rest, configuration-wise. Sounds simple, right? Sure! So, I thought it would be cool to enhance this a bit and instead of just indicating that yes, there is a difference, I would indicate exactly what that difference was.

Since I’m working predominately with text files, the first thing that came to mind was a diff algorithm. (D’uh!) The front-end for the tool that we use is built in Flex, and so I started looking for a diff algorithm implementation in ActionScript. No luck. Guess I’ll have to write my own :\ I started doing some research on the various approaches to diff algorithms and came to the consensus that the Myer’s diff algorithm[1] is widely accepted as the best general-purpose diff algorithm around. After about 6 pages into the research paper, though, I realized it would take too long to grok this all and implement it from scratch. So, instead, I found an implementation of the Myer’s diff algorithm and ported it to ActionScript. A few hours later, it was done!

As you can tell from the example above, text additions are green, and omissions are red. Any text that is the same remains black. And that’s it!

The usage is quite straightforward, too. There is really only one API, diff(), and it takes two parameters, the before-text and after-text. Done!

var diffs:Array = new Diff().diff(beforeText.text, afterText.text);

The result that you get back is an Array of the different operations that it took to go from the original string to the modified string. You can easily use this to display the differences in whatever way you want!

The code is too long to post here, but you can find it in my GitHub project ->



[1] “An O(ND) Difference Algorithm and Its Variations” by Eugene W. Myers

Relative Time Library for ActionScript

While working on a side-project of mine, I came across the need to display dates and times as relative instead of absolute. You know, saying “two hours ago” instead of “Mon Jan 5 17:24:33 GMT-0700 2011”. Since the web is going real-time these days, it just makes sense. Besides, everyone’s doing it, so it must be good! Anyways, I wrote a library (really, just a simple class) that you can use to do this with ActionScript. It’s really quite simple, but since I couldn’t find it anywhere else, I thought I’d contribute it here for everyone to use too. Here it is in action…


If you’re wondering, I’ve tried to follow the convention that Facebook uses for what format to display and when. Twitter has a very similar format, but I decided to go with Facebook’s. Also, if you notice, my library can handle times in the future as well as times in the past. Here’s how to use it…


Once you’ve added the library to your project, it’s really quite easy to use. Just call any of the two available APIs and pass in a date or two and you’ll get back the relative time string. Done!

var relativeTime:String = RelativeDate.getRelativeDate(firstDate, secondDate);
var relativeTime:String = RelativeDate.getRelativeDateFromNow(someDate);

Finally, here is the code in all it’s glory!

	import com.adobe.utils.DateUtil;
	 * Utility class to help create human-readable Strings representing
	 * the difference in time from two different dates (e.g. "just now"
	 * or "2 hours ago" or "13 minutes from now").
	 * @langversion ActionScript 3.0
	 * @playerversion Flash 10.0
	public class RelativeDate
		private static const SECONDS_PER_MINUTE:uint = 60;
		private static const SECONDS_PER_TWO_MINUTES:uint = 120;
		private static const SECONDS_PER_HOUR:uint = 3600;
		private static const SECONDS_PER_TWO_HOURS:uint = 7200;
		private static const SECONDS_PER_DAY:uint = 86400;
		private static const SECONDS_PER_TWO_DAYS:uint = 172800;
		private static const SECONDS_PER_THREE_DAYS:uint = 259200;
		 * Creates a human-readable String representing the difference
		 * in time from the date provided and now.  This method handles
		 * dates in both the past and the future (e.g. "2 hours ago"
		 * and "2 hours from now".  For any date beyond 3 days difference
		 * from now, then a standard format is returned.
		 * @param date The date for which to compare against.
		 * @return Human-readable String representing the time elapsed.
		public static function getRelativeDateFromNow(date:Date, capitalizeFirstLetter:Boolean = false):String
			return getRelativeDate(date, new Date(), capitalizeFirstLetter);
		 * Creates a human-readable String representing the difference
		 * in time from the first date provided with respect to the
		 * second date provided.  If no second date is provided, then
		 * the relative date will be calcluated with respect to "now".
		 * This method handles dates in both the past and the
		 * future (e.g. "2 hours ago" and "2 hours from now".  For
		 * any date beyond 3 days difference from now, then a
		 * standard format is returned.
		 * @param firstDate The date for which to compare against.
		 * @param secondDate The date to use as "present" when comparing against firstDate.
		 * @return Human-readable String representing the time elapsed.
		public static function getRelativeDate(firstDate:Date, secondDate:Date = null, capitalizeFirstLetter:Boolean = false):String
			var relativeDate:String;
			var isFuture:Boolean = false;
			if (secondDate == null)
				secondDate = new Date();
			// the difference between the passed-in date and now, in seconds
			var secondsElapsed:Number = (secondDate.getTime() - firstDate.getTime()) / 1000;
			if (secondsElapsed < 0)
				isFuture = true;
				secondsElapsed = Math.abs(secondsElapsed);
				case secondsElapsed < SECONDS_PER_MINUTE:
					relativeDate = "just now";
				case secondsElapsed < SECONDS_PER_TWO_MINUTES:
					relativeDate = "1 minute " + ((isFuture) ? "from now" : "ago");
				case secondsElapsed < SECONDS_PER_HOUR:
					relativeDate = int(secondsElapsed / SECONDS_PER_MINUTE) + " minutes " + ((isFuture) ? "from now" : "ago");
				case secondsElapsed < SECONDS_PER_TWO_HOURS:
					relativeDate = "about an hour " + ((isFuture) ? "from now" : "ago");
				case secondsElapsed < SECONDS_PER_DAY:
					relativeDate = int(secondsElapsed / SECONDS_PER_HOUR) + " hours " + ((isFuture) ? "from now" : "ago");
				case secondsElapsed < SECONDS_PER_TWO_DAYS:
					relativeDate = ((isFuture) ? "tomorrow" : "yesterday") + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase();
				case secondsElapsed < SECONDS_PER_THREE_DAYS:
					relativeDate = DateUtil.getFullDayName(firstDate) + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase();
					relativeDate = DateUtil.getFullMonthName(firstDate) + " " + firstDate.getDate() + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase()
			return ((capitalizeFirstLetter) ? relativeDate.substring(0, 1).toUpperCase() + relativeDate.substring(1, relativeDate.length) : relativeDate);
		 * @private
		private static function getMinutesString(date:Date):String
			return ((date.minutes < 10) ? "0" : "") + date.minutes;

Hopefully, this can help someone out there looking to do the same! Also, see the code in my GitHub repo!

Until next time, happy coding!


*Note: Shout-out to Joel Hooks for creating and sharing his awesome date-picker component!

ActionScript Puzzler – The Joy of Millisecs

Note: This is the same puzzler that was featured in the March issue of the Adobe Edge newsletter!

It’s about that time again…time for another Puzzler! I’ve written a few before, in a couple of languages too, but this will be my first in ActionScript! I know I have a lot of Flash readers, so hopefully this will be extra ‘puzzling’ for you (see what I did there?). For those that don’t know what a Puzzler is, it is essentially a short problem used to demonstrate special cases or “features” of a particular language. Here is the format:

  1. Code – I introduce the code
  2. Question – I pose a multiple-choice question and you guess what the outcome is…think hard!
  3. Walkthrough – I walk through a reasonable explanation
  4. Answer – I tell you the real outcome (it might surprise you), and explain why
  5. Moral – How can we avoid making mistakes like this in our own code

Now that we all know what a Puzzler is, here is a simple ActionScript Puzzler:


// declare key dates
var now:Date = new Date();
var birthday:Date = new Date(1940, 06, 27); // Bugs Bunny’s birthday!
// save them as milliseconds since epoch
var nowInMs:int = now.getTime();
var birthdayInMs:int = birthday.getTime();
// get the difference to calculate Bugs’ age in milliseconds
var millisecondsElapsed:int = nowInMs - birthdayInMs;
// sanity check
if (millisecondsElapsed == now.getTime() - birthday.getTime())
	trace("What’s up, Doc?");

What does this print?

  1. Nothing
  2. “What’s up, Doc?”
  3. Throws an exception
  4. None of the above


Alright, it looks like we are just trying to compute Bugs Bunny’s age in milliseconds, from the time he was “born” until now. First, we create the key dates. We have now initialized to the current date (as in the date this program is executed), and birthday initialized to Bug Bunny’s birthday. We then go and save those times as milliseconds since epoch so that we can easily do some date math with these two dates. Next, we calculate the difference of Bugs’ birthday (in ms) from now (also in ms) which should give us the total milliseconds elapsed since he was born. Finally, we do a sanity check. In the sanity check, we essentially duplicate the math we’ve done previously: calculate the difference from Bugs’ birthday until now, in milliseconds. This should obviously be true, and so we trace “What’s up, Doc?” to the debug console.



















The answer is a – nothing! How does this happen? Well, we must be skipping over the trace statement. That would only occur if the sanity check fails. But the sanity check does exactly what is done earlier on in the code…almost! The key error in this code is that there is an implicit narrowing type-cast! Where is it? Let’s take a look at the description of the Date class in the ActionScript 3 LiveDocs. In the documentation for the Date.getTime() method, we get the following function prototype:

  Method Defined By
Returns the number of milliseconds since midnight January 1, 1970, universal time, for a Date object.

Date.getTime() returns a Number! And we are storing that number in an int. In ActionScript, a Number uses the IEEE-754 double-precision floating-point specification, and therefore can use 53 bits to represent integer values. Comparing this to only 32 bits used by int and uint, we can see that Numbers can be used to represent values well beyond the range of the int and uint data types. Because of this implicit type-cast, our millisecond time gets narrowed and loses precision! Now, knowing this, it is easy to see why our sanity check fails. Our int variable millisecondsElapsed does not, in fact, store the total milliseconds elapsed since Bug Bunny was born, but rather, it stores the total milliseconds elapsed since he was born, truncated to 32 bits. Therefore, the sanity check fails, the if-statement falls through, and the trace statement never gets executed.


Although in some other languages, implicit narrowing type-casts cause warnings or even compilation errors, in ActionScript, they do not. So, whenever you are storing or working with numbers, be aware of the size of the numbers as well as the data-types floating around. Implicit casts do occur (and often, in any language), but implicit narrowing casts will go unnoticed by the compiler, and likely by you as well…until now :)

That’s it for this Puzzler! Hope you enjoyed! Happy coding!


Charles (source code)