<?xml version="1.0"  encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="http://thingsinjars.com/includes/style/rss.css" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://thingsinjars.com/rss/guides/" rel="self" type="application/rss+xml" />
<title>Things in Jars</title>
<link>http://thingsinjars.com/</link>
<description>Articles from Things in Jars</description>
<language>en</language>
<docs>http://en.wikipedia.org/wiki/RSS_(file_format)</docs>
<lastBuildDate>Sat, 27 Apr 13 00:00:00 -0700</lastBuildDate>
<ttl>45</ttl><item>
<title>Some App.net recipes</title>
<link>http://thingsinjars.com/post/469/some-appnet-recipes/</link>
<guid>http://thingsinjars.com/post/469/some-appnet-recipes/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-469">
        <p><a href="http://thingsinjars.com/post/469/some-appnet-recipes/">Some App.net recipes</a></p>
<p>This is a collection of code snippets for various common tasks you might need to accomplish with the <a href="https://github.com/appdotnet/api-spec">App.net API</a>. Most of these are focused on creating or reading geo-tagged posts. They require a developer account on app.net and at least one of an App ID, App Code, App Access Token or User Access Token. The calls here are implemented using jQuery but that's just to make it easier to copy-paste into the console to test them out (so long as you fill in the blanks). </p>

<p>An important thing to bear in mind is the possibility for confusion between a 'stream' and 'streams'. By default, a 'stream' is a discrete chunk of the 20 latest posts served at a number of endpoints. This is the open, public, <a href="https://alpha-api.app.net/stream/0/posts/stream/global">global stream</a>:</p>

<pre><code>https://alpha-api.app.net/stream/0/posts/stream/global
</code></pre>

<p>On the other hand, 'streams' are long-poll connections that serve up any matching posts as soon as they are created. The connection stays open while there is something there to receive the response. Streams are available under:</p>

<pre><code>https://alpha-api.app.net/stream/0/streams
</code></pre>

<p>Totally not confusing. Not at all.</p>



<h2>Creating a user access token</h2>

<p>Required for any user-specific data retrieval. The only tricky thing you'll need to think about here is the <code>scope</code> you require.</p>

<pre><code>scope=stream email write_post follow messages export
</code></pre>

<p>should cover most requirements.</p>

<h3>Requires</h3>

<ul>
<li><code>client_id</code></li>
</ul>

<p>Visit this URL:</p>

<pre><code>https://alpha.app.net/oauth/authenticate
    ?client_id=[your client ID]
    &amp;response_type=token
    &amp;redirect_uri=http://localhost/
    &amp;scope=stream email write_post follow messages export
</code></pre>



<h2>Using a user access token to create a post (with annotations)</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
<li>text to post</li>
</ul>

<p>The text is essential if you don't mark a post as '<code>machine_only</code>'. The annotations here are optional. Annotations don't appear in the global stream unless the requesting client asks for them.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({
    "annotations": [{
      "type": "net.app.core.geolocation",
      "value": {
        "latitude": 52.5,
        "longitude": 13.3,
        "altitude": 0,
        "horizontal_accuracy": 100,
        "vertical_accuracy": 100
      }
    }],
    "text": "Don't mind me, just checking something out."
  }),
  dataType: 'json',
  success: function(data) {
    console.log("Text+annotation message posted");
  },
  error: function() {
    console.log("Text+annotation message failed");
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/posts?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>



<h2>Using a user access token to post a machine_only post (with annotations)</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
</ul>

<p>In this example, we're creating a post that won't show up in user's timelines and adding the 'well-known annotation' for geolocation.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({
    "annotations": [{
      "type": "net.app.core.geolocation",
      "value": {
        "latitude": 52.5,
        "longitude": 13.3,
        "altitude": 0,
        "horizontal_accuracy": 100,
        "vertical_accuracy": 100
      }
    }],
    machine_only: true
  }),
  dataType: 'json',
  success: function(data) {
    console.log("Non-text message posted");
  },
  error: function() {
    console.log("Non-text message failed");
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/posts?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>



<h2>Retrieve the global stream, including geo-annotated posts if there are any</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
</ul>

<p>This is a very basic call to retrieve the <a href="https://alpha-api.app.net/stream/0/posts/stream/global">global stream</a> but it also instructs the endpoint to return us all annotations and include machine-only posts.</p>

<pre><code>var data = {
  "include_machine": 1,
  "include_annotations": 1,
  "access_token": "{USER_ACCESS_TOKEN}"
};

$.ajax({
    contentType: 'application/json',
    dataType: 'json',
    success: function(data) {
      console.log(data);
    },
    error: function(error, data) {
      console.log(error, data);
    },
    type: 'GET',
    url: 'https://alpha-api.app.net/stream/0/posts/stream/global',
    data: data
});
</code></pre>



<h2>Creating an App Access Token</h2>

<p>This is necessary for many of the <code>streams</code> operations. It is not used for individual user actions, only for application-wide actions. </p>

<ul>
<li><a href="https://github.com/appdotnet/api-spec/blob/master/auth.md#app-access-token-flow">App.net API wiki on App Access Tokens</a></li>
</ul>

<h3>Requires</h3>

<ul>
<li><code>client_id</code></li>
<li><code>client_secret</code></li>
</ul>

<p><code>client_credentials</code> is one of the four types of <code>grant_type</code> specified in the <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-31">OAuth 2.0 specification</a>. I had difficulty getting this to work when using a data object:</p>

<pre><code>var data = {
    "client_id": "{CLIENT_ID}",
    "client_secret":"{CLIENT_SECRET}",
    "grant_type": "client_credentials"
};
</code></pre>

<p>The <code>client_credentials</code> kept throwing an error. Instead, sending this as a string worked fine:</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: 'client_id={CLIENT_ID}&amp;client_secret={CLIENT_SECRET}&amp;grant_type=client_credentials',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, data) {
    console.log(error, data);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha.app.net/oauth/access_token'
});
</code></pre>

<p>One other thing to note is that this bit should be done server-side. This will throw a bunch of "…not allowed by Access-Control-Allow-Origin…" errors if you do it via jQuery.</p>

<h3>Returns</h3>

<pre><code>{
    "access_token": "{APP_ACCESS_TOKEN}"
    }
</code></pre>



<h2>Creating a <code>streams</code> format</h2>

<p>Now you have your app access token, you can use it to tell the service what kind of data you want back. The streams offered in the API have two quite powerful aspects. Firstly, filters allow you to run many kinds of queries on the data before it is streamed to you so you don't need to recieve and process it all. Secondly, the decoupling of filters from streams means you can specify the data structure and requirements you want once then just access that custom endpoint to get the data you want back any time.</p>

<h3>Requires</h3>

<ul>
<li><code>App access token</code></li>
</ul>

<p>This first example just creates an unfiltered stream endpoint</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"object_types": ["post"], "type": "long_poll", "id": "1"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/streams?access_token={APP_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<pre><code>{
    "data": {
        "endpoint": "https://stream-channel.app.net/channel/1/{LONG_RANDOM_ENDPOINT_URL}",
        "id": "77",
        "object_types": [
            "post"
        ],
        "type": "long_poll"
    },
    "meta": {
        "code": 200
    }
}
</code></pre>



<h2>Using Filters to create a stream of geotagged posts</h2>

<p>We'll specify some requirements for our filter now so that it only returns back a subset of posts. The rules we're specfying here are:</p>

<pre><code>At least one item in the "/data/annotations/*/type" field
must "match"
the value "net.app.core.geolocation"
</code></pre>

<h3>Requires</h3>

<ul>
<li><code>User access token</code></li>
</ul>

<p>The <code>field</code> is specified in '<a href="http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer-02">JSON Pointer</a>' format. Within the response, there is a 'data' object and a 'meta' object. The data contains an 'annotations' object which contains an array of annotations, each of which has a type. This is represented as <code>/data/annotations/*/type</code>.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"match_policy": "include_any", "clauses": [{"object_type": "post", "operator": "matches", "value": "net.app.core.geolocation", "field": "/data/annotations/*/type"}], "name": "Geotagged posts"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/filters?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<p>The filter rules you just specified, the <code>id</code> of the filter (remember that for later) and the details of the application used to make the request.</p>

<pre><code>{
"clauses": [
    {
        "field": "/data/annotations/*/type",
        "object_type": "post",
        "operator": "matches",
        "value": "net.app.core.geolocation"
    }
],
"id": "527",
"match_policy": "include_any",
"name": "Geotagged posts",
"owner": {
    "avatar_image": {
        "height": 200,
        "url": "https://d2rfichhc2fb9n.cloudfront.net/image/4/Pr63PjEwJ1fr5Q4KeL3392BMgSnIAYlHxv8OkWwzx75V8quNfpaFp4VPpKnDRxdXtYYPtIutrDVdU9NbJn7hKApQL84T5sfB1D9bWTgtizMWInignv0WyPPfM2DpqSThQgvkB68vbPzjZ8VeKM02M2GySZ4",
        "width": 200
    },
    "canonical_url": "https://alpha.app.net/thingsinjars",
    "counts": {
        "followers": 30,
        "following": 65,
        "posts": 96,
        "stars": 0
    },
    "cover_image": {
        "height": 230,
        "url": "https://d2rfichhc2fb9n.cloudfront.net/image/4/UWZ6k9xD8_8LzEVUi_Uz6C-Vn-I8uPGEBtKb9jSVoFNijTwyEm1mJYpWq6JvnA6Jd4gzW76vFnbSWvM3jadhc1QxUl9qS4NTKiv3gJmr1zY_UpFWvX3qhOIyKrBPZckf2MrinqWay3H0h9rfqY0Gp9-liEg",
        "width": 960
    },
    "created_at": "2012-08-12T17:23:44Z",
    "description": {
        "entities": {
            "hashtags": [],
            "links": [],
            "mentions": []
        },
        "html": "&lt;span itemscope="https://app.net/schemas/Post"&gt;Nokia Maps Technologies Evangelist; CreativeJS team member; the tech side of museum140; builder of The Elementals; misuser of semi-colons;rn&lt;/span&gt;",
        "text": "Nokia Maps Technologies Evangelist; CreativeJS team member; the tech side of museum140; builder of The Elementals; misuser of semi-colons;rn"
    },
    "id": "3191",
    "locale": "en_GB",
    "name": "Simon Madine",
    "timezone": "Europe/Berlin",
    "type": "human",
    "username": "thingsinjars"
}
}
</code></pre>



<h2>Listening to the geotagged post stream</h2>

<p>This wil return a link to a long-lasting connection to the app.net stream that will only return posts with the geolocation annotation.</p>

<h3>Requires</h3>

<ul>
<li><code>filter_id</code> from the previous call</li>
</ul>

<p>Note: the <code>filter_id</code> was returned as <code>id</code> in the previous response.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"object_types": ["post"], "type": "long_poll", "filter_id": "527"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/streams?access_token={APP_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<p>The same kind of response as the 'Creating a <code>streams</code> format' example except the data coming down on the stream is filtered.</p>

<pre><code>https://stream-channel.app.net/channel/1/{LONG_RANDOM_ENDPOINT_URL}
</code></pre>

<p>Open that URL up in your browser (seeing as we're testing) and, in a different tab, create a geo-tagged machine-only post (see above). Your post will appear almost instantly after you've submitted it.</p>
      </div>
]]></description>
<pubDate>Mon, 29 Oct 2012 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Building a Proximity Search</title>
<link>http://thingsinjars.com/post/466/building-a-proximity-search/</link>
<guid>http://thingsinjars.com/post/466/building-a-proximity-search/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-466">
        <p><a href="http://thingsinjars.com/post/466/building-a-proximity-search/">Building a Proximity Search</a></p>
<p>This is the detailed post to go with <a href="http://thingsinjars.com/post/465/proximity-search/">yesterday's quick discussion about proximity search</a>. All the code is <a href="https://github.com/thingsinjars/Proximity">available on GitHub</a>.</p>

<p>This assumes a bit of <a href="http://nodejs.org/">NodeJS</a> knowledge, a working copy of <a href="http://mxcl.github.com/homebrew/">homebrew</a> or something similar.</p>

<h2>Install</h2>

<ul>
<li>MongoDB - <code>brew install mongodb</code></li>
<li><a href="http://nodejs.org/">NodeJS</a></li>
<li>NPM (included in NodeJS installer these days)</li>
</ul>

<p>These are included in the <a href="https://github.com/thingsinjars/Proximity/blob/master/package.json"><code>package.json</code></a> but it can't hurt to mention them here:</p>

<ul>
<li><code>npm install twitter</code> (node twitter streaming API library)</li>
<li><code>npm install mongodb</code> (native mongodb driver for node)</li>
<li><code>npm install express</code> (for convenience with API later)</li>
</ul>

<p>Start <code>mongod</code> in the background. We don't quite need it yet but it needs done at some point, may as well do it now.</p>

<h2>Create a Twitter App</h2>

<p><a href="https://dev.twitter.com/apps/new">Fill out the form</a> Then press the button to get the single-user access token and key. I love that Twitter does this now, rather than having to create a full authentication flow for single-user applications.</p>

<h2>ingest.js</h2>

<p><em>(open the <a href="https://github.com/thingsinjars/Proximity/blob/master/ingest.js">ingest.js</a> file and read along with this bit)</em></p>

<p>Using the basic native MongoDB driver, everything must be done in the <code>database.open</code> callback. This might lead to a bit of Nested Callback Fury but if it bothers you or becomes a bit too furious for your particular implementation, there are a couple of alternative Node-MongoDB modules that abstract this out a bit.</p>

<pre><code>// Open the proximity database
db.open(function() {
    // Open the post collection
    db.collection('posts', function(err, collection) {
        // Start listening to the global stream
        twit.stream('statuses/sample', function(stream) {
            // For each post
            stream.on('data', function(data) {
                if ( !! data.geo) {
                    collection.insert(data);
                }
            });
        });
    });
});
</code></pre>

<h2>Index the data</h2>

<p>The hard work has all been done for us: <a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing/">Geospatial Indexing in MongoDB</a>. That's a good thing.</p>

<p>Ensure the system has a Geospatial index on the tweets.</p>

<pre><code>db.posts.ensureIndex({"geo.coordinates" : "2d"})
</code></pre>

<p>Standard Geospatial search query:</p>

<pre><code>db.posts.find({"geo.coordinates": {$near: [50, 13]}}).pretty()
(find the closest points to (50,13) and return them sorted by distance)
</code></pre>

<p>By this point, we've got a database full of geo-searchable posts and a way to do a proximity search on them. To be fair, it's more down to mongodb than anything we've done.</p>

<p>Next, we extend the search on those posts to allow filtering by query</p>



<pre><code>db.posts.find({"geo.coordinates": {$near: [50, 13]}, text: /.*searchterm.*/}).pretty()
</code></pre>

<h2>API</h2>

<p>Super simple API, we only have two main query types:</p>

<ul>
<li><code>/proximity?latitude=55&amp;longitude=13</code></li>
<li><code>/proximity?latitude=55&amp;longitude=13&amp;q=searchterm</code></li>
</ul>

<p>Each of these can take an optional <code>'callback'</code> parameter to enable <code>jsonp</code>. We're using express so the callback parameter and content type for returning JSON are both handled automatically.</p>

<p><code>api.js</code></p>

<p><em>(open the <a href="https://github.com/thingsinjars/Proximity/blob/master/api.js">api.js</a> file and read along with this bit)</em></p>

<p>This next chunk of code contains everything so don't panic.</p>

<pre><code>db.open(function() {
  db.collection('posts', function(err, collection) {
    app.get('/proximity', function(req, res) {
      var latitude, longitude, q;
      latitude = parseFloat(req.query["latitude"]);
      longitude = parseFloat(req.query["longitude"]);
      q = req.query["q"];

      if (/^(-?d+(.d+)?)$/.test(latitude) &amp;&amp; /^(-?d+(.d+)?)$/.test(longitude)) {
        if (typeof q === 'undefined') {
          collection.find({
            "geo.coordinates": {
              $near: [latitude, longitude]
            }
          }, function(err, cursor) {
            cursor.toArray(function(err, items) {
              writeResponse(items, res);
            });
          });
        } else {
          var regexQuery = new RegExp(".*" + q + ".*");
          collection.find({
            "geo.coordinates": {
              $near: [latitude, longitude]
            },
            'text': regexQuery
          }, function(err, cursor) {
            cursor.toArray(function(err, items) {
              writeResponse(items, res);
            });
          });
        }
      } else {
        res.send('malformed lat/lng');
      }

    });
  });
});
</code></pre>

<p>If you've already implemented the <code>ingest.js</code> bit, the majority of this <code>api.js</code> will be fairly obvious. The biggest change is that instead of loading the data stream then acting upon each individual post that comes in, we're acting on URL requests.</p>

<pre><code>app.get('/proximity', function(req, res) {
</code></pre>

<p>For every request on this path, we try and parse the query string to pull out a latitude, longitude and optional query parameter.</p>

<pre><code>if (/^(-?d+(.d+)?)$/.test(latitude) &amp;&amp; /^(-?d+(.d+)?)$/.test(longitude)) {
</code></pre>

<p>If we <strong>do</strong> have valid coordinates, pass through to Mongo to do that actual search:</p>

<pre><code>collection.find({
  "geo.coordinates": {
    $near: [latitude, longitude]
  }
}, function(err, cursor) {
  cursor.toArray(function(err, items) {
    writeResponse(items, res);
  });
});
</code></pre>

<p>To add a text search into this, we just need to add one more parameter to the <code>collection.find</code> call:</p>

<pre><code>var regexQuery = new RegExp(".*" + q + ".*");
collection.find({
  "geo.coordinates": {
    $near: [latitude, longitude]
  },
  'text': regexQuery
}
</code></pre>

<p>This makes it so simple, making it it kind of feels like cheating. Somebody else did all the hard work first.</p>

<h2>App.net Proximity</h2>

<p>This works quite well on the <a href="https://alpha-api.app.net/stream/0/posts/stream/global">App.net Global Timeline</a> but it'll really become useful once the <a href="https://github.com/appdotnet/api-spec/blob/master/resources/streams.md">streaming API is switched on</a>.</p>

<p>Of course, the <a href="https://github.com/thingsinjars/Proximity">code is all there</a>. If you want to have a go yourself, feel free.</p>
      </div>
]]></description>
<pubDate>Mon, 08 Oct 2012 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>CoverMap - Nokia Maps on Facebook</title>
<link>http://thingsinjars.com/post/463/covermap---nokia-maps-on-facebook/</link>
<guid>http://thingsinjars.com/post/463/covermap---nokia-maps-on-facebook/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-463">
        <p><a href="http://thingsinjars.com/post/463/covermap---nokia-maps-on-facebook/">CoverMap - Nokia Maps on Facebook</a></p>
<p>I'm almost managing to keep to my intended schedule of one map-based web experiment per week. Unfortunately, I've mostly been working on internal <a href="http://maps.nokia.com/">Nokia Maps</a> projects over the weekends recently so I've not had much to post here.</p>

<p>I can share my latest toy, though: <a href="http://covermap.me">CoverMap.me</a></p>

<p>Using just the public APIs over a couple of hours last Sunday afternoon, I made this to allow you to set a Nokia Map as your Facebook Timeline cover. The whole process is really straightforward so I thought I'd go over the main parts.</p>

<p>The exact aim of CoverMap.me is to allow the user to position a map exactly, choose from any of the available map styles and set the image as their cover image.</p>

<h2>Make a Facebook App</h2>

<p>Go to <a href="http://developers.facebook.com/apps/">developers.facebook.com/apps/</a> and click 'Create New App', fill in the basic details – name of the app, URL it will be hosted on, etc – and you're done.</p>

<h2>Facebook login</h2>

<p>I've used the Facebook JS SDK extensively over the summer for various projects but I wanted to try out the PHP one for this. Super, super simple. Really. Include the library (<a href="https://github.com/facebook/facebook-php-sdk">available here</a>), set your <code>appId</code> and <code>secret</code> and request the <code>$login_url</code>.</p>

<pre><code>$facebook-&gt;getLoginUrl(array('redirect_uri' =&gt; "http://example.com/index.php"));
</code></pre>

<p>That will give you a link which will take care of logging the user in and giving you basic access permissions and details about them.</p>

<h2>Nokia Maps JS API</h2>

<p>When I'm hacking together something quick and simple with the <a href="http://api.maps.nokia.com/">Nokia Maps API</a>, I usually use the properly awsm jQuery plugin <a href="https://github.com/mmarcon/jOVI">jOVI</a> written by the equally awsm <a href="http://marcon.me/">Max</a>. This makes 90% of the things you would want to do with a map extremely easy and if you're doing stuff advanced enough to want the extra 10%, you're probably not the type who'd want to use a jQuery plugin, anyway. Either way, you need to register on the <a href="http://api.developer.nokia.com/">Nokia developer site</a> to get your Nokia <code>app_id</code> and <code>secret</code>.</p>

<p>To create a map using jOVI, simply include the plugin in your page then run <code>.jOVI</code> on the object you want to contain the map along with starting parameters:</p>

<pre><code>$(window).on('load', function() {
  $('#mapContainer').jOVI({
    center: [38.895111, -77.036667], // Washington D.C.
    zoom: 12,           // zoom level
    behavior: true,     // map interaction
    zoomBar: true,      // zoom bar
    scaleBar: false,    // scale bar at the bottom
    overview: false,    // minimap (bottom-right)
    typeSelector: false,// normal, satellite, terrain
    positioning: true   // geolocation
  }, "APP_ID", "APP_SECRET");
});
</code></pre>

<p>This gives us a complete embedded map.</p>

<p>As I mentioned above, part of the idea for CoverMap.me was to allow the  to choose from any of the available map styles. This was an interesting oddity because the public <a href="http://api.maps.nokia.com/en/maps/intro.html">JS API</a> gives you the choice of 'Normal', 'Satellite', 'Satellite Plain' (a.k.a. no text), 'Smart' (a.k.a. grey), 'Smart Public Transport', 'Terrain' and 'Traffic' while the <a href="http://api.maps.nokia.com/en/restmaps/overview.html">RESTful Maps API</a> (the API that provides static, non-interactive map images) supports all of these <em>plus</em> options to choose each of them with big or small text <em>plus</em> a 'Night Time' mode. Because of this, I decided to go for a two-step approach where users were shown the JS-powered map to let them choose their location then they went through to the RESTful static map to allow them to choose from the larger array of static tiles.</p>

<h2>RESTful Maps</h2>

<p>The <a href="http://api.maps.nokia.com/en/restmaps/overview.html">RESTful Maps API</a> is relatively new but does provide a nice, quick map solution when you don't need any interactivity. Just set an <code>img src</code> with the query parameters you need and get back an image.</p>

<pre><code>(this should be all on one line)
http://m.nok.it/
    ?app_id=APP_ID
    &amp;token=APP_TOKEN
    &amp;nord       // Don't redirect to maps.nokia.com
    &amp;w=640      // Width
    &amp;h=480      // Height
    &amp;nodot      // Don't put a green dot in the centre
    &amp;c=38.895111, -77.036667 // Where to centre
    &amp;z=12       // Zoom level
    &amp;t=0        // Tile Style
</code></pre>

<p>That URL produces this image:</p>

<p><img src="http://m.nok.it/?app_id=_peU-uCkp-j8ovkzFGNU&token=gBoUkAMoxoqIWfxWA5DuMQ&nord&w=640&h=480&nodot&c=38.895111, -77.036667&z=12&t=0" alt="Map of Washington D.C."></p>

<h2>Upload to Facebook</h2>

<p>Given the above, we've now got an image showing a map positioned exactly where the user wants it in the tile style the user likes. We just need to make the Facebook API call to set it as Timeline Cover Image and we're done.</p>

<p>You'd think.</p>

<p>Facebook doesn't provide an API endpoint to update a user's profile image or timeline cover. It's probably a privacy thing or a security thing or something. Either way, it doesn't exist. Never fear! There's a solution!</p>

<p>With the default permissions given by a Facebook login/OAUTH token exchange/etc... (that thing we did earlier), we are allowed to upload a photo to an album. </p>

<p>The easiest way to do this is to download the map tile using cURL then repost it to Facebook. The clever way to do it would be to pipe the incoming input stream directly back out to Facebook without writing to the local file system but it would be slightly more hassle to set that up and wouldn't really make much of a difference to how it works.</p>

<pre><code>// Download from RESTful Maps
$tileUrl = "http://m.nok.it/?app_id=APP_ID&amp;token=APP_TOKEN&amp;nord&amp;w=640&amp;h=480&amp;nodot&amp;c=38.895111,%20-77.036667&amp;z=12&amp;t=0";
$ch = curl_init( $tileUrl );
$fp = fopen( $filename, 'wb' );
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_exec( $ch ); 
curl_close( $ch );
fclose( $fp );

//Upload to Facebook
$full_image_path = realpath($filename);
$args = array('message' =&gt; 'Uploaded by CoverMap.me');
$args['image'] = '@' . $full_image_path;
$data = $facebook-&gt;api("/{$album_id}/photos", 'post', $args);
</code></pre>

<p>The closest thing we can do then is to construct a Facebook link which suggests the user should set the uploaded image as their Timeline Cover:</p>

<pre><code>// $data['id'] is the image's Facebook ID 
$fb_image_link = "http://www.facebook.com/" . $username . "?preview_cover=" . $data['id'];
</code></pre>

<h2>Done</h2>

<p>There we go. Minimal development required to create a web app with very little demand on the user that gives them a Nokia Map on their Facebook profile. Not too bad for a Sunday afternoon.</p>

<p><a href="http://covermap.me">Go try it out</a> and let me know what you think.</p>

<p><p>The code is now <a href="https://github.com/thingsinjars/CoverMapMe">available on GitHub</a></p></p>
      </div>
]]></description>
<pubDate>Sat, 29 Sep 2012 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Web Audio</title>
<link>http://thingsinjars.com/post/458/web-audio/</link>
<guid>http://thingsinjars.com/post/458/web-audio/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-458">
        <p><a href="http://thingsinjars.com/post/458/web-audio/">Web Audio</a></p>
<p>I'm getting a bit obsessed with the <a href="http://en.wikipedia.org/wiki/HTML5_Audio#Web_Audio_API">Web Audio API</a> just now. That's not a bad thing, of course, I just wish the <a href="http://html5test.com/compare/feature/webaudio-webaudio.html">browsers would all catch up</a>.</p>

<p><a href="http://thingsinjars.com/post/459/sounds-like-a-hackathon/">Ages ago</a>, I mentioned the <a href="http://soundscape.nodester.com/">SoundScape</a> maps mashup <a href="http://marcon.me/">Max</a> and I made at the 5apps hackathon. Finally, here's the video of the two of us presenting it at a Nokia Berlin Tech Talk.</p>

<ul>
<li><a href="https://vimeo.com/46217788">Web Audio intro and SoundScape</a></li>
</ul>

<h2>Creative tutorials</h2>
<p>This goes along with the series of <a href="http://creativejs.com/resources/">Web Audio API introductory tutorials</a> I'm writing over at <a href="http://creativejs.com">CreativeJS</a>.</p>      </div>
]]></description>
<pubDate>Mon, 23 Jul 2012 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Create a draggable file on-the-fly with JS</title>
<link>http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/</link>
<guid>http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-440">
        <p><a href="http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/">Create a draggable file on-the-fly with JS</a></p>
<p>Here's a useful little code snippet if you're building a web application. It's a simple way of making the boundary between web-browser and platform a bit smaller. It allows you to create a file (text, html, whatever) in in your page which the user can drag onto their desktop (if their browser supports the dragstart event and dataTransfer methods).</p>

<pre><code>document.getElementById('downloadElement').addEventListener("dragstart", function (e) {
  e.dataTransfer.setData("DownloadURL", "text/html:filename.html:data:image/png;base64," + btoa(fileContent));
});
</code></pre>

<p>A description of the code:</p>
<ul>
 <li>attach an event listener to the draggable element you specify (<code>downloadElement</code>)</li>
<li>when you start to drag it (<code>dragstart</code>),</li>
<li>it creates a dataTransfer object (with the type <code>DownloadURL</code>)</li>
<li>and sets the content of that to be whatever you pass it (<code>fileContent</code>)</li>
<li>It uses <code><a href="https://developer.mozilla.org/en/DOM/window.btoa">btoa()</a></code> to encode the string data as a base64-encoded string.</li>
<li>When you combine this with the MIME-type (<code>text/html</code>),</li>
<li>you can create a file with the specified name (<code>filename.html</code>) when the user releases the drag in their local file system.</li>
<li>The fake MIME-type (<code>image/png</code>) is there as part of the object data to convince the browser this is a binary file (which it is, even though it's not an image).</li>
</ul>

<p>Note: The element this is attached to (<code>downloadElement</code> above) should either be draggable by default (image, link or text selection) or have the draggable attribute set otherwise this'll do nothing.</p>

<p>Credit goes to <a href="http://paul.kinlan.me/">Paul Kinlan</a> for using this in <a href="http://appmator.appspot.com/">Appmator</a> which is where I first saw this done this way. He actually uses it alongside some extremely clever JS zip-file creation stuff, too, it's definitely worth digging through the source there.</p>

<p>You can find out more about the drag events on the <a href="https://developer.mozilla.org/En/DragDrop/Drag_Operations">MDN</a>.</p>      </div>
]]></description>
<pubDate>Thu, 08 Dec 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Simple and clever beats clever</title>
<link>http://thingsinjars.com/post/439/simple-and-clever-beats-clever/</link>
<guid>http://thingsinjars.com/post/439/simple-and-clever-beats-clever/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-439">
        <p><a href="http://thingsinjars.com/post/439/simple-and-clever-beats-clever/">Simple and clever beats clever</a></p>
<p>When messing about with another little game idea, I found myself retyping (for the umpteenth time) the same little bit of value bounding code I use a lot:</p>

<pre><code>var x = Math.max(0, Math.min(y, 1))</code></pre>

Which basically translates to:

<pre><code>"Set x to be the value of y as long as it's between 0 and 1. 
If not, set it to 
  0 if it's smaller or 
  1 if it's larger."</code></pre>

<p>Of course, 0 and 1 don't need to be the boundaries, I'm just using them for convenience.</p>

<p>Instead of continuing with the game, I decided to take a little tangent and see if there was any way I could rewrite this so that the syntax was a bit more obvious. I'd like to be able to use syntax like:</p>

<pre><code>x = [0 &lt; y &lt; 1]</code></pre>

<p>to mean the same. Written exactly as above, JS will try and evaluate left-to-right, changing the comparisons to booleans. The statement would become</p>

<pre><code>y = 0.5

x = [0 &lt; y &lt; 1]
x = [0 &lt; 0.5 &lt; 1]
x = [true &lt; 1]
x = [false]</code></pre>

<p>Similarly:</p>

<pre><code>y = -0.5

x = [0 &lt; y &lt; 1]
x = [0 &lt; -0.5 &lt; 1]
x = [false &lt; 1]
x = [true]</code></pre>

<p>My first thought was to be clever about it, I wanted to try and figure out how to partially evaluate the expression and take the different outcomes to figure out the logic required. If '0 < y' was false, then y is less than zero therefore outside our bounds, the return value should then be 0. If the first part is true and the second is false then we know the value is higher than our bounds....etc and so on.</p>

<p>This proved to be a logical dead-end as there was no good way to partially evaluate the statements. Not without preparsing the JS, anyway. Which leads me onto the second attempt...</p>

<h2>Preparsing the JS</h2>

<p>The next attack on the problem was the idea of reading the JS as a string, shuffling it around quickly and silently (not like a ninja, more like a speedy librarian in slippers) and put it back where it was.</p>

<p>So I began to look at ways to recreate that. I remembered from many, many years ago (two, actually) <a href="http://alexsexton.com/" title="AlexSexton.com">Alex Sexton</a> creating the genius abomination that is <a href="http://summerofgoto.com/" title="The Summer of Goto | Official Home of Goto.js">goto.js</a> and how that used some kind of preparsing. A quick skim through the code later and I ended up on <a href="http://james.padolsey.com/" title="Home &ndash; James Padolsey">James Padolsey's site</a> looking at <a href="https://github.com/padolsey/parseScripts">parseScripts.js</a>.</p>

<p>In the end, all I needed to do was include parseScripts (which is a generalised form of the code I ended up using for the <a href="http://thingsinjars.com/post/424/whitehat-syndication/" title="">whitehat SEO question</a> from last month) and provide a new parser function and script type.</p>

<pre><code>parseScripts(/:bound/, function(unparsed) {
 return unparsed.replace(/\[(\d)\s*&lt;\s*(\w)\s*&lt;\s*(\d)\]/g, "Math.max($1, Math.min($2, $3))");
})</code></pre>

<p>I'm not saying parseScript isn't clever because it most definitely is but I am saying it's simple. There's not always a need to branch off into deep technical investigations of partial evaluation when a simple search-and-replace does the job better and faster.</p>

<p>For someone always going on about bringing simplicity and pragmatism into development, you'd think I'd have gotten there faster...</p>

<h2>Bounded Range</h2>
<p>The final <a href="http://thelab.thingsinjars.com/bounded/">bounded range syntax code is available here</a> (hint: view the console). It's silly but it was a fun half-hour.</p>

<h2>Improvements?</h2>
<p>Do you know of any better way to do this? Is there a clever parsing trick we can use instead? Is there, indeed, any language which has this syntax?</p>
      </div>
]]></description>
<pubDate>Sat, 03 Dec 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Poor man's touch interface</title>
<link>http://thingsinjars.com/post/433/poor-mans-touch-interface/</link>
<guid>http://thingsinjars.com/post/433/poor-mans-touch-interface/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-433">
        <p><a href="http://thingsinjars.com/post/433/poor-mans-touch-interface/">Poor man's touch interface</a></p>
<p>Here's a little code snippet for today.</p>

<p>While I was making the <a href="http://thingsinjars.com/post/434/super-mario-kart-css/">3D CSS Mario Kart</a>, I needed a simple, drop-in bit of code to handle touch interfaces. I looked through some old experiments and found a rough version of the code below. It was based on this <a href="http://stackoverflow.com/questions/3691461/remove-key-press-delay-in-javascript">KeyboardController</a> by Stack Overflow user <a href="http://stackoverflow.com/users/18936/bobince">Bob Ince</a>.</p>

<p>It doesn't do anything clever. All it does is provide a simple way to attach functionality to touch events in different areas of the screen &ndash; top-left, top-center, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-center, bottom-right. My apologies to any Brits for the spelling of centre as 'center'. It's the Internet, we have to.</p>

<h2>How to use</h2>
<p>Include this code:</p>
<pre><code>
function TouchController(areas, repeat) {
  var touchtimer;
  document.onmousedown = document.ontouchstart = document.ontouchmove = function(e) {
    var position;
    e.preventDefault();
    e.touches = [{&#x27;clientX&#x27;:e.pageX,&#x27;clientY&#x27;:e.pageY}];
    switch(true) {
    case (e.touches[0].clientY&lt;window.innerHeight/3) : 
        position = &#x27;top&#x27;;
        break;
    case (e.touches[0].clientY&gt;(2*window.innerHeight)/3) : 
        position = &#x27;bottom&#x27;;
        break;
    default : 
        position = &#x27;middle&#x27;;
        break;
    }
    position+=&#x27;-&#x27;;
    switch(true) {
    case (e.touches[0].clientX&lt;window.innerWidth/3) : 
        position += &#x27;left&#x27;;
        break;
    case (e.touches[0].clientX&gt;(2*window.innerWidth)/3) : 
        position += &#x27;right&#x27;;
        break;
    default : 
        position += &#x27;center&#x27;;
        break;  
    }

    if (!(position in areas)) {
      return true;
    }

    areas[position]();
    if (repeat!==0) {
      clearInterval(touchtimer);
      touchtimer= setInterval(areas[position], repeat);
    }
    return false;
  };
  // Cancel timeout
  document.onmouseup = document.ontouchend= function(e) {
  clearInterval(touchtimer);
  };
};
</code></pre>

<p>Now, all you need to do to attach a function to a touch event in the top-left area of the screen is:</p>
<pre><code>TouchController({
  'top-left': function() { topLeftFunction();}
}, 20);
</code></pre>

<p>I use this for direction control in the Mario Kart experiment which maps exactly onto the cursor keys used for the normal control.</p>
<pre><code>TouchController({
  'top-left': function() {  // UP + LEFT
				drawMap.move({y: 2}); 
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1) 
			  },
  'top-center': function() {  // UP
				drawMap.move({y: 2}); 
			  },
  'top-right': function() {  // UP + RIGHT
				drawMap.move({y: 2}); 
				drawMap.move({z: drawMap.z - 2}); 
				drawMap.sprite(1) 
			  },

  'middle-left': function() {  // LEFT
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1) 
			  },
  'middle-right': function() {  // RIGHT
				drawMap.move({z: drawMap.z - 2});
				drawMap.sprite(1) 
			  },

  'bottom-left': function() {  // DOWN + LEFT
				drawMap.move({y:  - 2}); 
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1)  
			  },
  'bottom-center': function() { 
				drawMap.move({y:  - 2}); 
			  },
  'bottom-right': function() {  // DOWN + RIGHT
				drawMap.move({y:  - 2}); 
				drawMap.move({z: drawMap.z - 2}); 
				drawMap.sprite(1)  
			  },
}, 20);
</code></pre>

<p>If you need anything clever or you need two or more touches, you should use something else. This is just a simple drop-in for when you're copy-paste coding and want to include touch-screen support.</p>
      </div>
]]></description>
<pubDate>Thu, 17 Nov 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>That Version-y Control-y Stuff</title>
<link>http://thingsinjars.com/post/431/that-version-y-control-y-stuff/</link>
<guid>http://thingsinjars.com/post/431/that-version-y-control-y-stuff/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-431">
        <p><a href="http://thingsinjars.com/post/431/that-version-y-control-y-stuff/">That Version-y Control-y Stuff</a></p>
<p>If you&rsquo;re reading this site, you&rsquo;re probably not a beginner. The following article is probably beneath you. Go on, read it anyway.</p>
<p>Just in case you don&rsquo;t know, a Version Control System (VCS) is pretty much the most important thing ever in the history of anything ever. Just think about it conceptually: the ability to stand back and look at everything you&rsquo;ve ever done, choose the good bits, drop the bad bits, mop up the mistakes… it gives you the freedom to “Play with it ‘til it breaks” with the safety net that you can always go back and fix it again.</p> 
<p>You Get To Play With Time Itself!</p>
<p>There are many, many debates about the different methodologies you can use with version control and which technologies are best suited to which methodologies and which interfaces are best suited to which technologies and so on ad nauseam. The main concepts of working with any VCS are essentially the same, however.</p>
<ol>
<li>It must be almost invisible.</li>
<li>It must be completely reliable</li>
<li>You mustn&rsquo;t rely on it</li>
</ol>
<h2>It must be almost invisible</h2>
<p>If you have never used a VCS before, it must fit perfectly into your workflow otherwise you won&rsquo;t do it. It isn&rsquo;t until you&rsquo;ve been saved from potential disaster by a system that you will truly appreciate it and see the value in working it into your process. If you have or are currently using a VCS, think about when and how you use it. Does it require launching a new application or does it run in the background? Do you have to manually check things in or is it seamless versioning? The more effort required to mark a version, the less often you&rsquo;ll do it as it breaks the flow of development</p>
<p>On the other hand, if the process is completely invisible, you might forget it&rsquo;s there. It&rsquo;s exactly the same as <a href="http://thingsinjars.com/post/408/workflow-the-flow-of-work/">assuming your changes are going live on the server</a> &ndash; the moment you assume it happens, it doesn&rsquo;t. You still need some level of manual checking.</p>
<h2>It must be completely reliable</h2>
<p>This is fairly obvious, hopefully. You need the security that your version system is working otherwise you might again be tempted to miss it out – why take the extra step required to version a file if it&rsquo;s not going to be there when I need it?</p>
<p>If you&rsquo;re hosting your own repositories internally to your organisation, don&rsquo;t put it on a server older than you are. The safest route to go down is contracted external hosting. That way, it&rsquo;s someone&rsquo;s job to make sure your datums are secure.</p>
<h2>You mustn&rsquo;t rely on it</h2>
<p>Always have a backup. Always have a copy. Always have an escape route. Or something. You should have picked up the theme by now. Version Control Systems are great but as soon as it is the only thing standing between you and a complete failure to deliver a project, it will fail. Or not. It&rsquo;s funny like that.</p>      </div>
]]></description>
<pubDate>Tue, 08 Nov 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Copy-paste coding</title>
<link>http://thingsinjars.com/post/430/copy-paste-coding/</link>
<guid>http://thingsinjars.com/post/430/copy-paste-coding/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-430">
        <p><a href="http://thingsinjars.com/post/430/copy-paste-coding/">Copy-paste coding</a></p>
<p>This weekend, I had a spare couple of hours on Saturday night (as often happens when you have a kid) so I decided to pass the time with a bit of copy-paste coding.</p>

<p>I grabbed a bit of <a href="http://banditracer.eu/carexample/">example code for a top-down racing game</a> built using <a href="http://www.box2d.org/">Box2d</a> and <a href="http://gamejs.org/">GameJs</a>. I then grabbed a <a href="http://maps.google.com/">Google Maps</a> demo and a <a href="http://maps.nokia.com/">Nokia Maps demo</a> and smooshed them together. I've seen a few racing games before so I know there's nothing innovative here, it's just a bit of silliness.</p>

<h2>The results</h2>
<ul>
 <li><a href="http://thelab.thingsinjars.com/car2d/index-ovi.html">Driving on Nokia Maps</a></li>
 <li><a href="http://thelab.thingsinjars.com/car2d/index.html">Driving on Google Maps</a></li>
</ul>

<h2>Copy-Paste: Not a bad thing</h2>
<p>There are many developers who will tell you that blindly copy-pasting is a terrible way to code. They make the valid points that you don't understand something if you don't read it properly and that you'll end up stuck down an algorithmic cul-de-sac with no way to three-point-turn your way out (although they may phrase it differently). These are valid points but...</p>

<p>If I'd sat down on Saturday night and thought "I want to build something in Box2D" then gone to the site, downloaded the library, read the docs and loaded the examples, by the time I had understood what I was doing, Sunday morning would have come round and I'd still have GameJS to read up on. There's absolutely no harm in blindly catapulting yourself a long way down the development track then looking round to see where you are. Sure, you'll end up somewhere unfamiliar and you may end up with absolutely no clue what the code around you does but at least you have something to look at while you figure it out. At least a few times, you'll find something almost works and a quick search of the docs later, you've figured it out and know what it's doing.</p>

<p>Basically, copy-pasting together a simple little demo and making it work is a lot more interesting than taking baby-steps through example code and beginner tutorials. Don't be too careful about trying to build something complicated.</p>

<h2>An Idea</h2>
<p>If you're in the mood for copy-paste coding, try taking the two demos above (Google and Nokia), grab the node.js server from the <a href="http://thingsinjars.com/post/412/multi-user-pages/">multi-user page experiment</a> and figure out how to have multiple racers on the same map (by transmitting angle and geo-coords).</p>      </div>
]]></description>
<pubDate>Mon, 31 Oct 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>You must be able to read before you get a library card</title>
<link>http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/</link>
<guid>http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-416">
        <p><a href="http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/">You must be able to read before you get a library card</a></p>
<p>I like JavaScript. JS. ECMAScript. Ol' Jay Scrizzle as nobody calls it.</p>

<p>I also like <a href="http://jquery.com/">jQuery</a>. jQ. jQuizzie. jamiroQuery. Whatever.</p>

<p>Ignoring the stoopid nicknames I just made up, did you notice how I referred to JavaScript and jQuery separately? I didn't say "I like JavaScript, there are some really great lightbox plugins for it" just the same as I didn't say "I wish there was a way to do indexOf in jQuery".</p>

<p>I'm regularly amazed at how many new (and some not-so-new) web developers either think they know JavaScript because they know jQuery or wish there was a way to do something in jQuery that they read about in an article about JavaScript. jQuery is a <em>library</em> written to make coding in JavaScript easier. It's made in JavaScript so you can say "jQuery is JavaScript" but only in the same way that "Simon is male". To confuse jQuery as all of JavaScript is the same as saying "Simon is all men" (don't worry, there's still only one of me).</p>

<p>For most web site or web app development, I do recommend using a library. Personally, I've used jQuery and <a href="http://www.prototypejs.org/">Prototype</a> extensively and decided I prefer jQuery. Libraries are designed to make coding faster and more intuitive and they can be a great productivity aid. You can get a lot more done quicker. There is a downside, however.</p>

<h2>Downside</h2>
<p>If you're doing what the library was intended to help with, great. Slide this panel up, pop open a modal window, scroll to the bottom of the page and highlight that header. Brilliant. The difficulties come when you're either trying to do something the library wasn't intended to do or something nobody's thought of before or you're just plain doing something wrong. If you are fluent in your library of choice but don't know the JavaScript underpinnings, your usual debugging tools can only help you so far. There will come a point where there's an impenetrable black-box where data goes in and something unexpected comes out. Okay, it's probably still data but it's unexpected data.</p>

<p>Don't let this point in the process be the discouragement. This is where the fun bit is.</p>

<h2>Learning to read</h2>
<p>Library authors are very clever groups of people. Often large groups. Reading through the unminified source of a library can be an awesomely educational experience as it's usually the culmination of many years best practice. If you want a nice introduction to some of the cool things in jQuery, for instance, check out these videos from <a href="http://paulirish.com/">Paul Irish</a>:</p>

<ul><li><a href="http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/">http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/</a></li>
<li><a href="http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/">http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/</a></li></ul>

<p>I've dug around in jQuery many, many times to try and figure out why something does or doesn't do what it should or shouldn't. The most detailed investigation was probably <a href="http://thingsinjars.com/post/371/investigating-ies-innerhtml/">Investigating IE's innerHTML</a> during which nothing was solved but I found out some cool stuff.</p>

<h2>Learning to write</h2>
<p>The best way to get your head around libraries is to write your own. Yes, there are literally millions of them (not literally) out there already but you don't need to aim for world dominance, that's not the point of writing your own. Start simply, map the dollar symbol to <code>document.getElementById</code>. Done. You've written a tiny library. </p>

<pre><code>function $(id){ 
    return document.getElementById(id);
}</code></pre>

<p>Now you can add some more stuff. Maybe you could check to see if the thing passed to the $ is already an element or if it's a string. That way, you could be a bit more carefree about how you pass things around.</p>

<pre><code>function $(id){ 
  if(id.nodeType) {
    return id;
  } else {
    return document.getElementById(id);
  }
}</code></pre>

<p>Add in a couple of AJAX methods, some array manipulation and before you know it, you've got a full-blown web development toolkit. </p>

<p>If you're wanting a boilerplate to start your library off, I recommend Adam Sontag's <a href="https://github.com/ajpiano/boilerplate-boilerplate">Boilerplate Boilerplate</a>.</p>

<h2>Here's your Library Card</h2>
<p>By now, you've rooted around in the jQuery undergrowth, dug through some of Moo's AJAX and pulled apart Prototype's string manipulation. You've written your own mini library, gotten a bit frustrated and wished you had a community of several thousand contributors to make it more robust. Now you're ready to start getting irked every time someone on <a href="http://forrst.com">Forrst</a> asks if there's a jQuery plugin for charAt. Enjoy.</p>
<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Thu, 04 Aug 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Workflow. The flow. Of work.</title>
<link>http://thingsinjars.com/post/408/workflow-the-flow-of-work/</link>
<guid>http://thingsinjars.com/post/408/workflow-the-flow-of-work/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-408">
        <p><a href="http://thingsinjars.com/post/408/workflow-the-flow-of-work/">Workflow. The flow. Of work.</a></p>
<h2>How to actually work</h2>
<p>Don&rsquo;t tell anyone (particularly not your clients and especially not my clients) but making websites is really very easy. Don't make it harder by deliberately hindering yourself. You should always try to travel the shortest distance between &ldquo;amends needs done&rdquo; and &ldquo;amend is done&rdquo;. Again, I hear a &ldquo;Pah!&rdquo; in the distance, &ldquo;Well, that&rsquo;s obvious.&rdquo;, but is it? Are you sure you&rsquo;re ‘Being all you can be&rsquo;?</p>
<h2>The shortest distance</h2>
<p>Okay, picture the scene: you've run out of socks. You need to put on a load of washing. The washing is in a pile in the corner of the room. You hunch over, pick up all the socks, pants, t-shirts and walk, waddle and totter to the washing machine. As you walk, you drop a sock and bend down to pick it up, dropping another. You recover that one and another falls. Eventually, you make it to the washing machine after a few minutes, put everything in, throw in some powder and set it going. As you head back to your bedroom, you spot three more socks that you missed. Darn.</p>
<p>Okay, picture the scene: you've run out of socks. You need to put on a load of washing. Fortunately, every time you took your socks off, you put them straight in the washing machine. You wander to the kitchen, put in the powder and switch it on. Done.</p>
<p>Any time you try to do anything, the more steps involved between intention and completion, the more likely it is to go wrong. Whether the intention is 'wear clean socks' or 'update this website', if you can do it in a handful of steps, you'll make fewer mistakes than if you have to do it in a hunched-over armful.</p>
<h2>Workflow. The flow. Of Work.</h2>
<p>The next time you're making an amend somewhere, watch yourself. Watch which applications you jump between. Don't just make your changes, pay attention to how you do them. Are you jumping between text editor and FTP client? Text editor and web browser? FTP and Subversion? Just take a few minutes to think about which steps you might be able to miss out. For instance, if you use Textmate and Transmit, you can set up DockSend so that pressing ctrl-shift-f then 2 will upload the file you currently have open to the same place on the server. You can now change the editor↔FTP↔browser cycle to editor↔browser.</p>
<h2>However...</h2>
<p>Seamless does not imply flawless. Don't be tempted to simplify to the stage where you don't need any interaction between making a change and the change being live. If you rely on the fact that your changes 'just happen', you might be tempted not to check. That's the point at which they don't 'just happen'.</p>
<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Fri, 28 Oct 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Testing</title>
<link>http://thingsinjars.com/post/406/testing/</link>
<guid>http://thingsinjars.com/post/406/testing/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-406">
        <p><a href="http://thingsinjars.com/post/406/testing/">Testing</a></p>
<h2>The web is a visual medium. Well, mostly.</h2>
<p>There's no better way to test a visual medium than by looking at it. Look at your site in as many browsers as you can. If you've already got as many browsers installed on your development computer as you can fit, get another computer and install some more. Either that or run a Virtual Machine.</p>


<h2>Definition: Virtual Machine (VM)</h2>
<p>Applications like VirtualBox, VMWare or Parallels allow you to run an entire computer within your computer. It is a self-contained system that doesn't interact with your own machine meaning you can have IE6 installed on one VM, IE7 on another and IE8 on a third. All running in a window on your iMac. Shiny.</p>


<p>If you can't do that easily, you could use one of the growing number of browser testing services. These are server rooms packed with computers running Virtual Machines and automated systems to which you supply a URL, wait a few moments and get shown an image (or several hundred images) showing your URL in different browsers on different platforms. Some of the more sophisticated services allow you to scroll down a long page or specify different actions, text entry or mouse events you want to see triggered. These services can be exceptionally useful when it comes to developing HTML e-mails as there are some rare and esoteric e-mail clients out in the wild. <a href="http://litmus.com/">Litmus</a> does an excellent job at virtualised testing for HTML e-mails. On that note, the Campaign Monitor <a href="http://www.campaignmonitor.com/templates/">library of free HTML e-mail templates</a> is a great place to start, learn and possibly finish when working on an HTML e-mail.</p>

<p>There is also a place for automated testing for some things. Recently, there has been a bit of a movement away from validating code as the purpose of web development is not to make it 'check a box' on a merely technical level, it is to get the message across via the design however possible. However, validation is still the best and easiest way to check your syntax. Syntax errors are still the main cause for mistakes appearing in your web sites and are the easiest thing to fix. Don't assume IE is wrong. Again, if you're keen on HTML e-mails, here's a <a href="http://litmus.com/blog/validating-html-for-email">great post on the Litmus blog</a>.</p>

<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Fri, 09 Sep 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Don’t be seduced by the drag-and-drop side</title>
<link>http://thingsinjars.com/post/405/dont-be-seduced-by-the-drag-and-drop-side/</link>
<guid>http://thingsinjars.com/post/405/dont-be-seduced-by-the-drag-and-drop-side/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-405">
        <p><a href="http://thingsinjars.com/post/405/dont-be-seduced-by-the-drag-and-drop-side/">Don’t be seduced by the drag-and-drop side</a></p>
<p>You don&rsquo;t have to be a survivor of the vi and Emacs holy wars to appreciate the beauty of fully hand-crafted code. There was a bit of attention a couple of weeks ago on the soon-to-be-launched <a href="http://muse.adobe.com/">Adobe Muse</a> which lets you &ldquo;Design and publish HTML websites without writing code&rdquo;. If you want to be a kick-ass developer, you must realise that tools like this aren't designed for you. They're designed for people who want to do what you can do but either don't have the time or the inclination to learn how. Although drag 'n' drop application do lower the barrier to entry for creating a website, there is still a need for web developers to know exactly what's going on in their pages.</p>

<p>I'm not saying that there will never be a time when visual design can be automatically translated into as good a product as a hand-crafted site, I'm just saying it&rsquo;s not yet.</p>

<p>In much the same way as with JavaScript (See &ldquo;<a href="http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/">You must be able to read before you get a library card</a>&rdquo;), building your HTML using that extra level of abstraction might work for almost every situation but will eventually leave you stuck somewhere you don&rsquo;t want to be. By all means, pimp up your text editor with all manner of handy tools, shortcuts and code snippets but make sure you still know exactly what each bit of mark up means and does. If you structure your code well (more on that in a later post), your natural feel for the code will be as good a validator as anything automated (by which I mean prone to errors and worth double-checking).</p>

<p>Learn the keyboard shortcuts. If you learn nothing else from this, learn the importance of keyboard shortcuts. You might start off thinking you'll never need a key combination to simply swap two characters around but one day, you'll find yourself in the middle of a functino reaching for ctrl-T.</p>

<p>Also, there is no easy way to tell if a text editor is fit for you until you have tried it, looking at screenshots won&rsquo;t work. You don't need to build an entire project to figure out whether or not you're going to get on with a new text editor, just put together a couple of web pages, maybe write a jQuery plugin. Do the key combinations stick in your head or are you constantly looking up the same ones again and again? Do you have to contort your hand into an unnatural and uncomfortable claw in order to duplicate a line?</p>

<p>The final thing to cover about text editors is that it's okay to pay for them. Sure, we all love free software. &ldquo;Free as in pears <em>and</em> free as in peaches&rdquo; (or whatever that motto is) but there are times when a good, well-written piece of software will cost money. And that's okay. You're a web developer. You are going to be spending the vast proportion of your day using this piece of software. If the people that made it would like you to spend $20 on it, don't instantly balk at the idea. Think back to the idea of web developers as artisan craftsmen. You're going to be using this chisel every day to carve out patterns in stone. Every now and then, you might need to buy your own chisel.</p>

<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Mon, 29 Aug 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>HTML5 for Large Public Bodies</title>
<link>http://thingsinjars.com/post/382/html5-for-large-public-bodies/</link>
<guid>http://thingsinjars.com/post/382/html5-for-large-public-bodies/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-382">
        <p><a href="http://thingsinjars.com/post/382/html5-for-large-public-bodies/">HTML5 for Large Public Bodies</a></p>
<h2>Your country needs you...</h2>

<p>...to stand at the cutting edge of technology.</p>

<p>Sounds awfully impressive, don't you think?</p>

<p>There are quite a few regulations to bear in mind and comply with when developing a website for a Government organisation or any large public body. This has lead to a lot of sites being developed in a very defensive manner, ensuring safe compliance at the expense of a great and consistent user experience.</p>

<p>This video features a presentation about how large publicly-liable institutions should and can embrace the latest in web technologies without sacrificing standards. By embracing them, in fact.</p>

<p>The content of this was developed while planning and building the <a href="http://www.nms.ac.uk/">National Museums Scotland website</a> which launched last November. The messages presented are applicable to museums, galleries, swimming pools, councils, anywhere, really.</p>

<p>If you're a techie person in the cultural or government sector, you might find this useful in convincing others to take advantage of the latest cool (and useful) technologies.</p>

<h2>Video</h2>
<p><a href="http://vimeo.com/24436131">HTML5 for Large Public Bodies</a> from <a href="http://vimeo.com/madine">Simon Madine</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

<h2>Links from the presentation</h2>
<ul>
<li><a href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">PolyFills</a></li>
<li><a href="http://www.netmagazine.com/features/making-html5-and-css3-work-polyfills-and-shims">.NET magazine article</a></li>
<li><a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills">(Almost) complete list of polyfills</a></li>
<li><a href="http://diveintohtml5.org/">Dive into HTML5</a></li>
<li><a href="http://html5boilerplate.com/">HTML5 Boilerplate</a></li>
<li><a href="http://www.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a></li>
<li><a href="http://html5doctor.com/">HTML5 Doctor</a></li>
<li><a href="http://alpha.gov.uk/">AlphaGov</a></li>
</ul>

<h2>Slideshow</h2>
<p>The source for the slides is <a href="http://thingsinjars.com/widgets/html5-presentation/">available online</a> although it's mostly webkit-friendly. I realise the irony of a presentation about cross-platform HTML5 not being a great example itself of that but it does degrade adequately. If I get the time in the future, I'll tidy it up. An actual good (and relevant) example of cross-platform web technologies is the <a href="http://www.nms.ac.uk/">National Museums Scotland website</a> itself which performs fantastically across all manner of platforms.</p>      </div>
]]></description>
<pubDate>Tue, 31 May 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>Psychopathic megalomaniac vs Obsequious sycophant?</title>
<link>http://thingsinjars.com/post/380/psychopathic-megalomaniac-vs-obsequious-sycophant/</link>
<guid>http://thingsinjars.com/post/380/psychopathic-megalomaniac-vs-obsequious-sycophant/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-380">
        <p><a href="http://thingsinjars.com/post/380/psychopathic-megalomaniac-vs-obsequious-sycophant/">Psychopathic megalomaniac vs Obsequious sycophant?</a></p>
<h2> - or - </h2>
<h2>Tabs vs Spaces?</h2>
<p>Which are you? Is there any middle ground?</p>

<p>In any modern, code-friendly text editor, you can set tab size. This means that one tab can appear to be as wide as a single space character or - more commonly - 2 or 4 spaces. It's even possible in some to set any arbitrary size so there's nothing stopping you setting tabs to be 30 spaces and</p>
<pre><code>format() {
                              your code() {
                                                            like;
                              }
                              this;
}</code></pre>

<p>However you do it, the point is that using tabs allows the reader personal preference.</p>

<p>Indenting your code using spaces, however, is completely different. A space is always a space. There's actually a simple conversion chart:</p>

<ul>
<li>1 = One</li>
<li>2 = Two</li>
<li>3 = Three</li>
<li>and so on.</li>
</ul>
<p>The fundamental difference here is that the person reading the code has no choice about how it's laid out. Tabs means you get to read the code how <em>you</em> want to, spaces means you read the code how <em>I</em> want you to. It's a subtle difference but an important one. </p>

<p>Space indenting is therefore perfectly suited to psychopathic megalomaniacs who insist their way is right while tab indenting is for obsequious sycophants who are putting the needs of others above themselves. Sure, there may be lots of grades in-between but why let moderation get in the way of a barely coherent point?</p>

<p>
Curiously, neither of these extremes feels a great need to comment their code. One sees no need as their code is for themselves and they already understand it, the other assumes that if they can understand it, its purpose is so obvious as to be trivial. Both are wrong here.</p>

<p>There's unfortunately no real middle ground here. Teams must agree amongst themselves what side of the fence they fall down on. It is entirely possible to set many text editors to automatically convert tabs to spaces or spaces to tabs on file save but if you're doing that, you'd better hope your favourite diff algorithm ignores white space otherwise version control goes out the window.</p>
<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Mon, 25 Jul 2011 00:00:00 GMT</pubDate>
<category>guides</category>
</item><item>
<title>The quest for Extreme JavaScript Minification</title>
<link>http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/</link>
<guid>http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-293">
        <p><a href="http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/">The quest for Extreme JavaScript Minification</a></p>
<p>As <a href="http://blah.thingsinjars.com/post/292/elementally-my-dear-javascript/" title="Elementally, my dear JavaScript">described in detail previously</a>, I've recently taken part in the <a href="http://js1k.com">JS1K</a> competition where you have to squeeze something cool and clever into 1024 bytes of JavaScript. The quest to condense has become quite addictive and I found myself obsessing over every byte. This is the kind of stuff that the <a href="http://code.google.com/closure/compiler/">Closure Compiler</a> does quite well automatically but there are some cases where you just need to get in there and manually tweak.</p> 

<p>Here are some of the tricks I've picked up in my struggle for extreme minification:</p>

<h2>Basic improvements</h2>
<h3>Use short variable names.</h3> 
<p>This one's fairly obvious. A more useful addition to this is:</p>
<h3>Shorten long variable names.</h3>
<p>If you're going to be accessing an element more than once, especially if it's a built-in element like 'document', you'll save a few bytes every time you reference it if you create a shortened reference to it.</p>
<pre><code class="prettyprint">  document.body.style.overflow="hidden"
  document.body.style.background="red"
  (74 characters)
</code></pre>
<p>can shorten to</p>
<pre><code class="prettyprint">  d=document;b=d.body;s=b.style;
  s.overflow="hidden";
  s.background="red"
  (69 characters)
</code></pre>
<p>and any references to <code class="prettyprint">s</code> after are going to save 19 characters every time.</p>
<h3>Remove whitespace</h3>
<p>This one's so obvious, I don't need to mention it.</p>
<h3>Set Interval</h3>
<p>The extremely handy <code class="prettyprint">setInterval</code> function can take either a function or a string. If you give it an anonymous function declaration:</p>
<pre><code class="prettyprint">  setInterval(function(){x++;y--},10);
</code></pre>
<p>You will use up more characters than if you give it just the inside of the function as a string:</p>
<pre><code class="prettyprint">  setInterval('x++;y--',10);
</code></pre>
<p>But the outcome will be the same.</p>

<h2>Little-used aspects</h2>
<p>Not many people use JavScript's scientific notation unless they're doing scientific stuff but it can be a great byte saver. The number <code class="prettyprint">100</code> is equivalent to <code class="prettyprint">1 * 10^2</code> which is represented in JavaScript as 1E2. That's not a great saving for 100 but 1000 is 1E3, 10000 is 1E4. Every time you go up a factor of 10, you save 1 byte.</p>


<h2>Fight your good style tendencies</h2>
<p>In the war against space, you have to bite the bullet and accept that you may need to sacrifice some of your hard-earned practices. But only this once. Don't get in to the habit, okay?</p>
<h3>No zeroes</h3>
<pre><code class="prettyprint">  0.5  = .5
</code></pre>
<p>Yeah, it looks ugly but it works and saves a byte.</p>
<h3>Naked clauses</h3>
<pre><code class="prettyprint">  if {
    :
    :
  } else y
</code></pre>
<p>The <code class="prettyprint">y</code> looks so naked out there. No braces to keep it warm. But if you only have one statement in your else clause, you don't need them...</p>
<h3>No semi-final. . . final-semi. . . Semi-colon. No final colon.</h3>
<p>You don't need a semi-colon on your last line, even if it does make it look as though you've stunted its growth.</p>

<h2>The final few bytes</h2>
<h3>Operator precedence</h3>
<p>You don't need brackets. Brackets are handy for you as the programmer to remember what's going on when and to reduce ambiguity but if you plan correctly, most of the time you won't need brackets to get your arithmetic to work out.</p>
<pre><code class="prettyprint">  b.getMilliseconds()/(a*250) 
      is the same as
  b.getMilliseconds()/a/250 
</code></pre>
<h3>Shorthand notation</h3>
<pre><code class="prettyprint">  l=l+1;l=l%14;
  l++;l%=14;
  l=++l%14;
</code></pre>
<p>The three lines above are equivalent and in order of bytes saved.</p>
<h3>Shorthand CSS</h3>
<p>If you need to set some CSS values in your script, remember to pick the most appropriate short form. Instead of <code class="prettyprint">s.background='black'</code>, use  <code class="prettyprint">s.background='#000'</code> but instead of <code class="prettyprint">s.background='#F00'</code>, use <code class="prettyprint">s.background='red'</code>. In the same vein, the statements <code class="prettyprint">margin="0px"</code> and <code class="prettyprint">margin=0</code> mean the same but the latter saves bytes.</p>

<h2>Don't be generic</h2>
<p>One final thing to mention is that these little challenges are not the norm. If you find yourself trying to squeeze code down like this you're probably working on a very specific project. Use that to your advantage and see if there are any savings to be made by discarding your usual policies on code reuse. In the JS1K challenge, we're provided with a specific <a href="http://js1k.com/demo">HTML page</a> and an empty script tag. One good saving made here (and mentioned in my previous post) was the way I grabbed the reference to the canvas element. The standard method is to use the id assigned to the canvas.</p>
<pre><code class="prettyprint">  d.getElementById('c')
</code></pre>
<p>Which is a good generic solution. No matter what else was on the page, no matter what order stuff was in, this would return the canvas. However, we have a very specific case here and the canvas is always going to be in the same place - the first child of the body element. That means we can do this instead:</p>
<pre><code class="prettyprint">  b.children[0]
</code></pre>
<p>This makes use of the reference we grabbed to the body earlier. If the page were rearranged, this would stop working but as it won't, we've saved 8 bytes.</p>

<h2>In conclusion</h2>
<p>Yes, this is all quite silly but it's also fun and tricky. Attempting these kinds of challenges keep us developers mindful of what it is we actually do and that makes it an extremely productive silly hobby.</p>      </div>
]]></description>
<pubDate>Sun, 08 Aug 2010 00:00:00 GMT</pubDate>
<category>guides</category>
</item></channel>
</rss>