<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stoat - Where? &#187; Code</title>
	<atom:link href="http://jamietalbot.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://jamietalbot.com</link>
	<description>Adventures in Engrish</description>
	<lastBuildDate>Sat, 29 Oct 2011 05:14:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>You Need A Montage</title>
		<link>http://jamietalbot.com/2011/01/31/you-need-a-montage/</link>
		<comments>http://jamietalbot.com/2011/01/31/you-need-a-montage/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 10:53:03 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[GraphicsMagick]]></category>
		<category><![CDATA[Image Manipulation]]></category>
		<category><![CDATA[ImageMagick]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[Montage]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=237</guid>
		<description><![CDATA[ImageMagick and GraphicsMagick are fantastic tools for manipulating images.  Here, I outline the montage sub-command and use it to tile two photos of differing dimensions, so that they can be easily aligned in a column format with other images.]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong> Check out an online montage creator that builds on this and adds a lot more!  <a href="http://jamietalbot.com/projects/graphics/montage">Montage Away</a>!</p>
<hr />
<p>My girlfriend Emily Benjamin is something of a special photographer and she is finally putting together a site to show off some of her great pieces.  Naturally, I put her onto WordPress.  Emily wants the photos to go front and centre, which is a fine idea, so we put together a very simple one-column theme based on QuickPic, which will be uncluttered and allow the photos to shine.</p>
<p>Problems arose when trying to lay out images though.  Many of the photos are cropped for emphasis and impact, and being different dimensions, laying them all out on one page can look messy.  This can be avoided by cheating a bit and pre-processing them in pairs and combining them into a single image, so that each constituent photos&#8217; heights match.  Arty people like because it allows for some cool dynamic looking layout.  It also helps reduce the amount of HTTP requests which techy people care about.</p>
<p>How though to generate these tiled images?  You could hand-crank one with GIMP, but that gets pretty boring after a couple of times.  There are also a couple of commercial products out there that could help, but that seems like cheating.  No, Team America said it best &#8211; <a href="http://www.youtube.com/watch?v=JU9Uwhjlog8">you need a montage</a>!  ImageMagick&#8217;s <a href="http://www.graphicsmagick.org/montage.html">montage</a> command to be precise.  (I happen to use GraphicsMagick, as ImageMagick was giving me insidious &#8220;Bus Errors&#8221; on my MacBook, but the same commands will work with both tools.)  [Image|Graphics]Magick are some of the finest free tools available, and a shining example of the power of both open source communities and command line applications.</p>
<p>We start with two fine images, <a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/bell.png">a church in Budapest</a> and <a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/lamppost.png">a view at sunset from the Ponte Vecchio, Florence</a>.  They&#8217;re both huge, because DSLRs now take photos at up to 20MB in JPEG format (!).  So, we need to shrink them down a little bit and glue them together with a bit of whitespace, ensuring that the whole resulting image is 800 pixels wide (our chosen width for the main column).  </p>
<p>The montage command makes this simple enough:</p>
<pre class="brush: bash; title: ; notranslate">
gm montage -geometry x800+5 -background yellow lamppost.png bell.png -resize 800 output.png
</pre>
<p>You&#8217;ll notice that I&#8217;ve made the background yellow, just so we can see where the borders are here.  The geometry parameter says to make sure each component image fits within 800px vertically, leaving a 5px border on each side.  We decided that we wanted a 10px internal space between the photos, so 5px on the side of each photo works nicely.  The -resize command at the end takes effect after the montage has been created and resizes the entire outputted image to 800px wide, preserving the aspect ratio.  This is the size of photos that has been chosen for the host site, but on this site with a narrower main column I&#8217;ve forced it to 500px.  You can click on the images to see them at full 800px size if you want to.  I&#8217;ve chosen to output it as a PNG.  The image looks like this:</p>
<p><a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output.png"><img src="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output.png" alt="First pass at tiling photos" title="Stage 1" width="500" /></a></p>
<p>That&#8217;s not a bad first go, but there&#8217;s plenty we can improve.  The sunset photo is narrower than the church photo, so it has been centred within its cell.  There&#8217;s also an extraneous border around the outside.  We handle these with two additional parameters, gravity and trim.  Gravity allows us to &#8216;pull&#8217; each photo in a given direction within its cell, and trim gets rid of a border, whatever colour it is.</p>
<p>For the gravity, we want to pull the left photo rightwards, and the right photo leftwards, so the central spacing is consistent.  We do that by specifying -gravity East for the first photo and -gravity West for the second.</p>
<pre class="brush: bash; title: ; notranslate">
gm montage -geometry x800+5 -background yellow -gravity East lamppost.png -gravity West bell.png -resize 800 output.png
</pre>
<p><a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output1.png"><img src="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output1.png" alt="Centralising the tiled images" title="Stage 2" width="500" /></a></p>
<p>That&#8217;s looking better, but now we just have to get rid of that outer border.  We do that using the -trim command, and at the same time I&#8217;m going to make the background colour transparent:</p>
<pre class="brush: bash; title: ; notranslate">
gm montage -quality 100 -geometry x800+5 -background transparent -gravity East lamppost.png -gravity West bell.png -trim -resize 800 output.png
</pre>
<p>Notice that I do the trim before the final resize.  ImageMagick commands are executed sequentially from left to right.  I&#8217;ve also added a -quality parameter to keep the quality of the final image high.  (In this case it&#8217;s probably too high, but we won&#8217;t worry about that.)  Our image now looks like this:</p>
<p><a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output2.png"><img src="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output2.png" alt="Removing the border" title="Stage 3" width="500" /></a></p>
<p>and it&#8217;s looking pretty groovy.  But what happens if we want to tile two photos of vastly differing heights?  The &#8216;x800&#8242; is a decent enough guess, but if we start off with source images that are smaller than that (but which would still comfortably make a nice component image in a larger montage), we can end up with a pretty crazy result:</p>
<p><a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output3.png"><img src="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output3.png" alt="When images are too small, or different orientations, we get problems." title="All Falls Down" width="500" /></a></p>
<p>Not awesome.  The problem is that we are only guessing as to the height of the component images.  We can do better than that though, using *Magick&#8217;s identify command.  This tool gives everything you could possibly want to know about an image, but for now we&#8217;re only interested in the height, and that&#8217;s relatively straightforward:</p>
<pre class="brush: bash; title: ; notranslate">
gm identify -format &quot;%h&quot;
</pre>
<p>which gives us a simple single number.  Ideally, we only want to initially shrink the component images enough so that they are the same size vertically as the smallest vertical of the two.  In practise, this means we are only shrinking the image that is larger vertically in the first stage.  Once they are composed at the same height, we can glue them and shrink the resulting image.  A little bit of bash scripting gets this done for us in a couple of lines:</p>
<pre class="brush: bash; title: ; notranslate">
#!/bin/bash
HEIGHT_ONE=`gm identify -format %h $1`;
HEIGHT_TWO=`gm identify -format %h $2`;

if [ &quot;$HEIGHT_ONE&quot; -lt &quot;$HEIGHT_TWO&quot; ]
then
    MIN_HEIGHT=&quot;$HEIGHT_ONE&quot;
else
    MIN_HEIGHT=&quot;$HEIGHT_TWO&quot;
fi

gm montage -quality 100 -geometry x${MIN_HEIGHT}+5 -background transparent -tile 2x1 -gravity East $1 -gravity West $2 -trim -resize 800 output.png
</pre>
<p>(If you&#8217;re copying and pasting that, ensure you paste as backticks on lines 3 and 4, not quotes or apostrophes.)</p>
<p>Save that as &#8216;you-need-a-montage&#8217;, then make it executable and you can do:</p>
<pre class="brush: bash; title: ; notranslate">
./you-need-a-montage left-image.jpg right-image.jpg
</pre>
<p>to end up with something like this:</p>
<p><a href="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output4.png"><img src="http://jamietalbot.com/wordpress/wp-content/uploads/2011/01/output4.png" alt="A nicely formatted montage with a transparent separator." title="Finalised" width="500" /></a></p>
<p>Be sure to check out more of what ImageMagick and GraphicsMagick can do for you &#8211; this is just scratching the surface.  And keep an eye out for <a href="http://emilybenjamin.com">Emily Benjamin</a> too, once the site is up and running!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2011/01/31/you-need-a-montage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Now Reading&#8230; More</title>
		<link>http://jamietalbot.com/2011/01/27/now-reading-more/</link>
		<comments>http://jamietalbot.com/2011/01/27/now-reading-more/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 12:21:23 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Kindle]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[Plugin]]></category>
		<category><![CDATA[Reading]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=186</guid>
		<description><![CDATA[On my recent joyful rediscovery of reading, a simple and inestimable pleasure that I let alone for too long, and a new bare-bones WordPress plugin I cobbled together tonight to list recently read books.]]></description>
			<content:encoded><![CDATA[<p>In keeping with my aim to read and write something every day, I&#8217;ve been busy putting the new Kindle to good use.  It remains the only tech purchase I&#8217;ve made that has exceeded my expectations, and for which I have no buyer&#8217;s remorse.  I got out of the habit of carrying books with me, but with the Kindle there&#8217;s no excuse.  I&#8217;ve rediscovered the act of reading for pleasure and have largely replaced time-wasting iPhone games like Angry Birds and Cut The Rope with something more meaningful.  Suddenly time on the bus is eagerly anticipated, rather than avoided, and the empty satisfaction of beating some poor AI on Monopoly is replaced by the genuine joy of finishing a novel.</p>
<p>I was using Amazon&#8217;s Reading List application on LinkedIn and writing short reviews there, but I quite like the idea of having a history of what I&#8217;ve read on my own site.  There are a couple of &#8220;now reading&#8221; plugins for WordPress, but none of them really did what I wanted, so I decided to scratch the itch and put something together.  30 minutes later and you can see the results in the sidebar on the homepage!  Writing plugins for WordPress hasn&#8217;t really changed much since I was active in that area a few years ago, but the main posts table now seems to be used for all kinds of content.  In that spirit, I just created a custom post type of &#8216;book&#8217;, inserted some data into the database and wrote a little widget to extract it.  Reusing the guid column for ISBNs lets me make use of the wonderful <a href="http://openlibrary.org/">Open Library</a> for covers and the post content just becomes the text.  I suppose I could have monetised it with Amazon links, but I&#8217;m sure I can live without the 5 bucks that would bring in a year!  There&#8217;s a little more to do yet, like flesh out a main library URL, and introduce a simple backend page for adding books, but for now it does what I want.</p>
<p>Now I only wish I&#8217;d done this years ago, as the list appears pretty thin at the moment!  I&#8217;ll just take that as yet another incentive to read more!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2011/01/27/now-reading-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Erlang Matrix Module</title>
		<link>http://jamietalbot.com/2011/01/18/an-erlang-matrix-module/</link>
		<comments>http://jamietalbot.com/2011/01/18/an-erlang-matrix-module/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 22:27:19 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[module]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=152</guid>
		<description><![CDATA[A simple matrix module written in Erlang, using lists rather than tuples as its main implementation detail, which provides a number of standard matrix operations without the excessive copying and overhead that existing modules exhibit.]]></description>
			<content:encoded><![CDATA[<p>As part of a recent investigation into counting Hamiltonian Paths in undirected graphs, I began researching the work of Eric Bax, whose paper on <a href="http://portal.acm.org/citation.cfm?id=173192">Inclusion Exclusion</a> promised to yield a quick solution.  Although I ended up going in a different direction, his reliance on adjacency matrices that would be processed 2<sup>n</sup> times required a matrix module that was as efficient as possible.  Writing the solution in Erlang, I found a surprising lack of matrix code on the web, with the most developed I could find being <a href="http://dada.perl.it/shootout/matrix.erlang.html">here</a>.</p>
<p>Erlang perhaps isn&#8217;t the best language for dealing with matrices, with its &#8216;one-time&#8217; mathematical approach to assignment, however the existing methods all seemed to make use of tuple_to_list(), list_to_tuple() conversion and excessive list copying.  Below I present a simple module which is at least more efficient than the above, and relies on a list of lists, using lists:nth() to retrieve elements.  Perhaps in the future this will be superceded by new <a href="http://www.erlang.org/doc/man/array.html">array</a> syntax, but for now it suits my needs.</p>
<p>Matrices are generally stable, by which I mean unchanging in dimensions.  Of course matrices can be different sizes, but the majority of matrix operations that return a matrix result return one the same size as at least one of the inputs.  Given that we know the matrix dimensions, in theory this makes tuples a suitable choice for implementation, but in practice the immutability of tuples (even more immutable than lists) make them unwieldy and involve a lot of overhead when building them.  And with Erlang&#8217;s binding there will be lots of rebuilding.</p>
<p>The main approach is to accept that we will be rebuilding the matrix in full each time and generalise to a standard matrix building function that takes matrix size and cell content generator function parameters:</p>
<pre class="brush: erlang; title: ; notranslate">
new(Columns, Rows, ContentGenerator) -&gt;
  [
    [ContentGenerator(Column, Row, Columns, Rows)
      || Column &lt;- lists:seq(1, Columns)
    ]
    || Row &lt;- lists:seq(1, Rows)
  ].
</pre>
<p>which reads roughly &#8220;for each row, for each column on that row, call the content generation function for that cell&#8221;.</p>
<p>Each content generator function has the following spec:</p>
<pre class="brush: erlang; title: ; notranslate">
fun((pos_integer(), pos_integer(), pos_integer(), pos_integer()) -&gt; any()
</pre>
<p>where the four parameters are current column, current row, number of columns, number of rows.  A simple identity function is as follows:</p>
<pre class="brush: erlang; title: ; notranslate">
fun(Column, Row, _, _) -&gt;
  case Column of Row -&gt; 1; _ -&gt; 0 end
end
</pre>
<p>which will generate the identity matrix:</p>
<pre class="brush: erlang; title: ; notranslate">
[[1 0 0]
 [0 1 0]
 [0 0 1]]
</pre>
<p>A sequential matrix might be generated with the following function:</p>
<pre class="brush: erlang; title: ; notranslate">
fun(Column, Row, Columns, _) -&gt;
  Columns * (Row - 1) + Column
end
</pre>
<p>giving:</p>
<pre class="brush: erlang; title: ; notranslate">
[[1 2 3]
 [4 5 6]
 [7 8 9]]
</pre>
<p>while a matrix composed of pseudo-random numbers 1 to MaxValue could be:</p>
<pre class="brush: erlang; title: ; notranslate">
fun(_, _, _, _) -&gt;
  random:uniform(MaxValue)
end
</pre>
<p>where MaxValue is bound in a closure, giving (for example):</p>
<pre class="brush: erlang; title: ; notranslate">
[[3 9 6]
 [1 1 4]
 [6 2 1]]
</pre>
<p>With this general mechanism, matrix operations such and addition or multiplication become a lot simpler.  All that is required is to define a generator function that sets each cell correctly according to whatever operation you are performing.  Matrix addition is defined thus:</p>
<pre class="brush: erlang; title: ; notranslate">
% Adds two matrices together.
-spec add(num_matrix(), num_matrix()) -&gt; num_matrix().
add(A, B) -&gt;
  new(length(lists:nth(1, A)), length(A),
    fun(Column, Row, _, _) -&gt;
      element_at(Column, Row, A) + element_at(Column, Row, B)
    end
  ).
</pre>
<p>Performance isn&#8217;t great for modification of a single cell, as it rebuilds the entire matrix.  A future optimisation could include recognising that an entire row hasn&#8217;t changed and simply rebinding that.  However, for my current use cases, I haven&#8217;t needed efficient single-cell manipulation.  There are specs for the functions, but very little in the way of error checking.  There are no checks for the addition of matrices of two different sizes, for example.</p>
<p>Future extensions will include the &#8216;Hungarian&#8217; approach to the assignment problem, retrieval functions for entire columns or rows, some unit testing code, and confirmed support for NxM matrices.  (Non-square matrices currently work in theory, but not all functions have been tested to work with them.)  Check out the code <a href="https://github.com/majelbstoat/Morgana/blob/master/src/matrix.erl">on GitHub</a>.  It&#8217;s freely available to use and fork, and if you do, be sure to send a pull request!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2011/01/18/an-erlang-matrix-module/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Giving Back: My 2011 Manifesto</title>
		<link>http://jamietalbot.com/2011/01/08/giving-back-my-2011-manifesto/</link>
		<comments>http://jamietalbot.com/2011/01/08/giving-back-my-2011-manifesto/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 23:14:53 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[CouchDB]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[Manifesto]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=145</guid>
		<description><![CDATA[Open source projects have immeasurably changed the world and my life for the better.  With no formal employment for the bulk of 2011, I pledge to give time and effort to people that need help, and projects that inspire me.]]></description>
			<content:encoded><![CDATA[<p>New Year&#8217;s resolutions are made to be broken, but as this is a week after the fact, perhaps I have a better chance.</p>
<p>The open source world has enriched my life significantly, both professionally, in providing the databases, languages, operating systems and IDEs that are my livelihood, and personally, in providing communications tools, entertainment and even this blogging platform.  Over the course of my career, I&#8217;ve tried to give back to these communities, both in time and code submissions, and I&#8217;ve contributed in some small way to a <a href="http://couchdb.org">number</a> <a href="http://wordpress.org">of</a> <a href="http://xinc.eu">projects</a>.  The challenging nature of my recent full-time employment has unfortunately meant that more recently I&#8217;ve only been able to do this in limited ways.</p>
<p>With my impending hiatus and upcoming travels, I hope to have more time to dedicate to the various online communities I follow.  This might be through forums such as <a href="http://stackoverflow.com/users/38812/majelbstoat">stackoverflow</a> where I&#8217;ve received answers to numerous difficult questions, or simply helping people in chatrooms.  It might be answering questions on Quora.  It will certainly involve code contributions, though to which projects I&#8217;m not sure.  No deed is entirely selfless, and regular development will ensure I stay sharp and widen my employment opportunities, but primarily this is about passion for development, which I&#8217;m certain I couldn&#8217;t live without for any length of time.  I&#8217;m very excited about CouchDB, which would also develop my capabilities in Erlang.  I value Zend Framework very highly, which would deepen my expertise in PHP.  Perhaps it will be both, or others instead.  But as the new year begins, I will make this my manifesto &#8211; that I will give back to those people and projects that have made my life, and many others&#8217; lives better.</p>
<p>My job title from January 22nd &#8211; Open Source Contributor.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2011/01/08/giving-back-my-2011-manifesto/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented jQuery Plugins Mk 2</title>
		<link>http://jamietalbot.com/2010/08/26/object-oriented-jquery-plugins-mk-2/</link>
		<comments>http://jamietalbot.com/2010/08/26/object-oriented-jquery-plugins-mk-2/#comments</comments>
		<pubDate>Thu, 26 Aug 2010 23:02:40 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Plugin]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=98</guid>
		<description><![CDATA[Update: This code is now on GitHub and has had some substantial improvements made. You should look at the latest code here and submit a pull request if you make any improvements! In a recent post, I outlined a method to abstract away the complexity of creating an encapsulated jQuery plugin. However, as was pointed [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong> This code is now on GitHub and has had some substantial improvements made.  You should look at the latest code <a href="https://github.com/majelbstoat/Celsus/blob/master/js/plugins/encapsulatedPlugin.js">here</a> and submit a pull request if you make any improvements!</p>
<hr />
<p>In a <a href="http://jamietalbot.com/2010/08/22/object-oriented-jquery-plugins/">recent post</a>, I outlined a method to abstract away the complexity of creating an encapsulated jQuery plugin.  However, as was pointed out in the comments, there was a missing piece that didn&#8217;t allow for arguments to be passed through.  More seriously, there was an issue with the binding of the facade function, which meant that only the last defined public function in the class could be called.</p>
<p>As an aside, if you need to bind a variable at the time that it is defined, it isn&#8217;t enough to define an anonymous function with a reference to the closure, as that can change by the time the function is called.  The bug in my code was in the piece that bound the facade function to the set member functions.</p>
<pre class="brush: jscript; title: ; notranslate">
	for ( var i in template) {
		if (typeof (template[i]) == 'function') {
			result[i] = function() {
				this.each(function() {
					this[i]();
				});
			};
		}
	}
</pre>
<p>By the time the inner function is called, &#8220;i&#8221; has already been re-bound to the final function name in the template.  The solution is to bind the inner function name to the outer function name at the time of definition, which we can do by wrapping it in (yet another!) function.</p>
<pre class="brush: jscript; title: ; notranslate">
	// Iterates through the set calling the specified function.
 	function makeIteratorFunction(f, set) {
		return function() {
			for ( var i = 0; i &lt; set.length; i++) {
				set[i][f].apply(set[i][f], arguments);
			}
		};
	}
</pre>
<p>and then calling that function:</p>
<pre class="brush: jscript; title: ; notranslate">
	if (template) {
		for ( var i in template) {
			if (typeof (template[i]) == 'function') {
				result[i] = makeIteratorFunction(i, result);
			}
		}
	}
</pre>
<p>At this point, although &#8220;i&#8221; will continue to change as the loop continues, the function call is bound through the closure on &#8220;f&#8221; in the auxiliary function, which remains fixed.  Google Chrome&#8217;s developer tools certainly make following all that a lot simpler!  I&#8217;ve updated the plugin with these improvements, which also enables us to pass arguments through, finally allowing:</p>
<pre class="brush: jscript; title: ; notranslate">
$('#foo').myplugin().publicMethodWithArguments('hello');
</pre>
<p>You can get the updated plugin <a href="/projects/js/jquery/encapsulatedPlugin.js.txt" title="jQuery encapsulated plugin generating plugin">here</a>.  Feedback welcomed!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/08/26/object-oriented-jquery-plugins-mk-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Object Oriented jQuery Plugins</title>
		<link>http://jamietalbot.com/2010/08/22/object-oriented-jquery-plugins/</link>
		<comments>http://jamietalbot.com/2010/08/22/object-oriented-jquery-plugins/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 17:36:48 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Plugin]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=91</guid>
		<description><![CDATA[Object oriented jQuery plugins have typically been hard to create in an elegant way.  Here, we demonstrate how to design a clean jQuery plugin which allows for full encapsulation of data, and allows access to public methods without using the data object as a obvious proxy.]]></description>
			<content:encoded><![CDATA[<p><strong>Update 2:</strong> This code is now on GitHub and has had some substantial improvements made.  You should look at the latest code <a href="https://github.com/majelbstoat/Celsus/blob/master/js/plugins/encapsulatedPlugin.js">here</a> and submit a pull request if you make any improvements!</p>
<hr />
<p><strong>Update:</strong> As pointed out in the comments, the first version of this code didn&#8217;t allow for methods with parameters.  Although the code in the main post below is unchanged, the code linked at the bottom of the page and <a href="/projects/js/jquery/encapsulatedPlugin.js.txt" title="jQuery encapsulated plugin generating plugin">here</a> has been updated to reflect some improvements, that now allow this and some other niceties.  The main body of the post should still be worth reading for the derivation though!</p>
<hr />
<p>I&#8217;ve recently begun the process of porting some javascript library code from Prototype to jQuery, and on the whole it hasn&#8217;t been too problematic.  I really like the element-centric nature of jQuery, whereas Prototype is more like a excellent set of useful static methods.  There were only a couple of things I found myself really missing, and they were enumerables, and elegant plugin encapsulation.  The first problem was solved with Xavier Shay&#8217;s nice <a href="http://rhnh.net/2008/12/28/inject-and-collect-with-jquery" title="Enumerables for jQuery">enumerables plugin</a>.  The second one was more of a challenge.</p>
<p>The lack of encapsulation for jQuery plugins seems to be a common frustration, and there are lots of queries on the web along the lines of &#8220;how do I add public methods to a jQuery plugin&#8221;.  The best solution I found came from <a href="http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html">Hector Virgen</a>, which allows you to do something like this:</p>
<pre class="brush: jscript; title: ; notranslate">
var pluginInstance = $('#foo').data('myplugin');
pluginInstance.publicMethod();
</pre>
<p>That&#8217;s pretty neat, but I didn&#8217;t really like the idea of having to go through the data object each time.  A couple of other people in the comments felt the same way, but there didn&#8217;t seem to be any solutions forthcoming, so I had a crack.  What follows is largely based on Hector&#8217;s code, so you should go and read that first before you go through this.</p>
<p>We start off with a basic plugin shell, slightly modified from Hector&#8217;s, per my taste:</p>
<pre class="brush: jscript; title: ; notranslate">
(function($) {
	var Celsus = Celsus || {};
	Celsus.MyPlugin = function(element, options) {

		// Private members
		var elem = $(element);

		var settings = $.extend({}, options || {});

		// Private methods
		function _privateMethod() {
			console.log(&quot;This is a private method!&quot;);
		}

		return {
			publicMethod: function() {
				console.log(elem);
				_privateMethod();
				return true;
			}
		};
	};

	$.fn.myplugin = function(options) {
		return this.each(function() {
			var element = $(this);
			if (element.data('myplugin')) {
				return;
			}
			var myplugin = new Celsus.MyPlugin(this, options);

			// Store the new plugin definition in a data object.
			element.data('myplugin', myplugin);
		});
	};
})(jQuery);
</pre>
<p>This is a pretty good start.  However, as Hector points out, the main issue is that the plugin returns a jQuery object to enable chaining.  In many complex instances, chaining isn&#8217;t necessarily something you&#8217;re going to want to do, so we make a small sacrifice and forego that convenience.  Instead, we are going to return a set of plugin instance objects:</p>
<pre class="brush: jscript; title: ; notranslate">
$.fn.myplugin = function(options) {
	var result = [];
	this.each(function() {
		var element = $(this);

		if (!element.data('myplugin')) {
			// Initialise
			var myplugin = new Celsus.MyPlugin(this, options);

			// Store the new functions in a validation data object.
			element.data('myplugin', myplugin);
		}
		result.push(element.data('myplugin'));
	});
};
</pre>
<p>At this point, it&#8217;s not looking too great.  We&#8217;ve broken chaining because we no longer return a jQuery object, but if you try and call</p>
<pre class="brush: jscript; title: ; notranslate">
$('#foo').myplugin().publicMethod();
</pre>
<p>it still doesn&#8217;t work.  This is because, although each plugin instance has the publicMethod() function, they are contained inside a bare array.  At this point we could actually do:</p>
<pre class="brush: jscript; title: ; notranslate">
($('#foo').myplugin()[0]).publicMethod();
($('#foo').myplugin()[1]).publicMethod();
</pre>
<p>Or something similar with each(), but this is very messy.  We need a bit of syntactic sugar.  To achieve this, the next step is to take that array, turn it into something we can work with, and add a facade, so that every public function we&#8217;ve just mixed in is presented as an option on the plugin instance set.  We do that by adding the following to the plugin definition:</p>
<pre class="brush: jscript; title: ; notranslate">
result = $(result);
var template = result[0];
if (template) {
	for ( var i in template) {
		if (typeof (template[i]) == 'function') {
			result[i] = function() {
				this.each(function() {
					this[i]();
				});
			};
		}
	}
}
</pre>
<p>Firstly, we convert the array to a jQuery object.  Then, we look at the first instance in the set and use that as a template.  It should contain all the public functions we&#8217;ve defined in our definition class, and all the instances are of the same type, so we can safely use the first entry&#8217;s template for all of them.  We then enumerate through all the public functions and create a proxy or facade function on the set, which simply calls the closure of that function for each element in the set.  This ensures that when you call</p>
<pre class="brush: jscript; title: ; notranslate">
$('#foo').myplugin().publicMethod();
</pre>
<p>it is functionally equivalent to:</p>
<pre class="brush: jscript; title: ; notranslate">
$('#foo').myplugin().each(function(instance) {
	instance.publicMethod();
});
</pre>
<p>So that&#8217;s pretty cool.  We&#8217;ve avoided namespace pollution, we can mix in any number of public methods, and private members and methods behave as you&#8217;d expect them to.  It isn&#8217;t possible to access public variables in this manner of course, but that is easily remedied by using public getters and setters.  We can even add in a reference back to the jQuery object, so we can get chaining back in in some form:</p>
<pre class="brush: jscript; title: ; notranslate">
result.$ = this;
</pre>
<p>Which lets us do:</p>
<pre class="brush: jscript; title: ; notranslate">
$('#foo').myplugin().$.addClass('bar');
</pre>
<p>This is useful when you&#8217;re doing plugin initialisation, but thereafter it&#8217;s a bit redundant as the actual plugin call simply returns an object which you then ignore.  The only final point is that there&#8217;s quite a lot of boilerplate going on here just to get set up.  In actual fact, the actions are pretty generic, so we can extract all that code and put it in its own plugin.  A plugin to generate a plugin!</p>
<pre class="brush: jscript; title: ; notranslate">
(function($) {
	$.fn.encapsulatedPlugin = function(plugin, definition, objects, options) {
		var result = [];
		objects.each(function() {
			var element = $(this);

			if (!element.data(plugin)) {
				// Initialise
				var instance = new definition(this, options);

				// Store the new functions in a validation data object.
				element.data(plugin, instance);
			}
			result.push(element.data(plugin));
		});

		// We now have a set of plugin instances.
		result = $(result);

		// Take the public functions from the definition and make them available across the set.
		var template = result[0];
		if (template) {
			for ( var i in template) {
				if (typeof (template[i]) == 'function') {
					result[i] = function() {
						this.each(function() {
							this[i]();
						});
					};
				}
			}
		}

		// Finally mix-in a convenient reference back to the objects, to allow for chaining.
		result.$ = objects;

		return result;
	};

})(jQuery);
</pre>
<p>With this little plugin, our plugin initialisation code is a lot lighter:</p>
<pre class="brush: jscript; title: ; notranslate">
	$.fn.myplugin = function(options) {
		return $.fn.encapsulatedPlugin('myplugin', Celsus.MyPlugin, this, options);
	};
</pre>
<p>Not too bad!  The actual code that specialises a plugin is tucked away in a neatly encapsulated object, we have access to all the public methods defined on it and multiple instances can happily live side by side and be invoked separately without trampling on each other.    You can grab a copy of the plugin generating plugin from <a href="/projects/js/jquery/encapsulatedPlugin.js.txt" title="jQuery encapsulated plugin generating plugin">here</a>.  This is still new cod and there might be the odd glitch, so if you spot any, or have other ideas, be sure to leave a comment!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/08/22/object-oriented-jquery-plugins/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Subtle Behaviour of The Static Keyword in PHP 5.3</title>
		<link>http://jamietalbot.com/2010/08/11/subtle-behaviour-of-the-static-keyword-in-php-5-3/</link>
		<comments>http://jamietalbot.com/2010/08/11/subtle-behaviour-of-the-static-keyword-in-php-5-3/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 21:58:04 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[Late-Static Binding]]></category>
		<category><![CDATA[LinkedIn]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=86</guid>
		<description><![CDATA[Describing a slight inconsistency in PHP 5.3's use of the static keyword and how it can affect late-static binding.]]></description>
			<content:encoded><![CDATA[<p>Version 5.3 of PHP added a new, very useful and long-overdue feature allowing for late-static binding using the &#8216;static&#8217; keyword instead of the &#8216;self&#8217; keyword.  The PHP manual has a good explanation of the difference.  However, there is a subtle behaviour that I certainly hadn&#8217;t anticipated and might catch you out.</p>
<p>A typical use-case of the new syntax is to lazy-load static variables in inherited child classes, which offers you the choice of avoiding the overhead of object-instantiation to provide class differentiation.  Unfortunately, it is not quite as straightforward as you might think.  Consider the following piece of code:</p>
<pre class="brush: php; title: ; notranslate">
class BaseClass {

	static $_value = null;

	public static function getValue() {
		if (null === static::$_value) {
			static::$_value = get_called_class();
		}
		return static::$_value;
	}
}

class ChildAClass extends BaseClass {}

echo BaseClass::getValue() . &quot;\n&quot;;
echo ChildAClass::getValue() . &quot;\n&quot;;
</pre>
<p>What&#8217;s going on here then?  When I look at that piece of code, I expect the output to be:</p>
<pre class="brush: php; title: ; notranslate">
BaseClass
ChildAClass
</pre>
<p>Instead, it appears the call to ChildAClass::getValue() fails the conditional test and returns the static value of BaseClass, giving the following output:</p>
<pre class="brush: php; title: ; notranslate">
BaseClass
BaseClass
</pre>
<p>Not very helpful.  How can we work around this?  The answer is to ensure you declare the static variable in each of your child classes as well as the parent.  It&#8217;s straightforward enough, but a pain to remember every time.  The following example demonstrates:</p>
<pre class="brush: php; title: ; notranslate">
class ChildBClass extends BaseClass {

	static $_value = null;
}

echo BaseClass::getValue() . &quot;\n&quot;;
echo ChildBClass::getValue() . &quot;\n&quot;;
</pre>
<pre class="brush: php; title: ; notranslate">
BaseClass
ChildBClass
</pre>
<p>So it appears (at least for PHP 5.3.3 (OS X)), that static only really means static if you declare it yourself each time.  This might be expected behaviour, but I consider it a bug, and it can certainly lead to hard to debug situations.  It doesn&#8217;t seem to be documented clearly in any standard location that I could find.</p>
<p>Short story &#8211; if you are looking to lazily-populate static variables using the new syntax, be sure to declare the variables in all of the child classes you are going to use!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/08/11/subtle-behaviour-of-the-static-keyword-in-php-5-3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Do You Still Want Gengo?</title>
		<link>http://jamietalbot.com/2010/06/30/do-you-still-want-gengo/</link>
		<comments>http://jamietalbot.com/2010/06/30/do-you-still-want-gengo/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 13:57:15 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Gengo]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[Plugin]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=82</guid>
		<description><![CDATA[Gengo is a multi-lingual plugin for WordPress that has fallen by the wayside.  Is there enough interest out there for me to restart development on it?]]></description>
			<content:encoded><![CDATA[<p>Gengo was (and remains) a project that I am very fond of.  Originally developed for my own personal use to blog in Japanese as well as English, it turned into a fairly full-featured plugin that was used by quite a few people.  Unfortunately, time pressures meant that I had to drop support for it a few years ago.  Even so, every few weeks I get an email or comment (usually nothing to do with the post it was written against!) asking me to consider restarting development.  </p>
<p>It might just be the alcohol talking, or end-of-financial-year madness, but with WordPress 3.0 recently out and a couple of requests already this week, I&#8217;m seriously considering starting development again.  I do have a couple of projects I want to do though, so I only want to dedicate time to Gengo if it&#8217;s going to be used.  My Japanese has sadly diminished to the point where I&#8217;m practically mono-lingual again, so I&#8217;m not going to be blogging in multiple languages any time soon, and it would purely be for others to use.  So, if enough people email me or comment in the next week or so, I&#8217;ll give it a crack.  Second time around, I&#8217;ll hopefully be able to design it more cleanly and more quickly, and WordPress&#8217; plugin architecture hopefully hasn&#8217;t changed too much while I&#8217;ve been away.</p>
<p>So if you want to see a new version of Gengo, please let me know.  On the other hand, I hear very good things about WPML, so If Gengo&#8217;s time has passed, feel free to say that too!  I won&#8217;t have hurt feelings, promise <img src='http://jamietalbot.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/06/30/do-you-still-want-gengo/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Using Multiple Start and End Keys for CouchDB Views</title>
		<link>http://jamietalbot.com/2010/03/24/using-multiple-start-and-end-keys-for-couchdb-views/</link>
		<comments>http://jamietalbot.com/2010/03/24/using-multiple-start-and-end-keys-for-couchdb-views/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 00:55:57 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[CouchDB]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[LinkedIn]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=69</guid>
		<description><![CDATA[Describing how to patch CouchDB 0.10.1 to query views with multiple start and end key ranges in one request.]]></description>
			<content:encoded><![CDATA[<p>CouchDB view collation is great and only has one real drawback that has caused me any real pain &#8211; the inability to handle queries that need to be parameterised by more than one dimension.  These are suprisingly common, including problems such as &#8220;find me posts in Category A in March&#8221;.</p>
<p>This can be handled with a function that emits keys like:</p>
<pre class="brush: jscript; title: ; notranslate">
[&quot;Category A&quot;, &quot;2010&quot;, &quot;03&quot;, &quot;Post 1&quot;]
[&quot;Category B&quot;, &quot;2010&quot;, &quot;03&quot;, &quot;Post 2&quot;]
[&quot;Category A&quot;, &quot;2010&quot;, &quot;03&quot;, &quot;Post 3&quot;]
</pre>
<p>and then use:</p>
<pre class="brush: jscript; title: ; notranslate">
startkey=[&quot;Category A&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category A&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
</pre>
<p>However find its reciprocal &#8220;All March posts regardless of category&#8221; is problematic.  You can&#8217;t do:</p>
<pre class="brush: jscript; title: ; notranslate">
startkey=[*,&quot;2010&quot;, &quot;03&quot;]&amp;endkey=[*,&quot;2010&quot;, &quot;03&quot;,{}]
</pre>
<p>where * (or _,  or nil, or pass) would represent &#8220;all&#8221;.</p>
<p>To handle this, there are currently only 2 options; design a new view with the the key components ordered differently, such that they emit:</p>
<pre class="brush: jscript; title: ; notranslate">
[&quot;2010&quot;, &quot;03&quot;, &quot;Post 1&quot;]
[&quot;2010&quot;, &quot;03&quot;, &quot;Post 2&quot;]
[&quot;2010&quot;, &quot;03&quot;, &quot;Post 3&quot;]
</pre>
<p>or, make multiple connections to the database like</p>
<pre class="brush: jscript; title: ; notranslate">
startkey=[&quot;Category A&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category A&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
startkey=[&quot;Category B&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category B&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
startkey=[&quot;Category C&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category C&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
</pre>
<p>where you have a query for each category.</p>
<p>Neither approach is particularly satisfactory.  On a recent particular problem set, a single view would be many hundreds of gigabytes of data, and while space is cheap, it&#8217;s not that cheap.  Additional views were not an option.  That same data set contained around 2000 different categories (or their equivalent) and 2000 connections for a particular query seemed excessive.</p>
<p>Since 0.9, Couch has had a way of passing multiple keys to a query in the post body of a view request.  Unfortunately, this only supported precise keys, not start-end key ranges.  There has been <a href="https://issues.apache.org/jira/browse/COUCHDB-523">a ticket</a> in the issue tracker to add this additional support since October, but it&#8217;s classed as a minor priority and nothing had been done on it.  So I decided to have a crack.</p>
<p>On the face of it, it seems like a fairly simple change, only affecting the HTTP View Erlang module.  On the other hand, I&#8217;ve probably written about 100 lines of Erlang in my life and never looked at the CouchDB code before, so it&#8217;s entirely possible I&#8217;ve done something wrong.  Regardless, the following is a simple solution that appears to work correctly.</p>
<p>The output_map_view and output_reduce_view functions already had the ability to handle start and end keys, but they were being artificially restricted to treat the supplied keys and both start and end.  I used Erlang&#8217;s pattern matching to make this a little richer:</p>
<pre class="brush: erlang; title: ; notranslate">
case Key of
	{[{&lt;&lt;&quot;startkey&quot;&gt;&gt;,StartKey},{&lt;&lt;&quot;endkey&quot;&gt;&gt;,EndKey}]} -&gt;
		nil;
	_ -&gt;
		StartKey = Key,
		EndKey = Key
end
</pre>
<p>and then passing those new variables in the appropriate place.  This seemed to work well.  I presume that the Keys parameter is processed just like multiple connections, and then the results aggregated, because the results are exactly the same as a call with the same parameters in the query string.</p>
<p>One final change was that group_level=X is mysteriously disallowed for Multikey queries.  I took a punt and removed this restriction and it all seemed to work fine.  I can only guess that this restriction didn&#8217;t make sense when you had to pass precise keys.</p>
<p>I then query using the following as POST data:</p>
<pre class="brush: jscript; title: ; notranslate">
{
    &quot;keys&quot;: [
        {
            &quot;startkey&quot;: [&quot;Category A&quot;,&quot;2010&quot;,&quot;03&quot;],
            &quot;endkey&quot;: [&quot;Category A&quot;,&quot;2010&quot;,&quot;03&quot;,{}]
        },
        {
            &quot;startkey&quot;: [&quot;Category B&quot;,&quot;2010&quot;,&quot;03&quot;],
            &quot;endkey&quot;: [&quot;Category B&quot;,&quot;2010&quot;,&quot;03&quot;,{}]
        }
    ]
}
</pre>
<p>With this solution, I&#8217;m able to query 2000 services simultaneously, group them at any level I like, and get back the results at the lightning speed I&#8217;ve become accustomed to.</p>
<p>One small caveat: If I want to get back keys across non-contiguous blocks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
startkey=[&quot;Category A&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category A&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
startkey=[&quot;Category A&quot;,&quot;2010&quot;,&quot;06&quot;]&amp;endkey=[&quot;Category A&quot;,&quot;2010&quot;, &quot;06&quot;,{}]
startkey=[&quot;Category B&quot;,&quot;2010&quot;,&quot;03&quot;]&amp;endkey=[&quot;Category B&quot;,&quot;2010&quot;, &quot;03&quot;,{}]
startkey=[&quot;Category B&quot;,&quot;2010&quot;,&quot;06&quot;]&amp;endkey=[&quot;Category B&quot;,&quot;2010&quot;, &quot;06&quot;,{}]
</pre>
<p>To get all posts in Category A and B in March and June, I can.  However, if I have a reduce function and group at level 1, I still end up with 4 rows, 2 for Category A, 2 for Category B.  I think this is because the queries are being run independently, without reference to the other.  To do a full aggregation across time periods (for example to get the total number of posts by category in March and June), I&#8217;d still need to do a client aggregation on the resulting data-set.  This may or may not be a big problem for you; it&#8217;s certainly something I can live with.</p>
<p>The CouchDB issue lives <a href="https://issues.apache.org/jira/browse/COUCHDB-523">here</a>, and the patch to 0.10.1 lives <a href="https://issues.apache.org/jira/secure/attachment/12439618/multi_start_end_key.diff">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/03/24/using-multiple-start-and-end-keys-for-couchdb-views/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Handling JSON Objects in CouchDB Native Erlang Views</title>
		<link>http://jamietalbot.com/2010/03/18/handling-json-objects-in-couchdb-native-erlang-views/</link>
		<comments>http://jamietalbot.com/2010/03/18/handling-json-objects-in-couchdb-native-erlang-views/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 05:41:02 +0000</pubDate>
		<dc:creator>Jamie Talbot</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[CouchDB]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[LinkedIn]]></category>

		<guid isPermaLink="false">http://jamietalbot.com/?p=63</guid>
		<description><![CDATA[Using CouchDB Erlang views can be confusing when your documents contain JSON objects.  Understanding how Couch processes JSON internally and making use of Erlang pattern matching smoothes the way.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working with CouchDB a fair bit in recent weeks and am really enjoying it so far.  Once I got my head around how to structure views and take advantage of view collation, I found it to be far more expressive than I first thought.</p>
<p>I still have a couple of gripes, the largest one of which is that you can&#8217;t use a wildcard parameter at the beginning of your view keys, so if you need to get &#8220;items by user by category&#8221; and &#8220;items by category by user&#8221;, you need two views.  I&#8217;m sure there are good architectural reasons for this, but for me it&#8217;s the one place where collation lets me down.  For at least one of the solutions I&#8217;m working on, multiple views are a major problem, as even one takes up 120GB (and counting).</p>
<p>But, to the main point.  Native Erlang views are now possible, and if you can create them, potentially significantly faster than Javascript ones.  There are a couple of gotchas though, not least for me the handling of JSON objects.</p>
<p>We start with a document like this:</p>
<pre class="brush: jscript; title: ; notranslate">
{
   &quot;_id&quot;: &quot;36kem&quot;,
   &quot;_rev&quot;: &quot;1-c895d5a55945a9898880bf870a3b3025&quot;,
   &quot;type&quot;: &quot;usage&quot;,
   &quot;timestamp&quot;: [
       &quot;2010&quot;,
       &quot;02&quot;,
       &quot;28&quot;,
       &quot;23&quot;,
       &quot;10&quot;
   ],
   &quot;data&quot;: [
       {
           &quot;t&quot;: &quot;E000005861&quot;,
           &quot;i&quot;: &quot;232920&quot;,
           &quot;o&quot;: &quot;2365730&quot;
       },
       {
           &quot;t&quot;: &quot;E000006504&quot;,
           &quot;i&quot;: &quot;15784&quot;,
           &quot;o&quot;: &quot;17786&quot;
       },
       {
           &quot;t&quot;: &quot;E000006505&quot;,
           &quot;i&quot;: &quot;16661&quot;,
           &quot;o&quot;: &quot;17786&quot;
       }
   ]
}
</pre>
<p>In reality there are thousands of entries in the data array, but this will do.  Our aim is to emit one key-value pair for each item in the &#8220;data&#8221; field of each document of type &#8220;usage&#8221;.  In Javascript this is pretty trivial.  Erlang however, proves more of a challenge.</p>
<p>Based on pointers from the <a href="http://wiki.apache.org/couchdb/EnableErlangViews">CouchDB Wiki</a>, I started with:</p>
<pre class="brush: erlang; title: ; notranslate">
fun ({Doc}) -&gt;
  case proplists:get_value(&lt;&lt;&quot;type&quot;&gt;&gt;, Doc) of
    &lt;&lt;&quot;usage&quot;&gt;&gt; -&gt;
      Emit(proplists:get_value(&lt;&lt;&quot;_id&quot;&gt;&gt;, Doc), null);
    _ -&gt;
      ok
  end
end.
</pre>
<p>and was very happy to see that work.  Two things to note here:  Don&#8217;t forget the {} around the Doc in the function definition or you&#8217;ll get strange errors, and; to get the value of a field in a document, you can use the standard proplists:get_value(<<"fieldname">>, Doc) construct.  So far so good.</p>
<p>The main issue for me came with manipulating the &#8220;data&#8221; field.  I didn&#8217;t actually want to emit null, but instead the &#8220;i&#8221; and &#8220;o&#8221; parts of the data field.  First off, I tried:</p>
<pre class="brush: erlang; title: ; notranslate">
  lists:foreach(fun(Item) -&gt; Emit(null, [proplists:get_value(&lt;&lt;&quot;i&quot;&gt;&gt;, Item), proplists:get_value(&lt;&lt;&quot;o&quot;&gt;&gt;, Item)]) end, proplists:get_value(&lt;&lt;&quot;data&quot;&gt;&gt;, Doc)
</pre>
<p>But met with some (very long) errors.  (Gripe number two &#8211; they could really do with humanising the Erlang crash dump.)</p>
<p>It took me quite a few attempts, including stripping it right back to confirm that I had an array to iterate and that each object does in fact contain an &#8220;i&#8221; and an &#8220;o&#8221; field, before I found the problem, which is this:</p>
<p><strong>Even though Documents are defined within {} braces, and JSON objects within that definition are also defined within {} braces, you cannot access them the same way in an Erlang view.</strong></p>
<p>proplists:get_value(<<"field">>, Doc) is fine for the document as a whole, but you can&#8217;t access JSON objects the same way.  Bad assumption on my part.  Luckily, the answer I got to another <a href="http://stackoverflow.com/questions/2414811/emit-tuples-from-erlang-views-in-couchdb/2422631#2422631">Stack Overflow question</a> recently pointed the way.</p>
<p>To access the data we need to pattern match the components using the Erlang representation of a JSON object, like so:</p>
<pre class="brush: erlang; title: ; notranslate">
  {[{&lt;&lt;&quot;t&quot;&gt;&gt;, TrackingID},{&lt;&lt;&quot;i&quot;&gt;&gt;, In},{&lt;&lt;&quot;o&quot;&gt;&gt;, Out}]} = Row
</pre>
<p>Ugly, hey? <img src='http://jamietalbot.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Useful though, as it extracts the TrackingID, In and Out values all in one go, kind of like a <code>list()</code> statement on steroids.</p>
<p>With that in place, and a little more tidying up of the code, we arrive at:</p>
<pre class="brush: erlang; title: ; notranslate">
fun({Doc}) -&gt;
	case proplists:get_value(&lt;&lt;&quot;type&quot;&gt;&gt;, Doc) of
		&lt;&lt;&quot;usage&quot;&gt;&gt; -&gt;
			[Year, Month, Day, Hour, Minute | _] = proplists:get_value(&lt;&lt;&quot;timestamp&quot;&gt;&gt;, Doc),
                        lists:foreach(fun(Row) -&gt;
                                {[{&lt;&lt;&quot;t&quot;&gt;&gt;, TrackingID},{&lt;&lt;&quot;i&quot;&gt;&gt;, In},{&lt;&lt;&quot;o&quot;&gt;&gt;, Out}]} = Row,
				Emit([TrackingID, Year, Month, Day, Hour, Minute],[In, Out])
			end, proplists:get_value(&lt;&lt;&quot;data&quot;&gt;&gt;, Doc));
		_ -&gt;
			ok
	end
end.
</pre>
<p>That little beauty lets me query the usage of a service at any granularity over data from the last 7 years in a faster time than the browser can render it.  Across an HTTP connection to a data source 1000km away.  On development hardware.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamietalbot.com/2010/03/18/handling-json-objects-in-couchdb-native-erlang-views/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

