Skip to content

Recent Articles


Recreating a Logo in SVG (from a PNG)

This is the hdpi logo for, in PNG format:


It’s file size is only 3.83KB, which isn’t bad at all. And it looks crisp on hdpi screens. But I wanted to try recreating it in SVG anyway, mainly as a learning exercise.

Getting the basic outline of the letters was easy, given how blocky they are. I had Adobe Illustrator trace them and output the result as an SVG. This would be my starting point for hand-coding the rest.

First, I rounded off each point that Illustrator generated to integers. For such simple shapes, integers really just make it easier to ensure everything is lining up. A few lines ended up a pixel off from where I wanted them, but that was easy to correct. So this was my starting point:

starting shape

Read moreRead more


Web Page Optimization – Changes I Made for Page Loading Speed

It has been years since I optimized the page loading speed at GoToQuiz. At that time, image sprites and CSS/javascript minification were the state of the art. In the intervening years, though, further progress has been made. Of particular note is the “retirement” of older versions of Internet Explorer, and the emergence of CSS3 and HTML5, which allows developers the ability to further streamline their sites. So as I am in the process of revamping the UI, I’m taking advantage of the latest techniques to boost page loading speed. Be aware, this is nothing revolutionary–this blog post is simply an overview of which changes I’m making, and why.

Migrating pages over to HTML5 allows the markup to be more semantic while taking fewer bytes–a double win.  Using tags such as nav, section and article helps alleviate so-called “div-itis”, allowing cleaner markup and a smaller overall filesize.  HTML5 also follows the maxim of “convention over configuration”, letting you eliminate unnecessary attributes like type=”text/javascript” on script tags, for example.

The adoption of CSS3 has provided many possibilities for creating beautiful visual effects without using image files.  Here is an example: on an early iteration of the design of the various headings on GoToQuiz, I used this sprite combined with CSS to create the rounded color bar appearance.

Read moreRead more


Simple, Light-Weight Radio Button Replacement jQuery Plugin

I was looking for a jQuery plugin to replace the standard browser radio buttons with custom images, but I had a few requirements. 1) Tabbing and focus had to function correctly, and 2) the javascript had to be light-weight. After looking into some heavy plugins and some simple ones that didn’t handle tabbing/focus properly, I decided to roll my own.

Here’s the plugin code, with comments:

(function($) {
    // source:
    'use strict';

    //the plugin
    $.fn.niceRadio = function(options) {
        if (this.length !== 0) {
            //initialize settings & vars
            var settings = $.extend(
                {   baseClass:      'nr_base',
                    focusClass:     'nr_focus',
                    checkedClass:   'nr_checked'},
                $radios = this,
                $aset = $();

            $radios.each(function(i, el) {
                var $radio = $(el),
                    //create an anchor per radio that will be our radio replacement
                    $a = $('<a href="#" id="nr_a'+ i +'" data-nr-id="'+ i +'" class="'+
                            settings.baseClass +' nr_for_'+ $radio.attr('name') +
                            '" tabindex="-1"></a>');

                //give each radio a custom class with a counter (nr_r#) for easy lookup
                $radio.addClass('nr_r'+ i)
                    //store the counter value as data as well
                    .data('nrId', i)
                    //insert the anchor immediately after the radio
                    //hide the radio visually
                    .css({position: 'absolute', 'margin-left': -2999});

                //if radio was already checked, add the checked class to it's replacement
                if ($':checked'))

                //collect the set of anchors as they are created
                $aset = $aset.add($a);

            //when an anchor is clicked...
            $ {

                //$clicked is the anchor
                var $clicked = $(this),
                    //$checked is the radio to be checked
                    $checked = $('.nr_r'+ $'nrId'));

                //check it
                $checked.prop('checked', true)
                    //focus it
                    //trigger the change event on it

            //when a radio received focus, add the focus class to its replacement
            $radios.focus(function() {
                $('#nr_a'+ $(this).data('nrId')).addClass(settings.focusClass);
            //when a radio loses focus, remove the focus class from it's replacement
            .blur(function() {
                $('#nr_a'+ $(this).data('nrId')).removeClass(settings.focusClass);
            //when a radio is changed, call the changeEvent function
            .change(function() {

            return $radios;

        //called when a radio selection changes
        function changeEvent($radio) {
            //if $radio is checked...
            if ($radio.prop('checked')) {
                //remove checked class from any other anchor associated with
                //radios of the same name
                $('.nr_for_'+ $radio.attr('name')).removeClass(settings.checkedClass);
                //add checked class to this radio's replacement
                $('#nr_a'+ $'nrId')).addClass(settings.checkedClass);
                $('#nr_a'+ $'nrId')).removeClass(settings.checkedClass);


This requires some CSS rules, which might look like:

.nr_base		     { display: inline-block;
                       height: 16px;
                       width: 16px;
                       background: transparent url(radio_sprite.png) no-repeat 0 0;
                       vertical-align: middle; }
.nr_checked	         { background-position: -16px 0; }
.nr_focus		     { outline: 1px dotted #555; }
.nr_checked.nr_focus { outline: none; }

Minified, this radio replacement plugin shrinks to under 1KB. It handles tabbing and focus properly, for both screen readers and keyboard users. It handles radio changes via clicking associated labels. And by using an anchor tag to hold the radio replacement image, it handles the odd browser that does not treat labels as clickable (a problem with some of the other radio replacement plugins I encountered).

Feel free to use this plugin as you like, and I hope it proves useful! Let me know if you find any bugs or particular browser quirks.


Really Cool Glossy Progress/Result Bars in Pure CSS

Inspired by this progress bar design, I decided to recreate the look using CSS.  The end result is this:

CSS Progress Bars

The bars above were created purely with CSS (taking advantage of CSS3 properties such as linear-gradient and box-shadow), supported by all recent browsers versions except IE9 and below.  Here is how, beginning with the HTML code.

<div id="container">
    <p id="title">Here are the results:</p>
    <p>Option 1</p>
    <!-- .barOuter is the box containing the bar,
         .barInner is the bar itself -->
    <div class="barOuter"><div class="barInner" style="width: 53%;"></div><div class="barLabel">53%</div></div>
    <p>Option 2</p>
    <div class="barOuter"><div class="barInner" style="width: 24%;"></div><div class="barLabel">24%</div></div>
    <p>Option 3</p>
    <div class="barOuter"><div class="barInner" style="width: 91%;"></div><div class="barLabel">91%</div></div>

Read moreRead more


Selecting Rows With Chinese Characters in MySQL

…or Russian/Cyrillic characters, or Arabic, or any characters of non-latin origin.

On this blog, I’ve let tons of spam comments pile up in the pending queue. Their number grew to the point of being completely unmanageable. Finally I decided to clean it up, and I had to find a way to bulk delete rows from the wp_comments table in the WordPress database. One thing I noticed was that hundreds, probably thousands, of spam comments contained Chinese characters. Other comments contained Russian or other non-latin characters. But how to select comments in which non-latin characters appear without selecting for specific strings (for example by using LIKE or REGEXP)?

It turns out the way to do it is like this:

FROM    wp_comments
WHERE   comment_content != CONVERT(comment_content USING latin1)

CONVERT … USING will convert the column value to the specified character set, replacing any characters that do not map into the set with a question mark. If there are no Chinese/Russian/etc. characters, the output of CONVERT … USING will be the same as the unconverted column value.

This was the SQL statement I used to delete the unwanted posts:

DELETE FROM wp_comments
WHERE   comment_content != CONVERT(comment_content USING latin1) AND
        comment_approved = '0'

If there is any interest, I can post some other SQL statements I used to clean up the spam.


Log SQL Statements With Parameter Values Filled In (Spring JDBC)

If you’re using parameterized queries with Spring JDBC (and why wouldn’t you?), it’s easy to log them with a simple log.debug() statement. But your logged statements will be full of ?’s instead of the values, which makes them much less useful. Suppose you’d like to know what was substituted for those question marks. It’s not so difficult if you use AspectJ.  Here is what is needed:

  1. aspectjrt.jar and aspectjweaver.jar from here.
  2. An aspect with a pointcut on the JdbcOperations interface, which JdbcTemplate implements.
  3. @Before advice that intercepts the execution of JdbcTemplate methods and logs de-parameterized SQL statements.
  4. Configuration of Spring applicationContext.xml to get it working.

Let’s start off with our class:

public class SqlLogger {
    private static final Logger log = LoggerFactory.getLogger(SqlLogger.class);

Here, I’m using an org.slf4j.Logger, but any logging framework will work.

Next step is to add the method that will capture the SQL and parameters as they are executed. Again, I’m using Spring JDBC, so all calls are made to an object that implements JdbcOperations.  We can set up our class to spy on all relevant calls by defining our method like so:

Read moreRead more


Make Rainbow-Colored Lists (and other HTML elements) – jQuery plugin

How to make rainbow-colored lists? I started searching for a solution and found a plugin for rainbow text, which inspired me to write my own jQuery plugin to rainbow-ify lists and other sets of HTML elements.

I’m used to working with RGB hex color codes.  But there is no intuitive way to generate a spectrum of color using RGB, so I turned to HSL (hue, saturation and lightness).  Most modern browsers support colors specified with hsl(hue, saturation%, lightness%), although IE versions prior to 9 do not. So I started out using HSL, adding IE support later. I found that keeping the saturation and lightness constant at 100% and 80% respectively while increasing the hue in steps produces a really nice rainbow effect.

Let’s back up a bit. Consider the following styled list:

rainbow list w/o rainbow!

I’d like to color this list to look like a rainbow. Using CSS alone is unwieldy; without knowing in advance the number of elements in the list, it’s impossible.  We need to use Javascript to get this result:

rainbow-colored list

Here’s how I did it–my rainbow plugin code (~1KB when minified):

Read moreRead more


jQuery Shake Plugin to, er, Make Elements Shake

I wanted to make a submit button shake back and forth when the form input is invalid, signaling the user that there was a problem. Simple enough. So I googled around for an existing solution, but the jquery plugins I found only made elements vibrate like crazy. I wanted a left-right shake.

Well it turned out to be very easy to implement myself.  Minified, my shake jquery plugin is less than 0.5KB.  Here’s a demo page.  Here’s the code:

(function($) {
    'use strict';

    //the plugin call
    $.shake = $.fn.shake = function(options) {
        if (this.length !== 0) {
            //initialize settings & vars
            var settings = $.extend(
                {   distance:   12,
                    iterations: 3,
                    duration:   160,
                    easing:     'swing'},
                $shakeThis = this;

            return $shakeThis.each(function(i, el) {
                var $el = $(el),
                    marg = ($el.parent().width() / 2) - ($el.outerWidth() / 2);

                $el.css('margin-left', marg);
                for (var j = 0; j < settings.iterations; j++)
                    leftRight($el, marg);

                $el.animate({'margin-left': marg}, settings);

        function leftRight($el, marg) {
            $el.animate({'margin-left': (marg - settings.distance)}, settings)
               .animate({'margin-left': (marg + settings.distance)}, settings);


Read moreRead more


CSS3 Styled Progress Bar

The quiz results on GoToQuiz are, more or less, progress bars.  They visually depict your quiz result as it falls between 0% and 100%, inclusive.  How would one go about creating an attractive progress bar entirely in CSS3?  I’ll quickly show how I did it.

First, this is what the old bars look like:

Simple red progress bar

It’s a <div> inside a <div> with some simple styling.  The inner <div> is set to a reddish background and given a width as a percentage–80%, in the example above.  This is a simple bar that communicates what it needs to, whether as a quiz result, poll result, or progress bar, but it’s not visually appealing.  In contrast, this is what the new bar looks like:

beautiful CSS3 progress bar

This is done without any images, which would require additional requests to the server and are best-avoided when CSS is up to the job.  And it works in all modern browsers (although IE < 10 will not stripe the unfilled portion of the bar).

First, here is the HTML for the progress bar: Read moreRead more


Distribute Android App From Your Own Web Server

Listing your app on Google Play or another centralized app store may not make sense for your situation.  This was the case for me when I created an app for small web community, which would be meaningless for anyone else.  There’s nothing stopping you from simply uploading the .apk file to your web server and linking to it, though.  And that’s what I did.

One thing I discovered is that not all devices will recognize the file as an installable app based on the file extension alone.  You must ensure you send the proper mime type.  You can achieve this for Apache by associating the correct mime type with .apk files.  Adding this line to .htaccess will do the trick:

AddType application/ apk

When a user clicks a link to the file, their device will download it.  There will be a “download complete” notification when completed.  Clicking this will grant the option to install the app.  It’s a process that is likely to be unfamiliar to your users, but it’s not too complicated.

One thing you lose is the automatic management of app updates that Google Play provides.  Your users will have to manually download the latest version of the app and install again, which thankfully is handled properly at that point by Android–that is to say, it’s treated as an upgrade to a newer version rather than a clean install.  Consider adding some type of notification to the app’s functionality that will alert users to perform an update if their app version is not the latest.


How To Make an Android Home Screen Widget Update Only When Visible

Depending on the nature of your home screen widget, you may want it to stay closely synched to real-time data. It would be nice if Android fired a system event that you could register for whenever your widget is visible on the screen. However, Android does not do this, and could not be counted upon to do so in any case because some users may be using a 3rd party alternative to the default home screen.

You’d like to update your widget early and often, at times when the user might be looking at it. But you want to prevent it from updating (and wasting resources) when the user is not engaged. There is a way to achieve this. This technique isn’t perfect, because it will cause your widget to update even when hidden behind another running app, but that much is unavoidable. (Note to Google: an isWidgetVisible() method would be great!)

I’m going to describe how I used a Service to update my web community widget only when the screen is on.  The java classes involved are:

  • MRPWidget (extends AppWidgetProvider)
  • WidgetUpdate (extends IntentService)
  • MRPAlarmReceiver (extends BroadcastReceiver)

I described the MRPWidget class here: creating an Android home screen widget.  Now I will describe how the Service is used to update the widget.

Read moreRead more


Android Home Screen Widget: Creating the AppWidgetProvider

Extending AppWidgetProvider is a simple way to encapsulate your app’s management of your home screen widget.  It provides several widget life cycle methods you can override to handle such events as a user adding or removing the widget from their home screen.  It also provides an onUpdate method that ties into the periodic updates the Android system will trigger for your widget.  For my purposes, I disabled this periodic updating because I wanted to control it myself via a Service.

Your AppWidgetProvider interacts with the widget via the RemoteViews class.  The widget is itself hosted in a separate process from the one in which your app runs, and RemoteViews provides methods to cross that gap, update the views and add click listeners.  Note that RemoteViews methods provide only a limited subset of view functionality, and this may restrict what you’d like to do with your widget.  For example, animations are not supported.

I’m going to describe how I created my web community widget.  The java classes involved are:

  • MRPWidget (extends AppWidgetProvider)
  • WidgetUpdate (extends IntentService)
  • MRPAlarmReceiver (extends BroadcastReceiver)

My widget class is named MRPWidget, and it extends AppWidgetProvider.  All visual updates to the widget are handled by this class, as well as starting the service that will perform the updates.  For example, when the widget is enabled it should start the service: Read moreRead more