• Home Home
  • Antiquiet Antiquiet
  • Twitter Twitter
  • Facebook Facebook

Kevin "Skwerl" Cogill

  • I would never call what I do "hacking."
    • Antiquiet
    • Rey Interactive
    • Technical
    • Personal
    • Musical
    • Old Stuff
  • Recent

    • Maurice Sendak
    • Electric Relaxation
    • The Only Good Matte Screen Film For Macbook Air
    • HTML Emails, Outlook And Background Images
    • Passing Query Variables To Facebook Fan Page Tabs
    • Omar Asks A Question That Comes To My Mind Every Time I See Legos In A Store
    • All Of This Could Have Been Yours
    • Calculating Distances Between Addresses
    • 24-Bit Audio Explained
    • Freaky Teeth
  • I Read

    • Cracked
    • Techdirt
    • Wired
    • You Are Not So Smart

Output

  • Archives

Technical

Macbook Air Anti-Glare Film

The Only Good Matte Screen Film For Macbook Air

I really do like my 13″ Macbook Air more than I ever thought I could when Airs were first unveiled. I maxed out the RAM and HD, but I didn’t pick up the Ethernet adapter or external optical drive, and I haven’t really missed them. The battery life is great, and on the road, getting real work done is about as convenient as opening up a magazine.

The only thing that gave me pause when I suddenly found myself needing a new laptop after the death of my 15″ Macbook Pro was the fact that there was no option for a matte screen. Even though the Air’s screen is not quite as glossy as those of its peers, I hate (with the sort of burning passion reserved by developers/designers for seemingly inconsequential details such as mildly objectionable fonts and colors) glossy displays where a certain shade of red could be lord knows what wrong color depending on what angle you’re viewing at or what in the room is reflecting off your screen. Yes, we’re talking about the most minuscule of nitpicky details, and I’m a psycho, but whatever. I ams what I ams. So before I even turned my new Macbook Air on for the first time, I had installed a Power Support anti-glare film.

Over the course of the past 8-10 months or so or however long I’ve had the Air, I’ve changed the film a few times, due to OCD more than necessity. I’ve tried a bunch of less expensive films.

However, the Power Support films are the only ones that really do give you a great matte display, just like the ones Apple provides optionally for the Macbook Pros. No one even asked me, let alone paid me to tell you this. Just a public service announcement from one psychotic design geek to all others.

If you have an Air, buy a bunch while the company / product is still around.

  • November 29, 2011
  • 0
  • 0

HTML Emails, Outlook And Background Images

Coding HTML for emails can be a total bitch. I’m not going to give an exhaustive how-to here, but I just wanted to share a few tricks I had to learn the hard way, in case it might save you some headaches.

First, a few general rules. These rules will occasionally need to be broken, but if you start off by at least trying to follow them, you’ll give yourself a more stable foundation.

  • Host all of your images online (or via a CDN/S3) and use absolute URLs. Of course.
  • Use old-school tables to position all of your elements. I know you spent a lot of time weaning yourself off them and mastering div tags positioned with CSS, but email clients rarely handle that stuff properly. For email, we’ve gotta take it all back to 1998.
  • When you do use CSS (which is by no means recommended against), put your styles either in-line, or in the body tag. Many email clients will chuck your head tag completely.
  • Set alt attributes for all of your images and links. I’ve seen email clients discard images and links that didn’t have alt attributes.
  • Explicitly setting border-collapse on your tables to collapse with CSS seems to help kill certain table spacing-related quirks.
  • Validate your HTML at w3.org. Get it as close to perfectly valid as possible (necessary hacks may make perfect validity impossible).

Now there’s one thing in particular that has given me an extraordinary amount of hell when doing HTML emails, and that is background images. Particularly when it comes to Outlook’s nasty habit of chucking them.

If you’re okay with having one big background image behind everything, you can apply a background image via CSS to the body tag. That actually works in Outlook. However, put your CSS inline or within the body tag (see above). I’ve also heard that you need to set repeat-y if you go this route; that setting CSS background-repeat to no-repeat will actually lose the background image completely in Outlook. Not sure if that’s always the case or what.

The holy grail here is applying background images to table cells. It doesn’t really work in Outlook. There is, however, a hack that I’ve found, and that is the main thing I wanted to share here today:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table width="600" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;">
<tr>
    <td style="width: 600px; height: 350px; background-image: url('http://epicreviewsdotorg.files.wordpress.com/2011/05/unicorn1.jpg');">
        <!--[if gte mso 9]>
        <v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display: inline-block; position: absolute; width: 600px; height: 350px; top: 0; left: 0; border: 0; z-index: 1;' src="http://epicreviewsdotorg.files.wordpress.com/2011/05/unicorn1.jpg" />
        <v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display: inline-block; position: absolute; width: 600px; height: 350px; top: -5; left: -10; border: 0; z-index: 2;'>
        <div>
        <![endif]-->
        <table width="600" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
          <tr>
            <td height="350" align="center" valign="top">
                <p>This table in here has a bunch of stuff I want to lay over the background image...</p>        
            </td>
          </tr>
        </table>
        <!--[if gte mso 9]>
        </div>
        </v:shape>
        <![endif]-->
    </td>
</tr>
</table>

Outlook can’t (or refuses to) render basic CSS, but it does know VML (Vector Markup Language), which is what Microsoft Office uses to position elements in Word and Powerpoint. So what we’re doing is targeting Outlook specifically, and hitting it with some VML.

  • November 28, 2011
  • 0
  • 0

Passing Query Variables To Facebook Fan Page Tabs

UPDATE: Apparently, you can pass variables in using Facebook’s app_data parameter, and then grab them by parsing out the signed request. Hard to say which is now the easier solution, but here’s another option, for whatever it’s worth. I guess it would be the way to go if you wanted to keep data out of the URL, or if you want a solution that also works outside of Facebook.

Here’s a trick to let you Facebook app developers do a couple of things that are typically considered impossible.

Let’s say you have a Facebook app with a Page Tab, and you want to pass it some dynamic variables from an external site or a share post. While you can link directly to a tab by appending an ?sk=app_ to the page URL (example), any custom, non-Facebook variables appended to the URL won’t be passed through to your tab page.

Another problem: Let’s say that tab page has links to sub-pages that load within the main tab iFrame (a la target=”_self”). That’s all easy enough, and pretty common. But what happens when you want to link to sub-sections of your tab page from an external site or share post?

You can’t get variables in through the “front door” so to speak, but you can pass them around the back, using what I call “the cookie trick” (or, inexplicably, “cookie party,” when it’s late in the office and we’re all loopy and/or drunk). The trick involves using a redirect that stores dynamic variables in a cookie, and then sends a user to the tab. When the tab loads, it grabs the data it needs from the cookie, and then deletes it. It’s completely transparent to the end-user.

Here’s all it takes. First, a redirect script:

1
2
3
$var = (empty($_GET['var'])) ? false : $_GET['var'];
if ($var) { setcookie('myapp_var', $var, time()+3600); }
header('Location: '.$fb_app_url);

Then, your main tab page just needs to check for the cookie, get what it needs, and then delete it:

1
2
3
4
5
$var = (empty($_COOKIE['myapp_var'])) ? false : $_COOKIE['myapp_var'];
if ($var) {
    setcookie('myapp_var', '', time()-86400);
    // Do stuff with $var...
}

Voila. You just send your vars to something like redirect.php?var=foo, and they’re slipped to your tab via the cookie.

If you want to link to a sub-page, just pass the sub-page path into your redirect.php as a variable, and then use a PHP header() redirect, or output a line of Javascript to send your users where they need to go.

Here’s an example of a deep-link to one of four mini-games in a Page Tab I built for The Black Eyed Peas Experience game: http://promethiumtorch.com/bep/redirect.php?goto=whatsyourgroove

  • November 24, 2011
  • 0
  • 0

Calculating Distances Between Addresses

Here’s a basic rundown of one way (there are many) to build a store locator.

Essentially it boils down to three steps:

  1. Geocode a table of addresses to latitude and longitude coordinates using the Google Maps API (only need to do this once).
  2. Geocode a query string to get its latitude and longitude coordinates.
  3. Query addresses from DB by comparing latitude and longitude using the Haversine formula.
  4. Bask in the warm glow of trigonometry.

Let’s start with the DB table. Since we’re going to be querying based on latitude and longitude, those two fields should be set as keys. Your MySQL server will probably cry if you don’t do this. And your queries may be noticeably slow.

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE `stores` (
    `id` INT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
    `store_name` VARCHAR(64) DEFAULT NULL,
    `store_address` VARCHAR(128) DEFAULT NULL,
    `store_city` VARCHAR(64) DEFAULT NULL,
    `store_state` VARCHAR(64) DEFAULT NULL,
    `latitude` DECIMAL(10,7) DEFAULT NULL,
    `longitude` DECIMAL(10,7) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `lat_key` (`latitude`),
    KEY `lng_key` (`longitude`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Populate your table of stores, leaving the latitude and longitude fields blank. Then, you can fill those fields by looping through the table, pinging them against the Google Maps API, and popping off AJAX calls to update your DB table:

(You’ll need to include the Maps API Javascript, and jQuery will help you with the AJAX calls.)

1
2
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>

You’ll want to query your table of stores, assembling an array of address strings, and encoding them to a JSON array or something using the row IDs as the keys. Then, loop through it:

1
2
3
4
5
6
7
8
9
10
11
12
var geocoder = new google.maps.Geocoder();
for (var index in addresses) {
    geocoder.geocode({ 'address':addresses[index] }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            $.post("insert.php", { id:index, lat:latitude, lng:longitude }, function(data) {
                console.log(data);
            });
        }
    });
}

You can update a DB, right? Your insert.php would look something like this:

1
2
3
4
5
6
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);
$q=$db->prepare('INSERT INTO stores (latitude,longitude) VALUES (?,?) WHERE id = ?');
$q->bindParam(1,$_POST['lat']);
$q->bindParam(2,$_POST['lng']);
$q->bindParam(3,$_POST['id']);
$q->execute();

If you hate Javascript (or just suck at it), you could go with this super simple PHP route to get latitude and longitude from Google (thanks Weston):

1
2
3
4
5
$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=/'.$address.'&sensor=false');
$output = json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$lon = $output->results[0]->geometry->location->lng;
// Insert to DB...

That’s step one, the hardest part, the part that only needs to be done once. Once you’ve got that groundwork done, your DB is ready for real user queries.

First, take the user’s input query and Geocode it, using either method above (Javascript or PHP), to get the latitude and longitude. Once you have those, you can do one clean MySQL query to get locations ordered by distance (replace QUERY_LAT and QUERY_LON with the latitude and longitude returned from Google, respectively):

1
SELECT *, (3959 * acos(cos(radians(QUERY_LAT)) * cos(radians(latitude)) * cos(radians(longitude) - radians(QUERY_LON)) + sin(radians(QUERY_LAT)) * sin(radians(latitude)))) AS distance FROM stores ORDER BY distance;

Fuck yeah, math.

  • November 24, 2011
  • 0
  • 0

24-Bit Audio Explained

  • November 24, 2011
  • 0
  • 0

Random Selection With Weight

I’d like to share with you a simple algorithm for taking random selections from a set of items while factoring in a manual, arbitrary “weighting” mechanism.

We’re assuming that the default weight is 1, and that a weight of 0 would exclude an item from the result set. Whether or not there is a “maximum” weight is irrelevant to this algorithm.

The idea is that you first sum all of the weights together, to get a grand total of the combined weight of all items in the result set. Now imagine all of your results lined up in a straight line, with the size of their spot in the line determined by their weight. So if the first item has a weight of 50, its spot in line goes from points 1 to 51. If the second item has a weight of 20, it goes from points 52 to 72. And so on, with the last item ending at that cumulative total we calculated.

What you then do is pick random numbers between (and including) 1 and that cumulative total. Whatever item is occupying that position in the line is your winner. Repeat for as many results as you need.

If your data is in a MySQL database, you can add a running cumulative count to the results array using a MySQL variable:

1
2
3
4
5
6
7
8
9
10
SET @csum := 0;
SELECT
    item.id,
    item.name,
    item.field,
    item.weight,
    (@csum := @csum + item.weight) as cumulative_sum
FROM items as item
WHERE item.weight > 0
ORDER BY id;

Then you iterate through a loop for as many random selections as you need, counting up to the item whose cumulative_sum contains your random number. For example, in PHP:

1
2
3
4
5
6
7
8
9
10
11
$winners = array();
while ($has_enough == false) {
    $random_index = rand(1,$cumulative_total);
    foreach ($items as $item) {
        if ($item['cumulative_sum'] >= $random_index) {
            $winners[] = $item;
            // Set $has_enough to true when you have enough...
            break;
        }
    }
}

All in all, very efficient.

  • November 24, 2011
  • 1
  • 0

Copyright © 2012 Kevin "Skwerl" Cogill. Powered by WordPress.

  • Twitter
  • Facebook
  • LinkedIn
  • Tumblr
  • Reddit
  • Steam
  • Google+