Monday, September 24, 2012

utm, no escape and irregular expressions


If you're doing work online and hang around marketing people enough, at some point "utm" might enter your world. Your landing pages will get hit with URL parameters like

utm_source=google&utm_medium=cpc&utm_term=some%25252Bgreat%25252Bkeywords&utm_campaign=Program

Beautiful, huh? ("UTM" stands for "Urchin Traffic Monitor", as Urchin was an early Google purchase and is at the core of their marketing tools.)

We were trying to use the utm_term variable, grabbing the keywords that triggered our ad (that the user then clicked) to appear on a web search. We wanted to parse the keywords to plug into our own local search engine.

I was aware aware of the %2B encoding... that's the hex code for a plus, and a plus is used to represent a space character, since URLs aren't supposed to have spaces. The double encoding (space to plus to hex) seemed a bit of overkill, but whatever...

But it wasn't enough! Searches were failing and it wasn't clear why... using our log browsing tool "Splunk" (what a name!) I grabbed log data to get the actual URLs, and found they our primitive "replace %2B with space" routine wasn't cutting it, because of beauties like "%252B" and even "%25252b" showing up. %25 is the code for the percent sign itself. So these guys weren't just doing double encoding, but triple and quadruple encoding!  Yeesh. (Meme: "Yo Dawg, we heard you like encoding, so we encoded your encoding so you can escape while you escape!")

I'm not sure if there's a handy library that would more properly do the un-escaping, but a bit of playing with javascript and actual data leads me to believe this regex should do the trick:

function removeDoubleEncodedSpaces(val){
return val.replace(/\%(25)*2b/gi," ");
}
So the pattern was a literal percent sign, 0 or more "25"s, then ending with a literal "2b", and I wanted to replace all of those with space, and do it in a case insensitive way. (Sometimes being an old Perl geek has its advantages.)

UPDATE: a coworker pointed out I could use decodeURIComponent(), a javascript built in. But I'd have to apply it 3 or 4 times in this case... I'm not sure if there's a while loop that would make sure all the encoding was taken care of.

Thursday, September 20, 2012

more html5 sound toys and games goodness

Last night I gave a brief presentation about my lowLag.js audio library at the Boston HTML5 Game Dev Meetup. I was able to show off the project's playground page with its new drum machine mini-app:

I got some nice feedback about the project from people. Brian Shim mentioned a trick of setting up a mic and getting a sound clip that has both the sound of the tap and the actual sound replay, so you can quantify the lag more precisely.

Admittedly, my humble project was a bit eclipsed by Tristan Jehan's talk about The Echo Nest. To brutally over simplify, part of their core is similar to what Pandora and the Musical Genome project do, but they use big data to get there, and when combined with an open API (and a number of music hackathons) they get some amazing stuff done... not just charting the relations between artists and songs in a metadata kind of way, but chopping and splicing and analyzing the song files themselves. Here were some of the projects mentioned:
Some of the others tools using the API seem to not be (or no longer online), like
Finally, we witnessed the launch of the Brainworth Kickstarter. The idea is a platform that teaches html5 game programming by playing games. It looks to have crazy fun social elements and general flexibility.

Monday, September 3, 2012

empower everyone: a new old paradigm for social software

Ok, enough of the in-the-trenches HTML5 audio gridning: lets talk about something a bit more abstract.

Recently I noticed a parallel in the solutions to problems faced by Google in their Hangouts app and by Apple with their AppleTV AirPlay photo sharing.

Google Hangouts is a group voice chat. That social technology often has a problem where one's person microphone is causing a problem for everyone else: either delay-echoing the main conversation, or making feedback, or having an on-device microphone amplify the typing sound of that person as they multitask during the chat, or some kind of intrusive background noise. Those sounds can be very disruptive to the group. But with Google Hangouts, everyone is empowered to mute anyone else. And they don't just mute that person for themselves, they mute that person for everyone!

If it ended there, a typical engineer might thing "That's censorship! How can that work? We should designate a conversation leader and only that person has such power!" But Google added two additional features that make it make sense: a public announcement of the muting is made on the Google Hangouts screen. ("Fred muted Barnie", for example). And a person who is muted is always empowered to unmute themselves. So while the potential for mute/unmute wars certainly exists, overall the experience makes sense.

I saw a similar problem and solution with AppleTV's AirPlay feature. We were over at our friend Sam's  house during our Labor Day vacation, and each of us had some pictures of the past few days on our iPhones that we'd like to show each other. The UI for this was breath-takingly simple in its "it just works" factor: in the iPhone photo app, hit the sharing button and then "AppleTV". And the rule is "last one in wins"; anyone can override what other people are looking at.  The stakes are pretty low, and anyone can replace what anyone else has beamed to the screen. Simplicity trumps authority!

But of course, there's nothing new under the sun, and this idea of empowering everyone has been around for a while. Here's an excerpt from Steven Levy's Hackers, Heroes of the Computer Revolution   about the ITS (Incompatible Time-Sharing System), an OS for the PDP-6:
ITS, in contrast [to Multics where hackers would prove their mettle by crashing the robust system], had a command whose specific function was crashing the system. All you had to do was type KILL SYSTEM, and the PDP-6 would grind to a halt. The idea was to take all the fun away from crashing the system by making it trivial to do that. On rare occasions, some loser would look at the available commands and say, "Wonder what KILL does?" and bring the system down, but by and large ITS proveed that the best security was no security it all.
Now it's not clear that this type of communal empowerment is always appropriate... like Alfred Pennyworth says in The Dark Knight, "some men just want to watch the world burn" and so the community needs to be able to reject such griefers with the scorn they deserve.  Still, it's a powerful idea to keep in mind for community UX.

Thursday, August 30, 2012

sounds good: hacking through the jungle of html5 audio

Audio is a more difficult thing for computers to get right. Even the humble(?) task of providing low-latency (i.e. quick response) audio clip playback is a challenge for some systems (I saw this first with using the minim library in Processing). And I'm talking basic audio, not heavily processed stuff, or even strictly "real time"-- enough so that in a game you can easily tell what onscreen event triggered the noise, not that you can base a "Guitar Hero" clone off of it.

tl;dr: Introducing lowLag.js Sound: a simple wrapper for low-latency, high-compatibility, html5-friendly audio. 

It gives you three comands: init(), load(), and play(), and provides nice speedy sound across most browsers. See its official homepage or its github page for more.

The background:

I asked my buddy Darius Kazemi if had a recommendation- he helped Subatomic Studios make an HTML5 port of their iOS game Fieldrunners (You might want to his New Game 2011 Post Mortem on the porting process) and his quick answer was
Soundmanager2 is the standard. Definitely use that.
SoundManager 2's turned out to be a decent recommendation, thanks in part to the online documentation: even though the primary download seems to be a whole source tree, you just need to pluck a few files out for use, as outlined on the template example page (the API and Demo code page was also helpful.)

So SoundManager2 (with its two-fisted Flash-object with html5 fallback) worked on most browsers, it had much lag, especially on Chrome. I mentioned this to Darius and he told me that on chrome he usually goes straight to the Webkit Audio API, and sent me his example page.

So now I had 3 different techniques for audio. I made 3 test pages: one for the <audio> tag cloning technique, one using soundmanager2, and one using webkitAudio. Each page has a high pluck sound button, a low pluck sound button, and a button to play both at once.

Anyway, the webpage shows the detailed work I did in finding out what techniques worked best in which browsers, and then how I wrapped those in a single easy-to-use wrapper js object. I know I'm going to use it on upcoming game projects.

Enjoy!

Thursday, August 16, 2012

simple labeled percentage bars in CSS

So at work the spec called for a percentage complete bar... one of my coworkers came up with something like the following (I reinvented the CSS, but the idea was his)

The css and HTML is a bit more fiddly than I like, but I've seen worse:

<style>
.percentage {
width:200px;
height:20px;
background-color:#CCCCCC;
text-align:center;
color:black;
position:relative;
font-family:tahoma,arial,sans-serif;
}
.percentage .bar{
position:absolute;
top:0px;
left:0px;
overflow:hidden;
width:100px;
}
.percentage .inner{
width:200px;
background-color:#000055;
color:white;
}
</style>

<div class="percentage">
<span class="val">50%</span>
<div class="bar">
<div class="inner"><span class="val">50%</span></div>
</div>
</div>


The basic idea is to have 3 nested divs. The outer div has a fixed width and the percentage, with a dark text color. The middle div is set to the desired visible width of the bar (multiplying the current percent value times the width of the outer bar, divided by 100) It has its overflow set to hidden, so that the final inner div (set to the full width of the outer bar) displays its darker shade, lighter text for only as far as it needs to-- then the duplicate text of the outermost div shows behind it. The innermost bar obviously doesn't have to be a set color, it can be a repeating background image or whatever.

I then added a demonstration of an animation technique. As far as I know, there's no easy way of knowing how far along a jQuery animation is (for updating the % text) so I used setTimeout with a function that incremented the value and then called itself (in something a bit like tail recursion) until finally the displayed value was the same as the goal value.

(Wrapping this as a jQuery object or applying it to a specific need is left as an exercise for the reader...)

So that was the UI side of things. On the UX side, I thought we had a problem. At work we are introducing a point-and-level system and were using the progress bar to to show the user's current level along with how the points total and how long until the next level. The display for that was something like this:
 Level 3 was achieved at 700 points, and at that point I had 850. Take a look and answer this question: about how many points do I need to be at Level 4? 




To me it looks like Level 4 is around 2500 or so -- the bar indicates that I'm only 1/3 of the way there. But that's not the case. Level 4 is 1200 points, and what the bar is showing me is that I'm about 1/3 of the way up from when I hit Level 3.

So, I found that counter-intuitive, and unlike how other point systems (like the unlock system in the game Just Cause 2) do things. Instead, I thought this display was more clear:

Here, it looks like I am most of the way to the next milestone, which is in fact the case.

An alternate display might be something like:

I think this does a clearer job than the first example of showing Level 3 as a baseline, and that Level 4 as what is being worked to.

The jury is still out on which display we'll use. It deserves some user testing, but I'm pretty sure either of the alternatives are a better form of data visualization than the original setup.

Friday, August 10, 2012

js singleton boilerdish

(Improved version as of early 2014)

This is mostly just for future reference for myself (hence the cutesy name "boilerdish" that I can Google on...)

There are several patterns for making JS objects. One of my favorites is:

var someObject = new function(){
    this.someVariable = undefined;

    this.init = function(){
        alert("started up");
        someObject.someVariable = true; //don't rely on meaning of "this" too much!
    };
}

$(document).ready(someObject.init);

(Also sometimes I like to throw in the diagnostic logging stuff I wrote about here)

Caveats: this pattern doesn't provide much "privacy" for members, so it's not good for defensive coding. It's also kind of assuming a "singleton" use, but I find that pretty common and useful. (Also, given how frustrating "it depends on what this 'this' is this time" can be, the fall back of being able to refer to  "someObject.someVariable" out of the global space, rather than relying on delegates so that something like "this.someVariable" can work, is extremely helpful...) It does mean that there can just be a single entry in the generic Window namespace, which is always a plus.

Monday, August 6, 2012

processing.js porting gotchas

I've been porting entries from my Java Advent Calendars (both the 2009 and 2011 editions) into HTML5, via the wonder that is Processing.js. The original Processing (a Java based IDE and API, geared at students and artists) is amazing enough -- I really credit it with enabling me to make some really fun stuff in folks' browsers (not to mention effortlessly generated native Windows and Mac apps) but it feels like applets are kind of on their way out. So Processing.js allowing what is basically straight Java code to be run as Javascript (using the Canvas object) is super amazing. I don't know what black magic preprocessing they do to get 90% of my Java classes to work in a Javascript context, but it's great work, and less problematic than I thought.

Still, there are lots of gotchas, so here's my list of things to look out for, as determined by my personal experience. (Which involved some Processing code against the older version of Java that didn't use typed collections, and might not be using the latest and greatest release of Processing.js.)

Environment Gotchas

  • Speed. Some of my code that runs fine as an applet runs a bit slow in the browser, or at least with  some browsers javascript engines. I haven't yet isolated what operations slow things the most, but it seems like the line drawing isn't as quick.
  • Error messages. When you're coding up new stuff, the error messages can be a bit opaque, and generally don't have the line number of the original .pjs file. 
  • Chrome and running things locally. Chrome tends to balk at running code loaded locally from the file system. (Might be a good excuse for that Python webserver trick I mentioned earlier.)
  • 3Dness. One of my first attempts at porting a simple 3D app ended in failure, I haven't researched if there's an easy way around this.
Coding Gotchas
Most of the coding problems I've run into involve collections.
  • Collections & Inheritance. I had a big problem with this early-on, with an overly ambitious engine project I was doing for the Boston HTML5 Gamejam. It used a lot of object subclassing, and it seems like items in a heterogeneous collection of subclasses weren't being cast to quite the right types when it came time to call function names that they had in common.
  • The .removeAll() function for Collections is late to the party. I'm not sure if later version of the library fix this, but it was a known issue.
  • HashSet is not implemented. I liked to use HashSets for collections where order didn't matter but I wanted to be able to remove specific member items efficiently. ArrayList is a pretty good substitute.
  • In the bad old days of Java, before it's implementation of "foreach", you had to use iterators, and the best way to remove an item if you were in the loop itself was through the Iterator.remove() method (which removes it from the container the iterator is based off of.) .remove on the Processing.js iterator doesn't seem to propagate up to the main collection. (Combined with the .removeAll() lack, this was a little annoying.)
  • Apparently in Processing,
    ArrayList<SomeClass>things = new ArrayList<SomeClass>();
    is fine, but Processing.js gets confused, and wants spaces before the collection name. (For a while this led be to be unfairly pessimistic about the porting from Java, because the error message wasn't clear, and I was writing lines like that without spaces all over the place.)
So despite this list, in practice I've been increasingly impressed with what Processing.js can do. It's an awesome set of training wheels for people looking to go from Java to Javascript, and sometimes I wonder if it might not be a solid tool in its own right, as crazily ambitious as "run Java classes in Javascript" seems.

Followup: one other class of error involve java being strict about its types, but js being loose:

 int spotToYcoord(int s){
     return s / 3;
   }
This returns int values only in Java, but the equivalent of floats in javascript. (In this case the fix was to explicitly return floor(s/3) instead.