All posts by patorjk

Plotting and Analyzing US Baby Naming Data

Photo By mahalie

I’ve created a new tool that allows you to query US baby naming data from the past 130 years and play around with it on an interactive chart. I got the idea after stumbling upon the data at the US Social Security website.

To cut to the chase, below you can see some interesting effects of our culture on naming trends.

  • Star Wars – George Lucas created the names “Anakin” and “Padme”, and he had a big impact on the number of babies given the name “Han”, “Leia” and “Luke”. I didn’t include Luke on the chart because it dwarfed the others so much, but between 1880 and 1977, 18,027 babies were named Luke, between 1977 and now, 176,125 babies were given that name.
  • Hermione – Apparently Hermione is a real name, though the 478 babies given the name since 2000 were probably due to the recent popularity in the Harry Potter series.
  • US Presidents – My friend Ben found this one. Back in the early twentieth century, who got elected president had a big impact on what people named their babies.
  • Reagan and Kennedy – I don’t want to get too political, and I’m just talking out of my ass here, but I wonder if the idealizing of past political heroes (from different sides of the aisle) has led to the recent surge in these names.
  • Ninja Turtles – The Ninja Turtle craze of the late-80’s / early 90’s seems to have caused a small impact on naming trends in that time period.
  • Paris – Paris Hilton’s sex tape leaked onto the internet in 2003 and became a big news story. For some reason this inspired hundreds of people to name their kid after her.
  • Osama – The frequency of people naming their kid “Osama” actually increased after the 1998 embassy bombings, but I’m guessing after 9-11, people realized naming their kid after after the world’s most wanted terrorist was probably not a good idea.
  • Miley – In 2005, 26 babies were born with the name “Miley”. In March of 2006, Hannah Montana debuted with star Miley Cyrus on the Disney Channel. That year the name started to sky rocket in popularity, and peaked in popularity in 2008 when 2,643 babies were given the name.
  • Selena – In 1995, this name shot up in popularity by 400%, with 3,839 babies given the name “Selena”. This was most likely was caused by the 1995 death of latin super star “Selena Quintanilla-Pérez“. Interestingly, Selena Gomez has not had the effect on “Selena” that Miley Cyrus has had with “Miley”.
  • Carson – This name had been slowly increasing in popularity, but it started to skyrocket in 1998, which coincidentally was the year MTV debuted its mega hit TV show TRL, with host Carson Daily. The name has maintained its popularity, so its probably not all due to Daily, but since TRL was a young person’s show, and not many notable people are named Carson, he probably had some effect in getting the ball rolling.
  • Shirley – Shirley Temple shot to super stardom in 1934 with Bright Eyes, and so did the use of her name for new borns.
  • Britney – Britney Spears dropped “…Baby One More Time” in 1999 and had a big impact on the “Britney” (interestingly, the version spelled “Brittany” stayed in steep decline during this time period).

These were all found by just trying out different names and looking at the time period for when the names peaked or dropped in popularity.

Chart Library and Modifications

For those of you who are curious, I used Martin Kleppmann’s PlotKit repo as a starting place for the chart (that repo is a heavily modified version of Plotkit with lots of new features and fixes). I then modified it to add in some additional features and minor bug fixes, including the mouse interaction stuff. I’ll probably submit my changes back to him at some point, though right now I feel like I kind of hacked stuff into it, so I’ll probably wait until I polish it up and the changes are field tested more. If you have any trouble with the chart please let me know.

The mouse interaction stuff was done by creating a separate canvas element and having it overlay the chart. The dynamic dots you see are then drawn on this canvas. This is done because re-drawing the whole chart is time consuming. The one exception to this is IE7 (and possibly IE8), for which I couldn’t get the overlay to work. So for those browsers, the whole chart re-drawn when it changes. So you’ll notice if you use IE7 that mouse interaction isn’t smooth, while if you use Chrome, FireFox, or IE9, things should be pretty smooth.

“The Book of CSS3” Book Review

The Book of CSS3

I had been wanting to learn more about CSS3, so when offered a review copy of The Book of CSS3, I accepted knowing that at the minimum, I’d at least get exposure to a bunch of cool new design features. Luckily, the book itself is well written and proves to be a great guide to what’s available now, and to what’s coming soon.

The book is written for web developers who are familar with CSS and who may have played around with some of the new CSS3 features, like rounded corners and drop shadows, but who are looking to get a fuller understanding of what it is and what they can do with it. After explaining a bit about what CSS3 is, remarking on its modular nature (the spec is broken into modules so that browsers can implement individual modules without having to implement the whole CSS3 spec right way) and giving a short write up of its troubled history (work on the CSS3 spec originally started way back in 1998), the book launches into chapters on individual CSS3 topics – you can see the full table of contents here.

The flow of the book from one topic to the next is pretty good, but with the exception of chapters dealing with animation and transformation, most of the chapters can pretty much be read in any order. However, the earlier chapters cover topics that are more widely accessible, stable, and cross-browser than the later chapters, so reading the book start to finish is probably advantageous. The structure of each chapter is very similar, with the author discussing a little about the topic and then leading you through various sections where features are described and showed off with examples. Cross-browser techniques (where relevant) and compatibly are also mentioned.

One of the early topics that really piqued my interest was Web Fonts. With Web Fonts you can use any font you want, even a crazy hand written one, and users will see it when viewing your webpage. The author even provides some cool links to some CSS3 font resources like Google Web Fonts, which makes it really easy for you to include and use fonts in a cross-browser manner.

Another topic that I enjoyed was “Transitions and Animations”. Animations let you move and change elements during a given time period. Unfortunely for us, the Animations module, at least for now, is only implemented in Webkit browsers (Chrome and Safari). However, Transitions are currently available in all of the major browsers except IE. A “Transition” is an animation that happens between two different states. They allow you to give a smooth feel to certain style changes. For example, say you wanted to change the color of a link, but you wanted the change to come in gradually. You could do that like so:


Example test: Mouse over this link!

As you can see, the hover pseudo-class changes the link to color to red, but since we’ve setup a transition for the color property, the link transitions from black to red over the period of 1 second, instead of abruptly changing to red. This effect also applies to other properties, and is especially neat when changing a div’s position or size.

Near the end of the book some yet-to-be implemented features are discussed. Chief among them is the “Template Layout Module”, which would allow you to lay out items on a page in way that is similar to a grid, but a in fashion that is little more intuitive. The Template Layout Module is made even more interesting by the fact that even though it is currently not implemented in any browser, you can still use it by using a JavaScript library written by Alexis Deveria.

I feel like I learned a lot from this book and that it not only contained a lot of useful information, but that the information was presented well. The only draw back to reading this kind of book is that CSS3 is still in flux right now and certain features will change as things are ironed out, however, much of what’s talked about is reasonably stable, and knowing about what’s coming will probably give you a better footing for the features when they finally arrive. If you’re looking to learn more about CSS3, this is definitely a book to look into.

CSS3 Card Flip Animation Trick

I’ve been playing around with some of CSS3’s new animation features. For an app I’m writing, my wife suggested I jazz things up a bit by having an image look like its flipping over, and I realized that with CSS3, I could actually do that. To demonstrate what I’m talking about, in the latest version of Chrome, click one of the playing card images below*.

The neat thing is that the effect is ridiculously simple. The one catch is that you can’t change the background-image property of a div during an animation. To get around this, you just need to use an image that contains all of the pictures you want to display. When the image is out of view (e.g., roated at 90 degrees or 270 degrees on the Y axis), you change the background-position. That way, when the image rotates back into view, it’s displaying a different picture.

It’s pretty simple, but kind of amusing. Below is some example code you can use for your own animations. The card image used in this example can be seen here, and the full set of cards can be obtained here.

CSS:

@-webkit-keyframes card1Flip {
    0% {-webkit-transform: rotateY(0deg);}
    24% {background-position-y:0px;}
    25% {background-position-y:204px;}
    50% { -webkit-transform: rotateY(180deg);}
    75% {background-position-y:204px;}
    76% {background-position-y:0px;}  
    100% {-webkit-transform: rotateY(360deg);}
}
.card1FlipProps {
    -webkit-animation-name: card1Flip;
    -webkit-animation-duration: 2000ms;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: 1;	
    -webkit-animation-direction: normal;
    -webkit-animation-delay: 0;
}
#card1 {
    background-image:url('/images/blog-2011/card_map.png');
    width:150px;
    height:204px;
}

JavaScript:

var elm;
elm = document.getElementById("card1");
elm.addEventListener("webkitAnimationEnd", function(){
    if (this.classList) {
        this.classList.remove('card1FlipProps');
    }
}, false);
elm.addEventListener("click", function() {
    if (this.classList) {
        this.classList.add('card1FlipProps');
    }
}, false);

HTML:

<div id="card1"></div>

* Important Notes: Unfortunately, the CSS3 animation module isn’t implemented in most browsers right now, so the above example will only work in the latest version of Chrome. Safari also uses Webkit as its layout engine, however, when I tested this example in the latest version of Safari (5.0.5), it didn’t work correctly. Some digging around showed that my version of Safari was using Webkit version 533.21.1, and my version of Chrome was using Webkit version 534.30.

Since the animation module is still being worked on right now, this technique, and animations in general, should probably be used cautiously and for effects that aren’t that important.

Extendible BBCode Parser in JavaScript

Photo By Dean Terry

I decided to try my hand at implementing a BBCode parser in JavaScript. You can play around with it online here, and download the source here.

I had looked around a little bit and noticed that the existing JavaScript BBCode parsers had at least a few of the following issues:

  • They didn’t report errors on misaligned tags (e.g., [b][u]test[/b][/u]).
  • They couldn’t handle tags of the same type that were nested within each other (e.g., [color=red]red[color=blue]blue[/color]red again[/color]). This happens because their regex will look for the first closing tag it can find.
  • They couldn’t handle BBCode’s list format (e.g., [list][*]item 1[*]item 2[/list]).
  • They didn’t report errors on incorrect parent-child relationships (e.g., [list][td]item 1?[/td][/list]).
  • They weren’t easily extendible.

I naively thought it’d be easy to quickly whip up a parser, and at first it was. Most BBCode tags can be implemented with a simple find and replace. However, I quickly ran into the issues of dealing with nested tags of the same type, the noparse tag, and the list tag’s annoying [*] tag (which doesn’t have a closing tag). Luckily, I came across a neat blog post on finding nested patterns in JavaScript, which came in handy for isolating tag pairs, from the inner-most on up. Taking the idea from that post, one can do something like this to process the inner tags first and avoid the nested tag problem:

var str = "[list][list]test[/list][/list]",
    re = /\[([^\]]*?)\](.*?)\[\/\1\]/gi;
while (str !== (str = str.replace(re, function(strMatch, subM1, subM2) {
    return "" + subM2 + "";
})));
// str = "test"

That idea works well, though you can’t implement a noparse tag if you process the inner-most tags first. So I decided to pre-process the BBCode with something similar to the idea above and add in nested-depth information to each open and close tag. Once all of the tags had that, I could parse the processed code with a regex that could easily match-up the correct open and close tags.

To get around the issue of the [*] tag having no closing tag, I wrote code that inserted [/*] tags where they were supposed to go during the pre-processing period. I wont go into the algorithm here, but you can dig into the code if you’re interested.

Also, I should note that the fact that JavaScript allows you to use a function as the second parameter to the replace method makes processing the tags really easy. Once you match a set of tags, you can recursively call the parse function on that tag’s contents from inside of the function you passed to replace.

Using the parser

To use the use the parser, you’d simply include xbbcode.js and xbbcode.css files somewhere on your page (which are contained in the zip file linked above), and then call the XBBCODE object from somewhere in your JavaScript:

var result = XBBCODE.process({
    text: "Some bbcode to process here",
    removeMisalignedTags: false,
    addInLineBreaks: false
});
console.log("Errors: " + result.error);
console.dir(result.errorQueue);
console.log(result.html);// the HTML form of your BBCode

Adding new tags

To add a new tag to your BBCode, add properties to the “tags” object inside of the XBBCODE object. For example, say you wanted to add a tag called [googleit] which would change its contents into a link of its google search results. You’d implement that by adding this to the tags object:

"googleit": {
    openTag: function(params,content) {
        var website = "\"http://www.google.com/#q=" + content + '"';
        return '<a href=' + website + '>';
    },
    closeTag: function(params,content) {
        return '</a>';
    }
}

Then you could have BBCode like this: “[googleit]ta-da![/googleit]” which would be transformed into this: “<a href=”http://www.google.com/#q=ta-da!”>ta-da!</a>”

If you have any suggestions or find any bugs let me know.

“HTML5: Up and Running” Book Review

HTML5: Up and Running

I’ve read a decent number of articles on what will be new in HTML5. I’ve read up on the canvas element, localStorage, web workers, and a couple of the other elements one can use when creating Chrome Web Browser Extensions (for when I created my Typing Speed Monitor and Image Definitions for Dictionaries extensions).

However, I hadn’t really sat down and taken the time to thoroughly go through all the goodies that are planned for/coming with HTML5. So when my office mate showed me a huge pile of books he had just purchased, I saw the one titled HTML5: Up and Runningand got kind of curious. After flipping through it, I found out that its also available online for free under the title of Dive into HTML5, but I ended up ordering my own copy since I prefer to read the paper editions. However, a good number of resources are linked to, so a digital version of the book is somewhat advantageous.

Anyway, the book starts off with some history on how HTML developed. It goes through an old thread in a 1993 W3C mailing list archive, where participants were discussing the creation of image tag. Essentially no one could really agree on how it should be setup (Should it be img, icon or include? Should its properties be src or href?), and ultimately an author of Mosaic (an early web browser) decided to just use what he had initially proposed and shipped his browser with a working img tag. The point of the story is to show you that HTML isn’t this carefully crafted language, it’s based on discussion, but many of its features came about simply because a popular web browser decided to stand behind them.

The next chapter discusses how you as a developer can use the new HTML5 tags in your web pages today, and still have your site be backward compatible with older browsers. It uses a JavaScript technique to do this, however, there are a couple of ways to use the new tags and be backwards compatible, some of which you can read about here.

The rest of the book focuses on giving introductions to the various new features you’ll have access to in HTML5, specifically: the canvas element, the video tag, the geolocation API, the localStorage element, how to setup your site for offline storage, all the new form elements, and how microdata works. These discussions are all pretty good, though I especially liked the chapter on the video tag. I didn’t really know much about the different video formats going into the chapter, so it was nice to have a high level discussion on how videos are encoded. It was also interesting to have the author touch on the licensing issues of H.264 video. After reading about all the fees involved, especially those possibly coming after Dec. 31, 2015, it seems like it’d be a bad format to use as a standard.

Overall I liked the book and would recommend checking it out if you’re curious about using and playing around with the currently available features of HTML5.

Programming Trivia App

Photo By Mirko Junge

This has been on my computer for months and while it’s not completely finished, I wanted get a version up since I’m starting work on it again, so I present Programming Trivia Questions.

It’s born out of the basic idea I had for my old Programming Quiz App, which I released last year. Shortly after creating that app I realized that creating a list of good quiz questions was actually kind of hard, and expecting someone to write a full, non-goofy quiz was probably too much. However, coming up with a question or two is usually pretty easy. So I figured I’d change the app to be like a question database where questions were tagged with certain keywords, and the user could just select categories and get questions on those categories.

I’m not at that point yet, but I have a working demo with 20 questions. The next step will be to connect it up to a database (right now it’s all client side) and then to allow users to submit questions. Anyway, I figured 20 random programming-themed questions would be mildly entertaining so I figured I’d share it with you all. If you have any suggestions let me know.

Oh, one last note, my favorite JS graphing library, Plotkit, doesn’t seem like its being updated anymore (it’s a fantastic library, but the last update was in 2006). I made some modifications to it for this app (I changed how the colorscheme mechanism worked for bar charts if just one dataset was used) and am debating forking that library or using another one. If anyone has any graphing library suggestions let me know.

AAC Police Brief Analyzer

Photo By dooq

I’ve created a new Facebook app which I call Anne Arundel County Police Brief Analyzer. I noticed my local police department had a Facebook page and that they posted their police briefs to this page. The briefs all followed the same format, so I decided to see if I could parse them to grab out some statistics.

The app is pretty simple, and right now all its doing is counting the number of times the various cities in the county are mentioned in the briefing sub-headings. Basically it answers the question: “Which cities show up in the police briefs the most?” This app would probably be more helpful with population data, however, it was mostly just done as an experiment, so I probably wont go any further with it. However, I figured I’d post it up since I found it kind of interesting.

The only hitch to creating the app was that you can only grab the 25 notes from Facebook per request, at least with their JavaScript SDK. To grab more notes, you have change the “offset” parameter (also see batch requests). Example:

FB.api("/aacopd/notes", {offset: 175, limit:25}, function(response) {
    console.dir(response.data);
});

patrickgillespie.com Update

I’ve updated the cloud code at patrickgillespie.com to now use a canvas element in browsers that support it. This leads to a much smoother appearance in Chrome and a slightly better appearance in FireFox. I tried using excanvas for the IE version, but it was too choppy for what I was doing, so the IE version still uses divs.

JavaScript Parallax Scrolling Experiment

Parallax Clouds at patrickgillespie.com

There’s a neat CSS technique called “Horizontal Parallax Scrolling”, where background images will move at different horizontal speeds when the window is resized (example). It’s done by positioning several divs on top of each other and having their background-position property set to different offsets. You can read a great CSS tutorial on it here.

I thought it was kind of cool and decided to see if I could come up with a way of doing “Vertical Parallax Scrolling”. There are a lot of ways one could approach this, but I decided to go with fixed positioned divs that would move when the user scrolled the page up and down. These divs would be attached to the background and a content div would sit on top of the background which would have a z-index higher than any of these fixed positioned divs. All content for the page would go inside of this content div. I figured this approach would suit me well since I was thinking of creating something where there’d be lots of floating objects in the background.

After playing around a bit I came up with something that worked reasonably well in IE7+, Firefox and Safari, and ok-ish in Chrome. The effect was neat and 3D-ish, so I decided to use it at patrickgillespie.com. It replaces the silly CD cover experiment I’d previously hosted there. The effect is still not as smooth as I’d like it, but I think for a really nice smoothness I’d probably have to use a canvas element instead of a bunch of divs. Anyway, if you’re interested, I’ve put together an example which you can download here.

Website Showdown!

Photo By fPat Murray

I’ve created a new web app that lets you pit two groups of websites against each other to see which group is more popular on Facebook. It’s called Website Showdown! and works by using the Facebook API to read the number of “Shares”, “Likes”, and “Comments” a particular URL has gotten on Facebook. Whichever group has the highest count, wins.

Also, when comparing URLs, the exact URL counts. “http://patorjk.com/” wont reference all of the times something from “patorjk.com” has been shared, only the number of times that particular URL has been shared. Trailing slashes (/) also seem to matter.

The data displayed in the app is read from Facebook’s link_stat table. I may end up adding other Social Media stats to the results, but I’ll wait to see if there’s any feedback on this app first.

The Facebook API is actually kind of fun. I’ve avoided it since I’d heard some bad things, but I had no issues with it (however, this is probably the most basic type of app one can create). I’ll probably tinker around with it some more, though as of late I’ve got a lot of unfinished projects on my plate.

Below you can see a screen cap of some results. If you find any bugs in the app please let me know.

Google vs Facebook

App URL: Website Showdown!

“JavaScript Patterns” Book Review

JavaScript Patterns

I went on my honeymoon recently and decided to pick up some reading for the plane ride*. The book JavaScript Patterns** piqued my interest after seeing it on this list of useful JavaScript books, so I decided to check it out.

The book’s aim is to provide useful techniques and abstractions (coding patterns), best practices, and approaches for implementing popular design patterns for the mid-level to advanced JavaScript developer. However, its main focus is on coding patterns. After introducing JavaScript and going over some basic concepts, the author launches into a chapter on best practices, which covers a grab bag of topics, everything from naming conventions to loop optimization to writing API docs. This chapter was actually where I first learned of YUIDoc and JSDoc, two great tools for generating API documentation for JavaScript code.

After that follow the chapters on coding patterns. The author goes over various subjects and explains techniques that will make you a better developer. Techniques like enforcing new when you define constructor function, the module pattern, self-defining functions, etc. Some of it you may already know, but it’s a good collection coding patterns.

The book finishes up with a chapter on implementing common design patterns in JavaScript (it covers: Singleton, Factory, Iterator, Decorator, Strategy, Facade, Proxy, Mediator, and Observer) and a chapter on working with the DOM. If your main interest is in learning design patterns, I’d probably recommend Pro JavaScript Design Patterns instead, since it’s main focus is design patterns and it devotes more time to explaining them and giving examples, however, if you’re already somewhat familiar with them and you have a decent understanding of how OOP works in JavaScript, than I would pick this book up instead as it cover more ground and is faster paced.

Overall I really enjoyed this book and learned a lot of useful tid bits from it. I’d recommend picking it up if you’re looking write better JavaScript code and to fine tune the techniques you know about JavaScript.

* The other books I read were Fahrenheit 451 (it was ok) and The Martian Chronicles (excellent book).
** Non-referral link, just so you all don’t think I’m trying to sell you books.