<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<link rel="self" href="/Atom/" />
	<id>http://billmill.org/</id>
	<title>My Name Rhymes</title>
	<subtitle>Bill Mill blogs irregularly</subtitle>
	<updated>2009-08-20T22:55:00Z</updated>
	<author>
		<name>Bill Mill</name>
		<email>bill.mill@gmail.com</email>
		<uri>http://billmill.org/</uri>
	</author>
	<link href="http://billmill.org/" />
	<entry>
		<title>Multi-Line Lambdas in Python Using the With Statement</title>
		<link href="http://billmill.org/multi_line_lambdas.html" />	
		<id>http://billmill.org/multi_line_lambdas.html</id>
		<updated>2009-08-20T22:55:00Z</updated>
		<summary type="html">&lt;p&gt;Python &lt;a 
href="http://www.artima.com/weblogs/viewpost.jsp?thread=147358"&gt;does not have 
multi-line lambdas&lt;/a&gt; because Guido dislikes them aesthetically. However, with 
just a bit of introspection, code like this is possible:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span style="font-weight: bold"&gt;with&lt;/span&gt; each([&lt;span style="color: #009999"&gt;12&lt;/span&gt;, &lt;span style="color: #009999"&gt;14&lt;/span&gt;, &lt;span style="color: #009999"&gt;16&lt;/span&gt;]):
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;   &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;     &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;     &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;+&lt;/span&gt;&lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;  
&lt;span style="color: #009999"&gt;12&lt;/span&gt;
&lt;span style="color: #009999"&gt;13&lt;/span&gt;
&lt;span style="color: #009999"&gt;14&lt;/span&gt;
&lt;span style="color: #009999"&gt;15&lt;/span&gt;
&lt;span style="color: #009999"&gt;16&lt;/span&gt;
&lt;span style="color: #009999"&gt;17&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;I'll say a bit about my motivation for creating code like this, show how 
easy it is to write, and then I'll argue that code like this is both pythonic 
and aesthetically appealing in some circumstances.

&lt;p&gt;&lt;h2&gt;A Mystery Solved (By Holmes Himself!)&lt;/h2&gt;

&lt;p&gt;When I first saw code using the &lt;code&gt;with&lt;/code&gt; statement, my hope was 
that it would be able to be used somewhat like Haskell's &lt;a 
href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29#More_complex_examples"&gt;Where 
clause&lt;/a&gt; or Ruby's &lt;a 
href="http://allaboutruby.wordpress.com/2006/01/20/ruby-blocks-101/"&gt;blocks&lt;/a&gt;.  
When I dug into the &lt;a 
href="http://www.python.org/dev/peps/pep-0343/"&gt;spec&lt;/a&gt;, I was disappointed to 
discover that if it was possible, it wasn't easy, and I pushed the thought 
aside.

&lt;p&gt;That was a couple years ago, and I didn't give it a moment's thought until I 
saw &lt;a 
href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.3"&gt;a 
blog post&lt;/a&gt; by Richard Jones that uses a &lt;code&gt;with&lt;/code&gt; statement in exactly 
the way I had considered impossible up to now. I spent a few hours trying to 
figure it out, but I was stumped, so I put up &lt;a 
href="http://stackoverflow.com/questions/1255914/finding-functions-defined-in-a-with-block"&gt;a 
question&lt;/a&gt; on Stack Overflow to see if somebody could show me how he did it.

&lt;p&gt;Within a few hours, &lt;a 
href="http://en.wikipedia.org/wiki/Alex_Martelli"&gt;Alex Martelli&lt;/a&gt; himself 
chimed in with a wonderful solution. The gist of the answer is that you can use 
the &lt;code&gt;inspect&lt;/code&gt; module to access the &lt;a 
href="http://www.python.org/doc/2.5.2/lib/typecontextmanager.html"&gt;context 
manager&lt;/a&gt;'s calling scope, and figure out what variables have been defined 
between its &lt;code&gt;__enter__&lt;/code&gt; and &lt;code&gt;__exit__&lt;/code&gt; functions. I'm 
glad I asked aloud, because even if I had stumbled close to the solution, I 
surely wouldn't have come up with one as complete as his.

&lt;p&gt;&lt;h2&gt;The How&lt;/h2&gt;

&lt;p&gt;Once I had Alex's proof of concept code in hand, I went to work making it do 
what I'd had in my head so long ago. In about an hour, I was able to write code 
that looks like this:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;each&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; i &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; iterable:
      block(i)

&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; each([&lt;span style="color: #bb8844"&gt;&amp;quot;twelve&amp;quot;&lt;/span&gt;, &lt;span style="color: #bb8844"&gt;&amp;quot;fourteen&amp;quot;&lt;/span&gt;, &lt;span style="color: #bb8844"&gt;&amp;quot;sixteen&amp;quot;&lt;/span&gt;]):
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x

@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;bmap&lt;/span&gt;(arr, block):
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;map&lt;/span&gt;(block, arr)

&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]) &lt;span style="font-weight: bold"&gt;as&lt;/span&gt; foo:
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; (&lt;span style="color: #999999"&gt;float&lt;/span&gt;(x) &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;) &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; &lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; foo &lt;span style="color: #999988; font-style: italic"&gt;# [1.0, 1.5, 2.0]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;What you see above are two functions which use a decorator giving them 
access to the function defined within the &lt;code&gt;with&lt;/code&gt; block. The 
decorator passes the block to the function as its last argument just &lt;a 
href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"&gt;like 
in Ruby&lt;/a&gt;.

&lt;p&gt;To understand how this happens, you need to know how context managers work.  
Context managers consist of a class with &lt;code&gt;__enter__&lt;/code&gt; and 
&lt;code&gt;__exit__&lt;/code&gt; methods which are called upon entering the with block and 
upon exiting, just as you'd expect.

&lt;p&gt;Alex's solution involves scanning the scope of the calling function from the 
&lt;code&gt;__enter__&lt;/code&gt; and &lt;code&gt;__exit__&lt;/code&gt; methods, and pulling out the 
differences between them. These differences will be all the variables that were 
defined in the &lt;code&gt;with&lt;/code&gt; block. A sketch:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;class&lt;/span&gt; &lt;span style="color: #445588; font-weight: bold"&gt;FindInteresting&lt;/span&gt;(&lt;span style="color: #999999"&gt;object&lt;/span&gt;):
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__enter__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
    &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;dict&lt;/span&gt;(f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals)

  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
    &lt;span style="color: #999988; font-style: italic"&gt;#pick out the differences between f.f_locals and self.already_defined&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;When we pick out the differences between the two, we need to be careful to 
check for names that have been redefined so that we don't miss out on new 
functions that reuse old names.

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
  interesting &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; {}
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; n &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals:
    newf &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals[n]
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; n &lt;span style="font-weight: bold"&gt;not&lt;/span&gt; &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined:
      interesting[n] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; newf
      &lt;span style="font-weight: bold"&gt;continue&lt;/span&gt;
    anf &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined[n]
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;id&lt;/span&gt;(newf) &lt;span style="font-weight: bold"&gt;!=&lt;/span&gt; &lt;span style="color: #999999"&gt;id&lt;/span&gt;(anf):
      interesting[n] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; newf
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;After this function has run, &lt;code&gt;interesting&lt;/code&gt; is a dictionary which 
(probably) contains all the names and values of the variables that have been 
redefined in the &lt;code&gt;with&lt;/code&gt; block.

&lt;p&gt;Because we have to use the &lt;code&gt;id&lt;/code&gt; check to determine if a name has 
been redefined, and Python sometimes caches objects in memory, our function can 
be fooled. In this case, &lt;code&gt;interesting&lt;/code&gt; will not detect 
&lt;code&gt;x&lt;/code&gt; because it's being redefined and cpython caches the low 
integers, so &lt;code&gt;id(x)&lt;/code&gt; will be the same for both &lt;code&gt;x&lt;/code&gt;s.

&lt;div class="highlight"&gt;&lt;pre&gt;x &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; FindInteresting:
  x &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;In general, the cpython runtime is not aggressive about caching, but you 
should know that this possibility exists. If you use this technique, I 
recommend being strict about checking only newly defined functions, since 
there's no way to be sure if you missed any redefined names.

&lt;p&gt;To make the teaser code at the top of the article work, I just wrapped 
Alex's code into a decorator that returned a context manager, then called the 
function being decorated with the definitions that we found in the 
&lt;code&gt;interesting&lt;/code&gt; dictionary. The context manager's 
&lt;code&gt;__call__&lt;/code&gt; function gets overridden to allow you to pass in 
arguments for the function being decorated.

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;accepts_block&lt;/span&gt;(f):
  &lt;span style="font-weight: bold"&gt;class&lt;/span&gt; &lt;span style="color: #445588; font-weight: bold"&gt;BlockContextManager&lt;/span&gt;(&lt;span style="color: #999999"&gt;object&lt;/span&gt;):
    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__call__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;, &lt;span style="font-weight: bold"&gt;*&lt;/span&gt;args, &lt;span style="font-weight: bold"&gt;**&lt;/span&gt;kwargs):
      &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; functools&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;partial(f, &lt;span style="font-weight: bold"&gt;*&lt;/span&gt;args, &lt;span style="font-weight: bold"&gt;**&lt;/span&gt;kwargs)
      &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;

    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__enter__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
      &lt;span style="color: #999988; font-style: italic"&gt;#do Alex&amp;#39;s magic, just as above&lt;/span&gt;
    
    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
      &lt;span style="color: #999988; font-style: italic"&gt;#make the interesting dictionary, just as above&lt;/span&gt;

      &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;:
        block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;list&lt;/span&gt;(interesting&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;itervalues())[&lt;span style="color: #009999"&gt;0&lt;/span&gt;]
        &lt;span style="font-weight: bold"&gt;assert&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(block, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;))
        &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction(block)

  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; BlockContextManager()
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;It looks complicated and nested, but all it's doing is saving the function 
and all its arguments, grabbing the definitions from the with block, making 
sure there's only one definition and it's a function, then tacking it onto the 
end of the arguments list for the function and calling it. Phew.

&lt;p&gt;The code above handles the case where you don't need to store the result of
the function being decorated:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;each&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; i &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; iterable:
    block(i)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;But what if we want to store the result? Turns out, we can further abuse the 
&lt;code&gt;with&lt;/code&gt; block by hijacking its &lt;code&gt;as&lt;/code&gt; clause. Because a 
variable defined in the &lt;code&gt;as&lt;/code&gt; clause gets detected by Alex's code, we 
can use the inspect module to change that variable so that after the with block 
it reflects the result of our computation.

&lt;p&gt;First we check to see if we probably have a block and a variable in the as 
statement, then we reach in and store our result there if we are in that case:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  &lt;span style="color: #999988; font-style: italic"&gt;#exactly as before; frame = inspect.currentframe(1)&lt;/span&gt;

  &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;:
    &lt;span style="color: #999988; font-style: italic"&gt;#exactly the same as before&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;elif&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;2&lt;/span&gt;:
    block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;None&lt;/span&gt;
    savename &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;None&lt;/span&gt;
    &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; n,v &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; interesting&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;iteritems():
      &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(v, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;)): block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; v
      &lt;span style="font-weight: bold"&gt;else&lt;/span&gt;: savename &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; n

    &lt;span style="font-weight: bold"&gt;assert&lt;/span&gt; savename &lt;span style="font-weight: bold"&gt;and&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(block, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;))

    frame&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals[savename] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction(block)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Which lets us do this:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;bmap&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;map&lt;/span&gt;(block, iterable)
  
&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]) &lt;span style="font-weight: bold"&gt;as&lt;/span&gt; result:
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;**&lt;/span&gt;&lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; result &lt;span style="color: #999988; font-style: italic"&gt;#[1,4,9]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This time, we're really taking a leap by assuming that if we find a callable 
and any other variable, that the variable is where we want to store our 
results. This can lead to somewhat unexpected results:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]):
  not_a_result &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;12&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;**&lt;/span&gt;&lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; not_a_result &lt;span style="color: #999988; font-style: italic"&gt;# [1,4,9] instead of 12&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;That's my extremely long-winded description of how to abuse the with 
operator. If you want to see the full function and the super-lame test code I 
wrote, you can &lt;a 
href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master"&gt;head on 
over to github&lt;/a&gt; and check it out.

&lt;p&gt;&lt;h2&gt;Aesthetics&lt;/h2&gt;

&lt;p&gt;It should be clear from all of the disclaimers I've had to put into this 
article that this technique is of limited use in Python as it stands today.  
I'd like to make an argument that it suggests some nice syntactic sugar for 
python to support someday, while remaining totally ignorant of the actual 
difficulties of putting it into the language.

&lt;p&gt;To do so, I'll start by posting the motivating example for decorators from 
&lt;a href="http://www.python.org/dev/peps/pep-0318/"&gt;the relevant PEP&lt;/a&gt;. It 
argues that this code:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;foo&lt;/span&gt;(cls):
  &lt;span style="font-weight: bold"&gt;pass&lt;/span&gt;
foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; synchronized(lock)(foo)
foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;classmethod&lt;/span&gt;(foo)
&lt;/pre&gt;&lt;/div&gt;


is not nearly as readable as this code:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;@classmethod
@synchronized(lock)
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;foo&lt;/span&gt;(cls):
  &lt;span style="font-weight: bold"&gt;pass&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The main problem with the readability of the first snippet is not that it 
requires 2 redefinitions and 4 repetitions of &lt;code&gt;foo&lt;/code&gt;. Rather, the 
main problem is that it places the cart before the horse by putting the 
function body ahead of the declarations that are required to understand it.

&lt;p&gt;Similarly, when we define callback functions before we use them, we're 
required to define the function body before the place where it will be actually 
used. Often, we see:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;handle_click&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flim()
  &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; foo:
    &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flam(foo)

onClick(handle_click)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;When it would be clearer to write:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; onClick():
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flim()
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; foo:
      &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flam()
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Which I find much more appealing.

&lt;p&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;I expect that there's no way that syntax like this could be officially 
supported by Python, both because of syntactic constraints and the 
&lt;acronym="Benevolent Dictator For Life"&gt;BDFL&lt;/a&gt;'s aesthetic concerns. I do 
think it is a neat exercise in pushing the Python interpreter and syntax past 
where they want to go, and I hope that it gives some food for thought on an 
interesting Python syntax.

&lt;p&gt;I'm excited to see where Richard Jones goes with his &lt;a 
href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.7"&gt;project&lt;/a&gt;, 
and the design choices that he makes in it, since he's pushing the boundaries 
of Python design. Many thanks to him and Alex Martelli for sending me down 
quite an enjoyable path.

&lt;p&gt;Finally, in case you missed it above, go ahead and &lt;a 
href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master"&gt;take a 
look at the code&lt;/a&gt; on github.

&lt;p&gt;If you want to leave a comment, I suggest leaving it on &lt;a href="http://www.reddit.com/r/Python/comments/9cnaw/multiline_lambdas_in_python_using_the_with/"&gt;reddit&lt;/a&gt;.

&lt;p&gt;&lt;h2&gt;Update:&lt;/h2&gt; Someone &lt;a
href="http://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython?ts=1253546882&amp;updated=AnonymousBlocksInPython"&gt;has&lt;/a&gt; taken this technique a bit farther,
using some bytecode hackery.
</summary>
		<content type="html">&lt;p&gt;Python &lt;a 
href="http://www.artima.com/weblogs/viewpost.jsp?thread=147358"&gt;does not have 
multi-line lambdas&lt;/a&gt; because Guido dislikes them aesthetically. However, with 
just a bit of introspection, code like this is possible:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span style="font-weight: bold"&gt;with&lt;/span&gt; each([&lt;span style="color: #009999"&gt;12&lt;/span&gt;, &lt;span style="color: #009999"&gt;14&lt;/span&gt;, &lt;span style="color: #009999"&gt;16&lt;/span&gt;]):
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;   &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;     &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;     &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;+&lt;/span&gt;&lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;...&lt;/span&gt;  
&lt;span style="color: #009999"&gt;12&lt;/span&gt;
&lt;span style="color: #009999"&gt;13&lt;/span&gt;
&lt;span style="color: #009999"&gt;14&lt;/span&gt;
&lt;span style="color: #009999"&gt;15&lt;/span&gt;
&lt;span style="color: #009999"&gt;16&lt;/span&gt;
&lt;span style="color: #009999"&gt;17&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;I'll say a bit about my motivation for creating code like this, show how 
easy it is to write, and then I'll argue that code like this is both pythonic 
and aesthetically appealing in some circumstances.

&lt;p&gt;&lt;h2&gt;A Mystery Solved (By Holmes Himself!)&lt;/h2&gt;

&lt;p&gt;When I first saw code using the &lt;code&gt;with&lt;/code&gt; statement, my hope was 
that it would be able to be used somewhat like Haskell's &lt;a 
href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29#More_complex_examples"&gt;Where 
clause&lt;/a&gt; or Ruby's &lt;a 
href="http://allaboutruby.wordpress.com/2006/01/20/ruby-blocks-101/"&gt;blocks&lt;/a&gt;.  
When I dug into the &lt;a 
href="http://www.python.org/dev/peps/pep-0343/"&gt;spec&lt;/a&gt;, I was disappointed to 
discover that if it was possible, it wasn't easy, and I pushed the thought 
aside.

&lt;p&gt;That was a couple years ago, and I didn't give it a moment's thought until I 
saw &lt;a 
href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.3"&gt;a 
blog post&lt;/a&gt; by Richard Jones that uses a &lt;code&gt;with&lt;/code&gt; statement in exactly 
the way I had considered impossible up to now. I spent a few hours trying to 
figure it out, but I was stumped, so I put up &lt;a 
href="http://stackoverflow.com/questions/1255914/finding-functions-defined-in-a-with-block"&gt;a 
question&lt;/a&gt; on Stack Overflow to see if somebody could show me how he did it.

&lt;p&gt;Within a few hours, &lt;a 
href="http://en.wikipedia.org/wiki/Alex_Martelli"&gt;Alex Martelli&lt;/a&gt; himself 
chimed in with a wonderful solution. The gist of the answer is that you can use 
the &lt;code&gt;inspect&lt;/code&gt; module to access the &lt;a 
href="http://www.python.org/doc/2.5.2/lib/typecontextmanager.html"&gt;context 
manager&lt;/a&gt;'s calling scope, and figure out what variables have been defined 
between its &lt;code&gt;__enter__&lt;/code&gt; and &lt;code&gt;__exit__&lt;/code&gt; functions. I'm 
glad I asked aloud, because even if I had stumbled close to the solution, I 
surely wouldn't have come up with one as complete as his.

&lt;p&gt;&lt;h2&gt;The How&lt;/h2&gt;

&lt;p&gt;Once I had Alex's proof of concept code in hand, I went to work making it do 
what I'd had in my head so long ago. In about an hour, I was able to write code 
that looks like this:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;each&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; i &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; iterable:
      block(i)

&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; each([&lt;span style="color: #bb8844"&gt;&amp;quot;twelve&amp;quot;&lt;/span&gt;, &lt;span style="color: #bb8844"&gt;&amp;quot;fourteen&amp;quot;&lt;/span&gt;, &lt;span style="color: #bb8844"&gt;&amp;quot;sixteen&amp;quot;&lt;/span&gt;]):
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;print&lt;/span&gt; x

@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;bmap&lt;/span&gt;(arr, block):
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;map&lt;/span&gt;(block, arr)

&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]) &lt;span style="font-weight: bold"&gt;as&lt;/span&gt; foo:
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; (&lt;span style="color: #999999"&gt;float&lt;/span&gt;(x) &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;) &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; &lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; foo &lt;span style="color: #999988; font-style: italic"&gt;# [1.0, 1.5, 2.0]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;What you see above are two functions which use a decorator giving them 
access to the function defined within the &lt;code&gt;with&lt;/code&gt; block. The 
decorator passes the block to the function as its last argument just &lt;a 
href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"&gt;like 
in Ruby&lt;/a&gt;.

&lt;p&gt;To understand how this happens, you need to know how context managers work.  
Context managers consist of a class with &lt;code&gt;__enter__&lt;/code&gt; and 
&lt;code&gt;__exit__&lt;/code&gt; methods which are called upon entering the with block and 
upon exiting, just as you'd expect.

&lt;p&gt;Alex's solution involves scanning the scope of the calling function from the 
&lt;code&gt;__enter__&lt;/code&gt; and &lt;code&gt;__exit__&lt;/code&gt; methods, and pulling out the 
differences between them. These differences will be all the variables that were 
defined in the &lt;code&gt;with&lt;/code&gt; block. A sketch:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;class&lt;/span&gt; &lt;span style="color: #445588; font-weight: bold"&gt;FindInteresting&lt;/span&gt;(&lt;span style="color: #999999"&gt;object&lt;/span&gt;):
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__enter__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
    &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;dict&lt;/span&gt;(f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals)

  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
    &lt;span style="color: #999988; font-style: italic"&gt;#pick out the differences between f.f_locals and self.already_defined&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;When we pick out the differences between the two, we need to be careful to 
check for names that have been redefined so that we don't miss out on new 
functions that reuse old names.

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  f &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; inspect&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;currentframe(&lt;span style="color: #009999"&gt;1&lt;/span&gt;)
  interesting &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; {}
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; n &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals:
    newf &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; f&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals[n]
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; n &lt;span style="font-weight: bold"&gt;not&lt;/span&gt; &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined:
      interesting[n] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; newf
      &lt;span style="font-weight: bold"&gt;continue&lt;/span&gt;
    anf &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;already_defined[n]
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;id&lt;/span&gt;(newf) &lt;span style="font-weight: bold"&gt;!=&lt;/span&gt; &lt;span style="color: #999999"&gt;id&lt;/span&gt;(anf):
      interesting[n] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; newf
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;After this function has run, &lt;code&gt;interesting&lt;/code&gt; is a dictionary which 
(probably) contains all the names and values of the variables that have been 
redefined in the &lt;code&gt;with&lt;/code&gt; block.

&lt;p&gt;Because we have to use the &lt;code&gt;id&lt;/code&gt; check to determine if a name has 
been redefined, and Python sometimes caches objects in memory, our function can 
be fooled. In this case, &lt;code&gt;interesting&lt;/code&gt; will not detect 
&lt;code&gt;x&lt;/code&gt; because it's being redefined and cpython caches the low 
integers, so &lt;code&gt;id(x)&lt;/code&gt; will be the same for both &lt;code&gt;x&lt;/code&gt;s.

&lt;div class="highlight"&gt;&lt;pre&gt;x &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; FindInteresting:
  x &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;In general, the cpython runtime is not aggressive about caching, but you 
should know that this possibility exists. If you use this technique, I 
recommend being strict about checking only newly defined functions, since 
there's no way to be sure if you missed any redefined names.

&lt;p&gt;To make the teaser code at the top of the article work, I just wrapped 
Alex's code into a decorator that returned a context manager, then called the 
function being decorated with the definitions that we found in the 
&lt;code&gt;interesting&lt;/code&gt; dictionary. The context manager's 
&lt;code&gt;__call__&lt;/code&gt; function gets overridden to allow you to pass in 
arguments for the function being decorated.

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;accepts_block&lt;/span&gt;(f):
  &lt;span style="font-weight: bold"&gt;class&lt;/span&gt; &lt;span style="color: #445588; font-weight: bold"&gt;BlockContextManager&lt;/span&gt;(&lt;span style="color: #999999"&gt;object&lt;/span&gt;):
    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__call__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;, &lt;span style="font-weight: bold"&gt;*&lt;/span&gt;args, &lt;span style="font-weight: bold"&gt;**&lt;/span&gt;kwargs):
      &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; functools&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;partial(f, &lt;span style="font-weight: bold"&gt;*&lt;/span&gt;args, &lt;span style="font-weight: bold"&gt;**&lt;/span&gt;kwargs)
      &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;

    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__enter__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
      &lt;span style="color: #999988; font-style: italic"&gt;#do Alex&amp;#39;s magic, just as above&lt;/span&gt;
    
    &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
      &lt;span style="color: #999988; font-style: italic"&gt;#make the interesting dictionary, just as above&lt;/span&gt;

      &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;:
        block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;list&lt;/span&gt;(interesting&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;itervalues())[&lt;span style="color: #009999"&gt;0&lt;/span&gt;]
        &lt;span style="font-weight: bold"&gt;assert&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(block, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;))
        &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction(block)

  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; BlockContextManager()
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;It looks complicated and nested, but all it's doing is saving the function 
and all its arguments, grabbing the definitions from the with block, making 
sure there's only one definition and it's a function, then tacking it onto the 
end of the arguments list for the function and calling it. Phew.

&lt;p&gt;The code above handles the case where you don't need to store the result of
the function being decorated:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;each&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; i &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; iterable:
    block(i)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;But what if we want to store the result? Turns out, we can further abuse the 
&lt;code&gt;with&lt;/code&gt; block by hijacking its &lt;code&gt;as&lt;/code&gt; clause. Because a 
variable defined in the &lt;code&gt;as&lt;/code&gt; clause gets detected by Alex's code, we 
can use the inspect module to change that variable so that after the with block 
it reflects the result of our computation.

&lt;p&gt;First we check to see if we probably have a block and a variable in the as 
statement, then we reach in and store our result there if we are in that case:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;__exit__&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  &lt;span style="color: #999988; font-style: italic"&gt;#exactly as before; frame = inspect.currentframe(1)&lt;/span&gt;

  &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;:
    &lt;span style="color: #999988; font-style: italic"&gt;#exactly the same as before&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;elif&lt;/span&gt; &lt;span style="color: #999999"&gt;len&lt;/span&gt;(interesting) &lt;span style="font-weight: bold"&gt;==&lt;/span&gt; &lt;span style="color: #009999"&gt;2&lt;/span&gt;:
    block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;None&lt;/span&gt;
    savename &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;None&lt;/span&gt;
    &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; n,v &lt;span style="font-weight: bold"&gt;in&lt;/span&gt; interesting&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;iteritems():
      &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(v, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;)): block &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; v
      &lt;span style="font-weight: bold"&gt;else&lt;/span&gt;: savename &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; n

    &lt;span style="font-weight: bold"&gt;assert&lt;/span&gt; savename &lt;span style="font-weight: bold"&gt;and&lt;/span&gt; &lt;span style="color: #999999"&gt;isinstance&lt;/span&gt;(block, &lt;span style="color: #999999"&gt;type&lt;/span&gt;(&lt;span style="font-weight: bold"&gt;lambda&lt;/span&gt;:&lt;span style="color: #999999"&gt;None&lt;/span&gt;))

    frame&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;f_locals[savename] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;thefunction(block)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Which lets us do this:

&lt;div class="highlight"&gt;&lt;pre&gt;@accepts_block
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;bmap&lt;/span&gt;(iterable, block):
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; &lt;span style="color: #999999"&gt;map&lt;/span&gt;(block, iterable)
  
&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]) &lt;span style="font-weight: bold"&gt;as&lt;/span&gt; result:
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;**&lt;/span&gt;&lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; result &lt;span style="color: #999988; font-style: italic"&gt;#[1,4,9]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This time, we're really taking a leap by assuming that if we find a callable 
and any other variable, that the variable is where we want to store our 
results. This can lead to somewhat unexpected results:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; bmap([&lt;span style="color: #009999"&gt;1&lt;/span&gt;,&lt;span style="color: #009999"&gt;2&lt;/span&gt;,&lt;span style="color: #009999"&gt;3&lt;/span&gt;]):
  not_a_result &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;12&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(x):
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; x&lt;span style="font-weight: bold"&gt;**&lt;/span&gt;&lt;span style="color: #009999"&gt;2&lt;/span&gt;

&lt;span style="font-weight: bold"&gt;print&lt;/span&gt; not_a_result &lt;span style="color: #999988; font-style: italic"&gt;# [1,4,9] instead of 12&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;That's my extremely long-winded description of how to abuse the with 
operator. If you want to see the full function and the super-lame test code I 
wrote, you can &lt;a 
href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master"&gt;head on 
over to github&lt;/a&gt; and check it out.

&lt;p&gt;&lt;h2&gt;Aesthetics&lt;/h2&gt;

&lt;p&gt;It should be clear from all of the disclaimers I've had to put into this 
article that this technique is of limited use in Python as it stands today.  
I'd like to make an argument that it suggests some nice syntactic sugar for 
python to support someday, while remaining totally ignorant of the actual 
difficulties of putting it into the language.

&lt;p&gt;To do so, I'll start by posting the motivating example for decorators from 
&lt;a href="http://www.python.org/dev/peps/pep-0318/"&gt;the relevant PEP&lt;/a&gt;. It 
argues that this code:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;foo&lt;/span&gt;(cls):
  &lt;span style="font-weight: bold"&gt;pass&lt;/span&gt;
foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; synchronized(lock)(foo)
foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;classmethod&lt;/span&gt;(foo)
&lt;/pre&gt;&lt;/div&gt;


is not nearly as readable as this code:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;@classmethod
@synchronized(lock)
&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;foo&lt;/span&gt;(cls):
  &lt;span style="font-weight: bold"&gt;pass&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The main problem with the readability of the first snippet is not that it 
requires 2 redefinitions and 4 repetitions of &lt;code&gt;foo&lt;/code&gt;. Rather, the 
main problem is that it places the cart before the horse by putting the 
function body ahead of the declarations that are required to understand it.

&lt;p&gt;Similarly, when we define callback functions before we use them, we're 
required to define the function body before the place where it will be actually 
used. Often, we see:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;handle_click&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
  foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flim()
  &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; foo:
    &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flam(foo)

onClick(handle_click)
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;When it would be clearer to write:

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;with&lt;/span&gt; onClick():
  &lt;span style="font-weight: bold"&gt;def&lt;/span&gt; &lt;span style="color: #990000; font-weight: bold"&gt;_&lt;/span&gt;(&lt;span style="color: #999999"&gt;self&lt;/span&gt;):
    foo &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flim()
    &lt;span style="font-weight: bold"&gt;if&lt;/span&gt; foo:
      &lt;span style="color: #999999"&gt;self&lt;/span&gt;&lt;span style="font-weight: bold"&gt;.&lt;/span&gt;flam()
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Which I find much more appealing.

&lt;p&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;I expect that there's no way that syntax like this could be officially 
supported by Python, both because of syntactic constraints and the 
&lt;acronym="Benevolent Dictator For Life"&gt;BDFL&lt;/a&gt;'s aesthetic concerns. I do 
think it is a neat exercise in pushing the Python interpreter and syntax past 
where they want to go, and I hope that it gives some food for thought on an 
interesting Python syntax.

&lt;p&gt;I'm excited to see where Richard Jones goes with his &lt;a 
href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.7"&gt;project&lt;/a&gt;, 
and the design choices that he makes in it, since he's pushing the boundaries 
of Python design. Many thanks to him and Alex Martelli for sending me down 
quite an enjoyable path.

&lt;p&gt;Finally, in case you missed it above, go ahead and &lt;a 
href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master"&gt;take a 
look at the code&lt;/a&gt; on github.

&lt;p&gt;If you want to leave a comment, I suggest leaving it on &lt;a href="http://www.reddit.com/r/Python/comments/9cnaw/multiline_lambdas_in_python_using_the_with/"&gt;reddit&lt;/a&gt;.

&lt;p&gt;&lt;h2&gt;Update:&lt;/h2&gt; Someone &lt;a
href="http://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython?ts=1253546882&amp;updated=AnonymousBlocksInPython"&gt;has&lt;/a&gt; taken this technique a bit farther,
using some bytecode hackery.
</content>
	</entry>
	<entry>
		<title>What Gladwell is Missing: Institutional Memory</title>
		<link href="http://billmill.org/institutional_memory.html" />	
		<id>http://billmill.org/institutional_memory.html</id>
		<updated>2009-05-31T16:50:00Z</updated>
		<summary type="html">&lt;p&gt;Malcolm Gladwell's recent &lt;a
href="http://www.newyorker.com/reporting/2009/05/11/090511fa_fact_gladwell?yrail"&gt;article&lt;/a&gt;,
ostensibly about how Davids can beat Goliaths, featured great praise for the
full-court press as a method for less-skilled teams to beat more-skilled ones.
He writes:

&lt;blockquote&gt;In the world of basketball, there is one story after another like
this about legendary games where David used the full-court press to beat
Goliath. Yet the puzzle of the press is that it has never become popular.
People look at upsets like Fordham over UMass and call them flukes. Basketball
sages point out that the press can be beaten by a well-coached team with adept
ball handlers and astute passers&amp;mdash;and that is true... Playing insurgent
basketball did not guarantee victory. It was simply the best chance an underdog
had of beating Goliath.&lt;/blockquote&gt;

&lt;p&gt;After his piece was &lt;a
href="http://galleyslaves.blogspot.com/2009/05/more-on-gladwell-press-etc.html"&gt;rightly&lt;/a&gt;
&lt;a
href="http://deadspin.com/5239721/malcolm-gladwell-wants-to-know-why-your-team-doesnt-press-more"&gt;criticized&lt;/a&gt; 
&lt;a
href="http://rivals.yahoo.com/ncaa/basketball/blog/the_dagger/post/Malcolm-Gladwell-still-talking-about-the-full-co?urn=ncaab,163209"&gt;all&lt;/a&gt;
&lt;a
href="http://rushthecourt.net/2009/05/05/gladwells-theory-on-full-court-pressure-is-the-only-outlier-here/"&gt;over&lt;/a&gt;
&lt;a
href="http://www.nbcnewyork.com/sports/basketball/Why-Dont-More-Basketball-Teams-Run-the-Press.html"&gt;the&lt;/a&gt; 
&lt;a
href="http://nymag.com/daily/intel/2009/05/malcolm_gladwell_isnt_a_basket.html"&gt;web&lt;/a&gt;,
ESPN &lt;a
href="http://sports.espn.go.com/espn/page2/story?page=simmons/090513"&gt;published&lt;/a&gt;
a long and interesting email conversation between him and Bill Simmons that
addressed the criticism. In it, Gladwell defended his column:

&lt;blockquote&gt;After my piece ran in &lt;em&gt;The New Yorker&lt;/em&gt;, one of the most common
responses I got was people saying, well, the reason more people don't use the
press is that it can be beaten with a well-coached team and a good point guard.
That is (A) absolutely true and (B) beside the point. The press doesn't
guarantee victory. It simply represents the underdog's best  chance of
victory&amp;hellip; I went to see a Lakers-Warriors game earlier this season, and
it was abundantly clear after five minutes that the Warriors' chances of
winning were, oh, no better than 10 percent. Why wouldn't you have a special
squad of trained pressers come in for five minutes a half and press Kobe and
Fisher?&amp;hellip;  Best case is that you rattle the Lakers and force
a half-dozen extra turnovers that turn out to be crucial. And if you lose, so
what? You were going to lose anyway.&lt;/blockquote&gt;

&lt;p&gt;Although lots of people have responded to this rebuttal, I haven't seen
anyone mention what I consider to be an important reason that many teams have
chosen not to implement full-court presses: &lt;strong&gt;Institutional
Memory&lt;/strong&gt;.

&lt;p&gt;Let's imagine that the Warriors had in fact, put on the press, and that it
had worked. The Warriors won against the vaunted Lakers! How would the team
respond? They would press more. When that worked to win some more games, they would
probably trade some of their players who were less well suited to the press to
make room for some younger, faster, fitter players. They would win a few more
games than they had been before. Everything's going good, right?

&lt;p&gt;Then they hit a snag; &lt;strong&gt;No team has won the NBA Championship by pressing
&lt;/strong&gt;. The Warriors could optimize like crazy for the press, but
they'd be training and working and trading and drafting to be, at best, a
pretty good team. But no NBA team wants to be a pretty good team&amp;mdash;they all
want to win championships.

&lt;p&gt;The mental exercise reveals what Gladwell has missed: the Warriors aren't
playing to win that game, or even the most games that season. They're playing
to try and win an NBA championship,
and to do so, they need to spend years trying to build up the institutional
memory of how to win games in the traditional way so that they can eventually beat
every team, not just to win more games than they did playing traditionally.

&lt;p&gt;All of this leads to a simple admonishment when analyzing organizations:
don't expect that the organization is optimizing for what you think they're
optimizing for. And when an organization seems to be acting in ways that are surprising to
you, look for metrics that may be more important to them than the ones you
expect.
</summary>
		<content type="html">&lt;p&gt;Malcolm Gladwell's recent &lt;a
href="http://www.newyorker.com/reporting/2009/05/11/090511fa_fact_gladwell?yrail"&gt;article&lt;/a&gt;,
ostensibly about how Davids can beat Goliaths, featured great praise for the
full-court press as a method for less-skilled teams to beat more-skilled ones.
He writes:

&lt;blockquote&gt;In the world of basketball, there is one story after another like
this about legendary games where David used the full-court press to beat
Goliath. Yet the puzzle of the press is that it has never become popular.
People look at upsets like Fordham over UMass and call them flukes. Basketball
sages point out that the press can be beaten by a well-coached team with adept
ball handlers and astute passers&amp;mdash;and that is true... Playing insurgent
basketball did not guarantee victory. It was simply the best chance an underdog
had of beating Goliath.&lt;/blockquote&gt;

&lt;p&gt;After his piece was &lt;a
href="http://galleyslaves.blogspot.com/2009/05/more-on-gladwell-press-etc.html"&gt;rightly&lt;/a&gt;
&lt;a
href="http://deadspin.com/5239721/malcolm-gladwell-wants-to-know-why-your-team-doesnt-press-more"&gt;criticized&lt;/a&gt; 
&lt;a
href="http://rivals.yahoo.com/ncaa/basketball/blog/the_dagger/post/Malcolm-Gladwell-still-talking-about-the-full-co?urn=ncaab,163209"&gt;all&lt;/a&gt;
&lt;a
href="http://rushthecourt.net/2009/05/05/gladwells-theory-on-full-court-pressure-is-the-only-outlier-here/"&gt;over&lt;/a&gt;
&lt;a
href="http://www.nbcnewyork.com/sports/basketball/Why-Dont-More-Basketball-Teams-Run-the-Press.html"&gt;the&lt;/a&gt; 
&lt;a
href="http://nymag.com/daily/intel/2009/05/malcolm_gladwell_isnt_a_basket.html"&gt;web&lt;/a&gt;,
ESPN &lt;a
href="http://sports.espn.go.com/espn/page2/story?page=simmons/090513"&gt;published&lt;/a&gt;
a long and interesting email conversation between him and Bill Simmons that
addressed the criticism. In it, Gladwell defended his column:

&lt;blockquote&gt;After my piece ran in &lt;em&gt;The New Yorker&lt;/em&gt;, one of the most common
responses I got was people saying, well, the reason more people don't use the
press is that it can be beaten with a well-coached team and a good point guard.
That is (A) absolutely true and (B) beside the point. The press doesn't
guarantee victory. It simply represents the underdog's best  chance of
victory&amp;hellip; I went to see a Lakers-Warriors game earlier this season, and
it was abundantly clear after five minutes that the Warriors' chances of
winning were, oh, no better than 10 percent. Why wouldn't you have a special
squad of trained pressers come in for five minutes a half and press Kobe and
Fisher?&amp;hellip;  Best case is that you rattle the Lakers and force
a half-dozen extra turnovers that turn out to be crucial. And if you lose, so
what? You were going to lose anyway.&lt;/blockquote&gt;

&lt;p&gt;Although lots of people have responded to this rebuttal, I haven't seen
anyone mention what I consider to be an important reason that many teams have
chosen not to implement full-court presses: &lt;strong&gt;Institutional
Memory&lt;/strong&gt;.

&lt;p&gt;Let's imagine that the Warriors had in fact, put on the press, and that it
had worked. The Warriors won against the vaunted Lakers! How would the team
respond? They would press more. When that worked to win some more games, they would
probably trade some of their players who were less well suited to the press to
make room for some younger, faster, fitter players. They would win a few more
games than they had been before. Everything's going good, right?

&lt;p&gt;Then they hit a snag; &lt;strong&gt;No team has won the NBA Championship by pressing
&lt;/strong&gt;. The Warriors could optimize like crazy for the press, but
they'd be training and working and trading and drafting to be, at best, a
pretty good team. But no NBA team wants to be a pretty good team&amp;mdash;they all
want to win championships.

&lt;p&gt;The mental exercise reveals what Gladwell has missed: the Warriors aren't
playing to win that game, or even the most games that season. They're playing
to try and win an NBA championship,
and to do so, they need to spend years trying to build up the institutional
memory of how to win games in the traditional way so that they can eventually beat
every team, not just to win more games than they did playing traditionally.

&lt;p&gt;All of this leads to a simple admonishment when analyzing organizations:
don't expect that the organization is optimizing for what you think they're
optimizing for. And when an organization seems to be acting in ways that are surprising to
you, look for metrics that may be more important to them than the ones you
expect.
</content>
	</entry>
	<entry>
		<title>The Bill Mill NCAA Bracket Randomizer</title>
		<link href="http://billmill.org/ncaa_randomizer.html" />	
		<id>http://billmill.org/ncaa_randomizer.html</id>
		<updated>2009-03-18T16:00:00Z</updated>
		<summary type="html">&lt;p&gt;&lt;em&gt;Short version&lt;/em&gt;: check out the &lt;a href="http://billmill.org/static/ncaa-bracket-randomizer/out.html"&gt;bracket randomizer&lt;/a&gt; I wrote.
&lt;h2&gt;The Long Version&lt;/h2&gt;
&lt;p&gt;Each year, when the NCAA basketball tournament comes around, I end up in
four or five pools, with a separate bracket filled out for each. I love the
games, and I love having teams to root for, but I really hate the process of
guessing to fill out my brackets. I inevitably pick too many upsets, just
because I want to have fun rooting for underdogs; instead I end up bored after
the first two rounds.

&lt;p&gt;This year, I thought I could write some software to help me pick out my
brackets. If I let the computer pick reasonably but randomly for each pool, I figure that I
stand a better chance of having &lt;em&gt;one&lt;/em&gt; decent bracket instead of the
assortment of crappy ones I normally end up with.

&lt;p&gt;So the last two nights, I &lt;a
href="http://billmill.org/static/ncaa-bracket-randomizer/out.html"&gt;wrote
myself a bracket randomizer&lt;/a&gt;; just push the "randomize" button at the top and
watch it go.

&lt;p&gt;In order to pick what team will win a given game, it first calculates the
chance each team will win by plugging &lt;a
href="http://kenpom.com/rate.php"&gt;Ken Pomeroy's&lt;/a&gt; ratings
into the &lt;a
href="http://www.diamond-mind.com/articles/playoff2002.htm"&gt;log5&lt;/a&gt; formula.
Then it picks a random number and compares it to the probability of the
favorite winning; if the number is lower than that, it advances the favorite.
Otherwise, it advances the underdog. Rinse and repeat, and you should have a
reasonable random bracket for the whole tournament.

&lt;h2&gt;The Output&lt;/h2&gt;

&lt;p&gt;Next to each team in the bracket, you'll see three numbers in parentheses.
These numbers represent, respectively, the team's Pythagorean rating, adjusted
offensive efficiency, and adjusted defensive efficiency.

&lt;p&gt;If that's Greek to you (&lt;em&gt;groan&lt;/em&gt;), go check out &lt;a
href="http://www.kenpom.com/blog/index.php/weblog/ratings_explanation/"&gt;Ken's
explanation&lt;/a&gt; of what that means.

&lt;p&gt;The color of each team, once you've randomized, represents their odds of
winning. Brighter green is more of a favorite, deeper red more of an underdog.
It should update the colors if you manually change the teams, but it won't; I
just didn't have time to get everything done that I wanted to. Similarly, it
won't update future games if you change the winner of an early one.

&lt;h2&gt;The Code&lt;/h2&gt;

&lt;p&gt;The surprisingly difficult part of this project was creating a simple HTML bracket that
looked reasonable and allowed you to click to advance a team. I didn't get
everything into the page that I wanted to, simply because I spent so much time
just getting that done. (Keep in mind we're talking about a 2-night hack here).

&lt;p&gt;The code to generate the bracket is contained in one super-ugly &lt;a
href="http://github.com/llimllib/ncaa-bracket-randomizer/blob/1db753ce4f91fc84265efa6a27fa7ee00e84eaa2/bracket.py"&gt;python
file&lt;/a&gt;.

&lt;p&gt;If you've got ideas for stuff to add, or want to generate a cooler looking
bracket, or just check out the code, you can &lt;a
href="http://github.com/llimllib/ncaa-bracket-randomizer/tree/master"&gt;go get
it&lt;/a&gt; at github. Feel free to fork and enjoy!
</summary>
		<content type="html">&lt;p&gt;&lt;em&gt;Short version&lt;/em&gt;: check out the &lt;a href="http://billmill.org/static/ncaa-bracket-randomizer/out.html"&gt;bracket randomizer&lt;/a&gt; I wrote.
&lt;h2&gt;The Long Version&lt;/h2&gt;
&lt;p&gt;Each year, when the NCAA basketball tournament comes around, I end up in
four or five pools, with a separate bracket filled out for each. I love the
games, and I love having teams to root for, but I really hate the process of
guessing to fill out my brackets. I inevitably pick too many upsets, just
because I want to have fun rooting for underdogs; instead I end up bored after
the first two rounds.

&lt;p&gt;This year, I thought I could write some software to help me pick out my
brackets. If I let the computer pick reasonably but randomly for each pool, I figure that I
stand a better chance of having &lt;em&gt;one&lt;/em&gt; decent bracket instead of the
assortment of crappy ones I normally end up with.

&lt;p&gt;So the last two nights, I &lt;a
href="http://billmill.org/static/ncaa-bracket-randomizer/out.html"&gt;wrote
myself a bracket randomizer&lt;/a&gt;; just push the "randomize" button at the top and
watch it go.

&lt;p&gt;In order to pick what team will win a given game, it first calculates the
chance each team will win by plugging &lt;a
href="http://kenpom.com/rate.php"&gt;Ken Pomeroy's&lt;/a&gt; ratings
into the &lt;a
href="http://www.diamond-mind.com/articles/playoff2002.htm"&gt;log5&lt;/a&gt; formula.
Then it picks a random number and compares it to the probability of the
favorite winning; if the number is lower than that, it advances the favorite.
Otherwise, it advances the underdog. Rinse and repeat, and you should have a
reasonable random bracket for the whole tournament.

&lt;h2&gt;The Output&lt;/h2&gt;

&lt;p&gt;Next to each team in the bracket, you'll see three numbers in parentheses.
These numbers represent, respectively, the team's Pythagorean rating, adjusted
offensive efficiency, and adjusted defensive efficiency.

&lt;p&gt;If that's Greek to you (&lt;em&gt;groan&lt;/em&gt;), go check out &lt;a
href="http://www.kenpom.com/blog/index.php/weblog/ratings_explanation/"&gt;Ken's
explanation&lt;/a&gt; of what that means.

&lt;p&gt;The color of each team, once you've randomized, represents their odds of
winning. Brighter green is more of a favorite, deeper red more of an underdog.
It should update the colors if you manually change the teams, but it won't; I
just didn't have time to get everything done that I wanted to. Similarly, it
won't update future games if you change the winner of an early one.

&lt;h2&gt;The Code&lt;/h2&gt;

&lt;p&gt;The surprisingly difficult part of this project was creating a simple HTML bracket that
looked reasonable and allowed you to click to advance a team. I didn't get
everything into the page that I wanted to, simply because I spent so much time
just getting that done. (Keep in mind we're talking about a 2-night hack here).

&lt;p&gt;The code to generate the bracket is contained in one super-ugly &lt;a
href="http://github.com/llimllib/ncaa-bracket-randomizer/blob/1db753ce4f91fc84265efa6a27fa7ee00e84eaa2/bracket.py"&gt;python
file&lt;/a&gt;.

&lt;p&gt;If you've got ideas for stuff to add, or want to generate a cooler looking
bracket, or just check out the code, you can &lt;a
href="http://github.com/llimllib/ncaa-bracket-randomizer/tree/master"&gt;go get
it&lt;/a&gt; at github. Feel free to fork and enjoy!
</content>
	</entry>
	<entry>
		<title>Image Programming in JavaScript: Converting to Monochrome</title>
		<link href="http://billmill.org/monotone.html" />	
		<id>http://billmill.org/monotone.html</id>
		<updated>2009-03-05T12:18:00Z</updated>
		<summary type="html">
&lt;p&gt;In &lt;a href="the_histogram.html"&gt;part 1&lt;/a&gt; of this series, we looked at how
each pixel of an image is composed of three parts; red, green and blue, and
showed how to make histograms to give a summary of each. Towards the end, I 
showed that they can be averaged in different ways to create a single
histogram. In this article, we're going to look at the idea of mixing colors
in more depth and show how we can use it to turn color images into monochrome 
in a variety of ways.

&lt;h2&gt;Some Terminology&lt;/h2&gt;

&lt;p&gt;In the last article, we talked about how each pixel is composed of a red,
a green, and a blue component, and how each of those has a value between 0 and
255. What I didn't tell you then was that it's often useful to consider just 
the red components of pixels in an image, just the green components, or just
the blue components.

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;channel&lt;/em&gt; of an image I&lt;sub&gt;1&lt;/sub&gt; is an image
I&lt;sub&gt;2&lt;/sub&gt; composed entirely of one component of I&lt;sub&gt;1&lt;/sub&gt;&lt;/blockquote&gt;

&lt;p&gt;So when we talk about the &lt;em&gt;red channel&lt;/em&gt; of an image, we're talking
about the image that results from simply dropping the green and blue
components of each of its pixels. It's best to see it in action:

&lt;p&gt;&lt;img src="static/images/jump_r_g_b.jpg"&gt;

&lt;p&gt;The first image above can be entirely reconstructed from the last three 
monochrome images, using the first for the red channel, the second for the 
green channel, and the third for the blue. By the end of the article, we'll 
show the code for the &lt;a href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt; 
that was used to convert the color image above into each of the monochrome 
ones.

&lt;h2&gt;Monochrome in Black and White&lt;/h2&gt;

&lt;p&gt;Before we discuss converting a color image into monochrome, it will help to 
understand a bit more about what we mean by monochrome.

&lt;p&gt;Conceptually, we can consider each pixel of a monochrome image to consist of 
just one byte of information, instead of three bytes for red, green and blue as 
in a color image. This byte represents the brightness of a pixel, where 0 is 
black (no brightness) and 255 is white (no brightness). The values in between 
represent the grays, from the dark low numbers to the light high colors.

&lt;p&gt;Since monochrome images are composed of values other than (r, g, b), let's 
update the working definition of a digital image that we used last time:

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;Digital Image&lt;/em&gt; is a sequence of pixels, each of which 
is composed of one or more &lt;em&gt;channels&lt;/em&gt;. The value of each channel 
represents its strength in that pixel.&lt;/blockquote&gt;

&lt;p&gt;So a monochrome image consists of only one channel, that representing the 
brightness of each pixel.

&lt;h2&gt;The Real World Intrudes&lt;/h2&gt;

&lt;p&gt;We've got a nice new mental model of a monochrome image, but the real world, 
as it tends to do, will complicate matters. We're working with color images on 
the &amp;lt;canvas&amp;gt; element, which means that each pixel needs to be composed of 
red, green, and blue. In order to display a monochrome image on a 
&amp;lt;canvas&amp;gt;, we'll need to convert each pixel from one channel, brightness,
to three.

&lt;p&gt;A convenient property of RGB images makes this transformation easy: any 
pixel made up of equal parts red, green, and blue will be gray. Therefore, to 
convert an image from monochrome to RGB, we simply use the brightness channel 
of each pixel in the monochrome image as all three channels in the RGB image.

&lt;h2&gt;Mixing it Up&lt;/h2&gt;

&lt;p&gt;Reversing the process, to create monochrome images from color ones, offers 
us a few more options. For every pixel, our task is to take three channels and 
condense them into one. The obvious thing to do is to simply average them; and 
indeed, this is exactly what happens by default in most photo editing programs 
when you convert an image to monochrome.

&lt;p&gt;There's no reason that we need to limit ourselves to that transformation, 
though. We should consider other options because the average often produces 
flat, uninteresting pictures. Instead, we can mix the channels any way we want 
to produce the most interesting result possible.

&lt;p&gt;I've put up a &lt;a href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt; where 
you can play with the mixture of colors. Simply put numbers into each of the 
three inputs at the bottom of the page and hit "desaturate" to create a 
monochrome image where the channels have been weighted proportionally to the 
numbers you've entered. The histogram below the desaturate button will show you 
the effects of your mix.

&lt;p&gt;Play with the values to find the result you find most pleasing, and notice
how different the images that result from each mix can be.

&lt;h2&gt;Show Me The Goods&lt;/h2&gt;

&lt;p&gt;Here's the important parts of the code in the &lt;a 
href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt;, with the fiddly bits 
stripped out:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; desaturate(rweight&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; gweight&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; bweight) {
  &lt;span style="color: #999988; font-style: italic"&gt;//normalize the color weights&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; scale &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt; &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; (rweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; gweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; bweight);
  rweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  gweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  bweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;

  each_pixel(image_data&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(r&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; g&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; b) {
    &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; brightness &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; r &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; rweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; g &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; gweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; b &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; bweight&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;

    &lt;span style="color: #999988; font-style: italic"&gt;//replace the r, g, and b values of the pixel with &amp;quot;brightness&amp;quot;&lt;/span&gt;
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; [brightness&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; brightness&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; brightness];
  });
}

&lt;span style="color: #999988; font-style: italic"&gt;//red channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//green channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//blue channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//my favorite mix:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;5&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;4&lt;/span&gt;);
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;First we convert the color weights into percentages, then we multiply
each component of each pixel times its weight to arrive at a new value for the
pixel to take. Finally, we use the brightness value we've calculated as the 
value for all three channels to render the image in grayscale.

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;In this article, we've extended our definition of an image to include images 
with channels other than just red, green, and blue. We learned how to convert 
monochrome images for display in RGB, and looked at a couple different ways to 
convert back from RGB to monochrome. Finally, we looked at code to do the 
conversions we'd spent the whole article talking about.

&lt;p&gt;Hopefully you have a pretty good grasp on what an image on a &amp;lt;canvas&amp;gt; 
is by now. If you want to download the code for the demos I've shown so far and 
play with it, go ahead and &lt;a 
href="http://github.com/llimllib/pixastic/tree/master"&gt;check it out&lt;/a&gt; at 
github.

&lt;p&gt;Any comments, criticisms, or thoughts on what you'd like to see me write 
about, you can let me know by sending me an &lt;a 
href="mailto:bill.mill@gmail.com"&gt;email&lt;/a&gt;.
</summary>
		<content type="html">
&lt;p&gt;In &lt;a href="the_histogram.html"&gt;part 1&lt;/a&gt; of this series, we looked at how
each pixel of an image is composed of three parts; red, green and blue, and
showed how to make histograms to give a summary of each. Towards the end, I 
showed that they can be averaged in different ways to create a single
histogram. In this article, we're going to look at the idea of mixing colors
in more depth and show how we can use it to turn color images into monochrome 
in a variety of ways.

&lt;h2&gt;Some Terminology&lt;/h2&gt;

&lt;p&gt;In the last article, we talked about how each pixel is composed of a red,
a green, and a blue component, and how each of those has a value between 0 and
255. What I didn't tell you then was that it's often useful to consider just 
the red components of pixels in an image, just the green components, or just
the blue components.

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;channel&lt;/em&gt; of an image I&lt;sub&gt;1&lt;/sub&gt; is an image
I&lt;sub&gt;2&lt;/sub&gt; composed entirely of one component of I&lt;sub&gt;1&lt;/sub&gt;&lt;/blockquote&gt;

&lt;p&gt;So when we talk about the &lt;em&gt;red channel&lt;/em&gt; of an image, we're talking
about the image that results from simply dropping the green and blue
components of each of its pixels. It's best to see it in action:

&lt;p&gt;&lt;img src="static/images/jump_r_g_b.jpg"&gt;

&lt;p&gt;The first image above can be entirely reconstructed from the last three 
monochrome images, using the first for the red channel, the second for the 
green channel, and the third for the blue. By the end of the article, we'll 
show the code for the &lt;a href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt; 
that was used to convert the color image above into each of the monochrome 
ones.

&lt;h2&gt;Monochrome in Black and White&lt;/h2&gt;

&lt;p&gt;Before we discuss converting a color image into monochrome, it will help to 
understand a bit more about what we mean by monochrome.

&lt;p&gt;Conceptually, we can consider each pixel of a monochrome image to consist of 
just one byte of information, instead of three bytes for red, green and blue as 
in a color image. This byte represents the brightness of a pixel, where 0 is 
black (no brightness) and 255 is white (no brightness). The values in between 
represent the grays, from the dark low numbers to the light high colors.

&lt;p&gt;Since monochrome images are composed of values other than (r, g, b), let's 
update the working definition of a digital image that we used last time:

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;Digital Image&lt;/em&gt; is a sequence of pixels, each of which 
is composed of one or more &lt;em&gt;channels&lt;/em&gt;. The value of each channel 
represents its strength in that pixel.&lt;/blockquote&gt;

&lt;p&gt;So a monochrome image consists of only one channel, that representing the 
brightness of each pixel.

&lt;h2&gt;The Real World Intrudes&lt;/h2&gt;

&lt;p&gt;We've got a nice new mental model of a monochrome image, but the real world, 
as it tends to do, will complicate matters. We're working with color images on 
the &amp;lt;canvas&amp;gt; element, which means that each pixel needs to be composed of 
red, green, and blue. In order to display a monochrome image on a 
&amp;lt;canvas&amp;gt;, we'll need to convert each pixel from one channel, brightness,
to three.

&lt;p&gt;A convenient property of RGB images makes this transformation easy: any 
pixel made up of equal parts red, green, and blue will be gray. Therefore, to 
convert an image from monochrome to RGB, we simply use the brightness channel 
of each pixel in the monochrome image as all three channels in the RGB image.

&lt;h2&gt;Mixing it Up&lt;/h2&gt;

&lt;p&gt;Reversing the process, to create monochrome images from color ones, offers 
us a few more options. For every pixel, our task is to take three channels and 
condense them into one. The obvious thing to do is to simply average them; and 
indeed, this is exactly what happens by default in most photo editing programs 
when you convert an image to monochrome.

&lt;p&gt;There's no reason that we need to limit ourselves to that transformation, 
though. We should consider other options because the average often produces 
flat, uninteresting pictures. Instead, we can mix the channels any way we want 
to produce the most interesting result possible.

&lt;p&gt;I've put up a &lt;a href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt; where 
you can play with the mixture of colors. Simply put numbers into each of the 
three inputs at the bottom of the page and hit "desaturate" to create a 
monochrome image where the channels have been weighted proportionally to the 
numbers you've entered. The histogram below the desaturate button will show you 
the effects of your mix.

&lt;p&gt;Play with the values to find the result you find most pleasing, and notice
how different the images that result from each mix can be.

&lt;h2&gt;Show Me The Goods&lt;/h2&gt;

&lt;p&gt;Here's the important parts of the code in the &lt;a 
href="/static/pixastic/demos/mono_demo.html"&gt;demo&lt;/a&gt;, with the fiddly bits 
stripped out:

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; desaturate(rweight&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; gweight&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; bweight) {
  &lt;span style="color: #999988; font-style: italic"&gt;//normalize the color weights&lt;/span&gt;
  &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; scale &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt; &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; (rweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; gweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; bweight);
  rweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  gweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  bweight &lt;span style="font-weight: bold"&gt;*=&lt;/span&gt; scale&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;

  each_pixel(image_data&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(r&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; g&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; b) {
    &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; brightness &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; r &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; rweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; g &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; gweight &lt;span style="font-weight: bold"&gt;+&lt;/span&gt; b &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; bweight&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;

    &lt;span style="color: #999988; font-style: italic"&gt;//replace the r, g, and b values of the pixel with &amp;quot;brightness&amp;quot;&lt;/span&gt;
    &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; [brightness&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; brightness&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; brightness];
  });
}

&lt;span style="color: #999988; font-style: italic"&gt;//red channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//green channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//blue channel only:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;);

&lt;span style="color: #999988; font-style: italic"&gt;//my favorite mix:&lt;/span&gt;
desaturate(&lt;span style="color: #009999"&gt;5&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;4&lt;/span&gt;);
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;First we convert the color weights into percentages, then we multiply
each component of each pixel times its weight to arrive at a new value for the
pixel to take. Finally, we use the brightness value we've calculated as the 
value for all three channels to render the image in grayscale.

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;In this article, we've extended our definition of an image to include images 
with channels other than just red, green, and blue. We learned how to convert 
monochrome images for display in RGB, and looked at a couple different ways to 
convert back from RGB to monochrome. Finally, we looked at code to do the 
conversions we'd spent the whole article talking about.

&lt;p&gt;Hopefully you have a pretty good grasp on what an image on a &amp;lt;canvas&amp;gt; 
is by now. If you want to download the code for the demos I've shown so far and 
play with it, go ahead and &lt;a 
href="http://github.com/llimllib/pixastic/tree/master"&gt;check it out&lt;/a&gt; at 
github.

&lt;p&gt;Any comments, criticisms, or thoughts on what you'd like to see me write 
about, you can let me know by sending me an &lt;a 
href="mailto:bill.mill@gmail.com"&gt;email&lt;/a&gt;.
</content>
	</entry>
	<entry>
		<title>Image Programming in JavaScript: The Histogram</title>
		<link href="http://billmill.org/the_histogram.html" />	
		<id>http://billmill.org/the_histogram.html</id>
		<updated>2009-02-26T01:14:00Z</updated>
		<summary type="html">&lt;p&gt;Recently, I've spent a lot of my time &lt;a 
href="http://flickr.com/photos/llimllib"&gt;taking photographs&lt;/a&gt;. When I get 
home from taking pictures, I immediately pop open Lightroom to import the 
images, pick out my favorites, do some adjustments on them, and publish them.

&lt;p&gt;As a programmer, though, it was bothering me that I don't know 
&lt;em&gt;exactly&lt;/em&gt; what's happening behind the scenes when I adjusted my images.  
What's &lt;em&gt;really&lt;/em&gt; happening when I adjust the "saturation" slider for a 
photo?  How does sharpening work, and what does its "amount" mean?

&lt;p&gt;Sure, I could go read books to find out, but there's only way to really know 
what's happening: write a program to do it. This article represents part 1 of 
what will hopefully become a series on programming the digital image with 
JavaScript.

&lt;h2&gt;Wait, JavaScript?&lt;/h2&gt;

&lt;p&gt;Sure thing! With the recent adoption of the &amp;lt;canvas&amp;gt; element into 
modern browsers, JavaScript has gained the ability to load, display, and 
manipulate images at the pixel level. In addition, Jacob Seidelin recently 
created the &lt;a href="http://www.pixastic.com/"&gt;Pixastic&lt;/a&gt; library to do the 
heavy DOM and canvas lifting for us.

&lt;p&gt;As much as possible, I'll be using Pixastic as a base because JavaScript is 
a reasonably enjoyable programming language, the framework is new and simple, 
and I can show neat demos right in the browser. I'll also be using &lt;a 
href="http://jquery.com"&gt;jQuery&lt;/a&gt;, because it makes writing cross-browser 
JavaScript much more pleasant.

&lt;h2&gt;Jumping Right In: What Is a Digital Image?&lt;/h2&gt;

&lt;p&gt;In the spirit of &lt;acronym title="You Ain't Gonna Need It"&gt;YAGNI&lt;/acronym&gt;, 
we're going to accept a superficial answer to this question, at least for now.  
We're basically going to pretend that all images are in color and represented 
in the same color space in the same way. Our provisional definition of a 
digital image is this:

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;Digital Image&lt;/em&gt; is a sequence of pixels, each of which 
is represented by a 3-byte tuple (red, green, blue). The value of each element 
represents the strength of that color in that pixel.&lt;/blockquote&gt;

&lt;p&gt;This means that each pixel has a value between 0 and 255, where 0 represents 
absence and 255 full strength. For example, the tuple (255, 0, 0) would 
represent a pure red pixel, the tuple (0, 255, 0) a pure green one, and (0, 0, 
255) a pure blue one.

&lt;div style="float:right"&gt;&lt;img src="/static/images/AdditiveColor.png"&gt;&lt;/div&gt;

&lt;p&gt;Since we're mixing light&lt;sup&gt;&lt;a href="#foot1"&gt;1&lt;/a&gt;&lt;/sup&gt;, the colors are &lt;a 
href="http://en.wikipedia.org/wiki/Additive_color"&gt;additive&lt;/a&gt;, which means 
that they get lighter when mixed. Thus (255, 255, 0) represents a mixture of 
red and green which produces yellow, (0, 255, 255) represents green and blue 
combined to form magenta, and so on as you can see in the chart to the right.

&lt;p&gt;You can think of it is as if you're in a dark room shining colored 
flashlights on a wall; if you don't shine any lights the wall remains black. If 
you shine all three colors on it, you get white. Thus, it makes sense that (0, 
0, 0) represents black and (255, 255, 255) represents white.

&lt;h2&gt;OK, I get it. So what's a Histogram?&lt;/h2&gt;

&lt;div style="float:right"&gt;&lt;img src="/static/images/hist.png"&gt;&lt;/div&gt;

&lt;p&gt;There are of course lots of colors in between the pure ones I talked about 
above, represented by the all the possible color tuples with values between 0 
and 255. In order to understand an image at a glance, it's often helpful to see 
just how often each color occurs in that image. The histogram allows us to do 
just that.

&lt;p&gt;To the right is the basic schematic of a histogram. The y-axis represents 
the frequency of each color value, which are represented on the x-axis. The 
left side of the histogram shows darker colors and the right side lighter.

&lt;p&gt;&lt;blockquote&gt;The &lt;em&gt;histogram&lt;/em&gt; of an image is a chart of how often each 
possible value or range of values for a color occurs in that image&lt;/blockquote&gt;

&lt;p&gt;Below is an image next to the histograms for its red, green, and blue 
values, respectively.

&lt;p&gt;&lt;img src="/static/images/jump_hist.png"&gt;

&lt;p&gt;We can see that there are a lot of light blues, presumably in the the sky, a 
lot of midrange reds and greens, and not a whole lot of dark colors, though 
there is a spike at pure black. I won't go over what a histogram means for your 
photography; you should read what a &lt;a 
href="http://www.luminous-landscape.com/tutorials/understanding-series/understanding-histograms.shtml"&gt;better 
photographer&lt;/a&gt; has to say about that.

&lt;h2&gt;On To The Source&lt;/h2&gt;

&lt;p&gt;There are 2 major steps in creating histograms: gathering the data and 
drawing the histogram. To gather the data, we'll initialize three arrays with 
256 slots, one array slot for each of the color values. Then we'll just loop 
through each pixel in the image and add one in the appropriate histogram slot 
for each color. That's it!

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; array256(default_value) {
  arr &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; [];
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; (&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;=&lt;/span&gt;&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #009999"&gt;256&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;++&lt;/span&gt;) { arr[i] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; default_value&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; }
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; arr&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
}

&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; rvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; gvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; bvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);

each_pixel(image_data&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(r&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; g&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; b) {
  rvals[r]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
  gvals[g]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
  bvals[b]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
});
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Where &lt;code&gt;each_pixel&lt;/code&gt; is simply a function that loops through the 
image and passes the red, green, and blue value of each pixel of its first 
argument to the function passed as its second argument. What we have at the end 
of this code is three arrays, each containing the count of each possible value 
of one color in the image.

&lt;p&gt;To simplify the display of these histograms, we'll draw on a &amp;lt;canvas&amp;gt; 
256 pixels wide, so that each possible color occupies one pixel. Since our 
canvas is only 100 pixels tall, and any histogram value could be greater than 
100, we'll scale each value as the percentage of the maximum value in the 
histogram.

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="color: #999988; font-style: italic"&gt;//get a reference to the canvas to draw on&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; ctx &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; $(&lt;span style="color: #bb8844"&gt;&amp;quot;#colorhistcanvas&amp;quot;&lt;/span&gt;)[&lt;span style="color: #009999"&gt;0&lt;/span&gt;].getContext(&lt;span style="color: #bb8844"&gt;&amp;quot;2d&amp;quot;&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; rmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; rvals);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; bmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; bvals);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; gmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; gvals);

&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; colorbars(max&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; vals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; color&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; y) {
  ctx.fillStyle &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; color&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  jQuery.each(vals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(i&lt;span style="font-weight: bold"&gt;,&lt;/span&gt;x) {
    &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; pct &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; (vals[i] &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; max) &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; &lt;span style="color: #009999"&gt;100&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
    ctx.fillRect(i&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; y&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;-&lt;/span&gt;&lt;span style="color: #999999"&gt;Math&lt;/span&gt;.round(pct));
  });
}

colorbars(rmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; rvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(255,0,0)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;100&lt;/span&gt;);
colorbars(gmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; gvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(0,255,0)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;200&lt;/span&gt;);
colorbars(bmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; bvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(0,0,255)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;300&lt;/span&gt;);
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;You can see this code in action at the top half of the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;histogram demo 
page&lt;/a&gt;. Note that the histograms on that page are being generated by
JavaScript when you load the page, so you can look into the source and
see exactly how the process works.

&lt;h2&gt;A Mean Feat&lt;/h2&gt;

&lt;p&gt;Most of the time, the three histograms are more information than we need.  
Instead, we want to be able to tell at a glance whether we've overexposed or 
underexposed the shot, and a single histogram can give us all the information 
we need. In this case, all we need is an average of the three histograms.

&lt;p&gt;The obvious way to average the three histograms is to weight them all 
equally, sum each value, and divide by three. You'll see this histogram under 
"Average" on the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;demo page&lt;/a&gt;.

&lt;p&gt;However, not all colors appear equally bright to human eyes, so the equally 
weighted histogram is commonly replaced with one more heavily weighted towards 
green, which appears brightest. A commonly given figure is 30% red, 59% green, 
and 11% blue, the results of which you can see in the "weighted average" 
histogram on the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;demo&lt;/a&gt;.

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Hopefully, this article lays a solid base on which I can begin building up 
to show more complex and interesting image transformations with JavaScript and 
Pixastic. It should have given you a basic understanding of how an image is 
formed and how to build several different types of histograms from it. For a 
more detailed understanding, I encourage you to study the code given in the 
demo page; it should all be pretty simple.

&lt;p&gt;If you have any questions or comments, please feel free to drop me &lt;a 
href="mailto:bill.mill@gmail.com"&gt;an email&lt;/a&gt;.

&lt;p&gt;&lt;h5&gt;&lt;a name="foot1"&gt;&lt;sup&gt;1&lt;/sup&gt;: As opposed to pigment, which is governed 
by &lt;a href="http://en.wikipedia.org/wiki/Subtractive_color"&gt;subtractive 
color&lt;/a&gt;&lt;/a&gt;&lt;/h5&gt;
</summary>
		<content type="html">&lt;p&gt;Recently, I've spent a lot of my time &lt;a 
href="http://flickr.com/photos/llimllib"&gt;taking photographs&lt;/a&gt;. When I get 
home from taking pictures, I immediately pop open Lightroom to import the 
images, pick out my favorites, do some adjustments on them, and publish them.

&lt;p&gt;As a programmer, though, it was bothering me that I don't know 
&lt;em&gt;exactly&lt;/em&gt; what's happening behind the scenes when I adjusted my images.  
What's &lt;em&gt;really&lt;/em&gt; happening when I adjust the "saturation" slider for a 
photo?  How does sharpening work, and what does its "amount" mean?

&lt;p&gt;Sure, I could go read books to find out, but there's only way to really know 
what's happening: write a program to do it. This article represents part 1 of 
what will hopefully become a series on programming the digital image with 
JavaScript.

&lt;h2&gt;Wait, JavaScript?&lt;/h2&gt;

&lt;p&gt;Sure thing! With the recent adoption of the &amp;lt;canvas&amp;gt; element into 
modern browsers, JavaScript has gained the ability to load, display, and 
manipulate images at the pixel level. In addition, Jacob Seidelin recently 
created the &lt;a href="http://www.pixastic.com/"&gt;Pixastic&lt;/a&gt; library to do the 
heavy DOM and canvas lifting for us.

&lt;p&gt;As much as possible, I'll be using Pixastic as a base because JavaScript is 
a reasonably enjoyable programming language, the framework is new and simple, 
and I can show neat demos right in the browser. I'll also be using &lt;a 
href="http://jquery.com"&gt;jQuery&lt;/a&gt;, because it makes writing cross-browser 
JavaScript much more pleasant.

&lt;h2&gt;Jumping Right In: What Is a Digital Image?&lt;/h2&gt;

&lt;p&gt;In the spirit of &lt;acronym title="You Ain't Gonna Need It"&gt;YAGNI&lt;/acronym&gt;, 
we're going to accept a superficial answer to this question, at least for now.  
We're basically going to pretend that all images are in color and represented 
in the same color space in the same way. Our provisional definition of a 
digital image is this:

&lt;p&gt;&lt;blockquote&gt;A &lt;em&gt;Digital Image&lt;/em&gt; is a sequence of pixels, each of which 
is represented by a 3-byte tuple (red, green, blue). The value of each element 
represents the strength of that color in that pixel.&lt;/blockquote&gt;

&lt;p&gt;This means that each pixel has a value between 0 and 255, where 0 represents 
absence and 255 full strength. For example, the tuple (255, 0, 0) would 
represent a pure red pixel, the tuple (0, 255, 0) a pure green one, and (0, 0, 
255) a pure blue one.

&lt;div style="float:right"&gt;&lt;img src="/static/images/AdditiveColor.png"&gt;&lt;/div&gt;

&lt;p&gt;Since we're mixing light&lt;sup&gt;&lt;a href="#foot1"&gt;1&lt;/a&gt;&lt;/sup&gt;, the colors are &lt;a 
href="http://en.wikipedia.org/wiki/Additive_color"&gt;additive&lt;/a&gt;, which means 
that they get lighter when mixed. Thus (255, 255, 0) represents a mixture of 
red and green which produces yellow, (0, 255, 255) represents green and blue 
combined to form magenta, and so on as you can see in the chart to the right.

&lt;p&gt;You can think of it is as if you're in a dark room shining colored 
flashlights on a wall; if you don't shine any lights the wall remains black. If 
you shine all three colors on it, you get white. Thus, it makes sense that (0, 
0, 0) represents black and (255, 255, 255) represents white.

&lt;h2&gt;OK, I get it. So what's a Histogram?&lt;/h2&gt;

&lt;div style="float:right"&gt;&lt;img src="/static/images/hist.png"&gt;&lt;/div&gt;

&lt;p&gt;There are of course lots of colors in between the pure ones I talked about 
above, represented by the all the possible color tuples with values between 0 
and 255. In order to understand an image at a glance, it's often helpful to see 
just how often each color occurs in that image. The histogram allows us to do 
just that.

&lt;p&gt;To the right is the basic schematic of a histogram. The y-axis represents 
the frequency of each color value, which are represented on the x-axis. The 
left side of the histogram shows darker colors and the right side lighter.

&lt;p&gt;&lt;blockquote&gt;The &lt;em&gt;histogram&lt;/em&gt; of an image is a chart of how often each 
possible value or range of values for a color occurs in that image&lt;/blockquote&gt;

&lt;p&gt;Below is an image next to the histograms for its red, green, and blue 
values, respectively.

&lt;p&gt;&lt;img src="/static/images/jump_hist.png"&gt;

&lt;p&gt;We can see that there are a lot of light blues, presumably in the the sky, a 
lot of midrange reds and greens, and not a whole lot of dark colors, though 
there is a spike at pure black. I won't go over what a histogram means for your 
photography; you should read what a &lt;a 
href="http://www.luminous-landscape.com/tutorials/understanding-series/understanding-histograms.shtml"&gt;better 
photographer&lt;/a&gt; has to say about that.

&lt;h2&gt;On To The Source&lt;/h2&gt;

&lt;p&gt;There are 2 major steps in creating histograms: gathering the data and 
drawing the histogram. To gather the data, we'll initialize three arrays with 
256 slots, one array slot for each of the color values. Then we'll just loop 
through each pixel in the image and add one in the appropriate histogram slot 
for each color. That's it!

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; array256(default_value) {
  arr &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; [];
  &lt;span style="font-weight: bold"&gt;for&lt;/span&gt; (&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;=&lt;/span&gt;&lt;span style="color: #009999"&gt;0&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #009999"&gt;256&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; i&lt;span style="font-weight: bold"&gt;++&lt;/span&gt;) { arr[i] &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; default_value&lt;span style="font-weight: bold"&gt;;&lt;/span&gt; }
  &lt;span style="font-weight: bold"&gt;return&lt;/span&gt; arr&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
}

&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; rvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; gvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; bvals &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; array256(&lt;span style="color: #009999"&gt;0&lt;/span&gt;);

each_pixel(image_data&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(r&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; g&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; b) {
  rvals[r]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
  gvals[g]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
  bvals[b]&lt;span style="font-weight: bold"&gt;++;&lt;/span&gt;
});
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Where &lt;code&gt;each_pixel&lt;/code&gt; is simply a function that loops through the 
image and passes the red, green, and blue value of each pixel of its first 
argument to the function passed as its second argument. What we have at the end 
of this code is three arrays, each containing the count of each possible value 
of one color in the image.

&lt;p&gt;To simplify the display of these histograms, we'll draw on a &amp;lt;canvas&amp;gt; 
256 pixels wide, so that each possible color occupies one pixel. Since our 
canvas is only 100 pixels tall, and any histogram value could be greater than 
100, we'll scale each value as the percentage of the maximum value in the 
histogram.

&lt;p&gt;&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span style="color: #999988; font-style: italic"&gt;//get a reference to the canvas to draw on&lt;/span&gt;
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; ctx &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; $(&lt;span style="color: #bb8844"&gt;&amp;quot;#colorhistcanvas&amp;quot;&lt;/span&gt;)[&lt;span style="color: #009999"&gt;0&lt;/span&gt;].getContext(&lt;span style="color: #bb8844"&gt;&amp;quot;2d&amp;quot;&lt;/span&gt;);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; rmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; rvals);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; bmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; bvals);
&lt;span style="font-weight: bold"&gt;var&lt;/span&gt; gmax &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; &lt;span style="color: #999999"&gt;Math&lt;/span&gt;.max.apply(&lt;span style="font-weight: bold"&gt;null,&lt;/span&gt; gvals);

&lt;span style="font-weight: bold"&gt;function&lt;/span&gt; colorbars(max&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; vals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; color&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; y) {
  ctx.fillStyle &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; color&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
  jQuery.each(vals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;function&lt;/span&gt;(i&lt;span style="font-weight: bold"&gt;,&lt;/span&gt;x) {
    &lt;span style="font-weight: bold"&gt;var&lt;/span&gt; pct &lt;span style="font-weight: bold"&gt;=&lt;/span&gt; (vals[i] &lt;span style="font-weight: bold"&gt;/&lt;/span&gt; max) &lt;span style="font-weight: bold"&gt;*&lt;/span&gt; &lt;span style="color: #009999"&gt;100&lt;/span&gt;&lt;span style="font-weight: bold"&gt;;&lt;/span&gt;
    ctx.fillRect(i&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; y&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;1&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="font-weight: bold"&gt;-&lt;/span&gt;&lt;span style="color: #999999"&gt;Math&lt;/span&gt;.round(pct));
  });
}

colorbars(rmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; rvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(255,0,0)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;100&lt;/span&gt;);
colorbars(gmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; gvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(0,255,0)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;200&lt;/span&gt;);
colorbars(bmax&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; bvals&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #bb8844"&gt;&amp;quot;rgb(0,0,255)&amp;quot;&lt;/span&gt;&lt;span style="font-weight: bold"&gt;,&lt;/span&gt; &lt;span style="color: #009999"&gt;300&lt;/span&gt;);
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;You can see this code in action at the top half of the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;histogram demo 
page&lt;/a&gt;. Note that the histograms on that page are being generated by
JavaScript when you load the page, so you can look into the source and
see exactly how the process works.

&lt;h2&gt;A Mean Feat&lt;/h2&gt;

&lt;p&gt;Most of the time, the three histograms are more information than we need.  
Instead, we want to be able to tell at a glance whether we've overexposed or 
underexposed the shot, and a single histogram can give us all the information 
we need. In this case, all we need is an average of the three histograms.

&lt;p&gt;The obvious way to average the three histograms is to weight them all 
equally, sum each value, and divide by three. You'll see this histogram under 
"Average" on the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;demo page&lt;/a&gt;.

&lt;p&gt;However, not all colors appear equally bright to human eyes, so the equally 
weighted histogram is commonly replaced with one more heavily weighted towards 
green, which appears brightest. A commonly given figure is 30% red, 59% green, 
and 11% blue, the results of which you can see in the "weighted average" 
histogram on the &lt;a 
href="http://billmill.org/static/pixastic/demos/hist_demo.html"&gt;demo&lt;/a&gt;.

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Hopefully, this article lays a solid base on which I can begin building up 
to show more complex and interesting image transformations with JavaScript and 
Pixastic. It should have given you a basic understanding of how an image is 
formed and how to build several different types of histograms from it. For a 
more detailed understanding, I encourage you to study the code given in the 
demo page; it should all be pretty simple.

&lt;p&gt;If you have any questions or comments, please feel free to drop me &lt;a 
href="mailto:bill.mill@gmail.com"&gt;an email&lt;/a&gt;.

&lt;p&gt;&lt;h5&gt;&lt;a name="foot1"&gt;&lt;sup&gt;1&lt;/sup&gt;: As opposed to pigment, which is governed 
by &lt;a href="http://en.wikipedia.org/wiki/Subtractive_color"&gt;subtractive 
color&lt;/a&gt;&lt;/a&gt;&lt;/h5&gt;
</content>
	</entry>
</feed>
