<?xml version="1.0" encoding="UTF-8"?><feed
  xmlns="http://www.w3.org/2005/Atom"
  xmlns:thr="http://purl.org/syndication/thread/1.0"
  xml:lang="en"
  >
  <id>http://livingcode.org/feed/atom</id>
  <updated>2009-11-13T19:33:25Z</updated>
  <title type="text">Living Code</title>
  <subtitle type="text">Programming for the Fun of It</subtitle>
  <link rel="self" type="application/atom+xml" href="http://livingcode.org/feed" />
  <link rel="alternate" href="http://livingcode.org" />
  <rights type="text">Copyright 2009</rights>
  <generator uri="http://wordpress.org/" version="2.8.6">WordPress</generator>
      <entry>
    <id>http://livingcode.org/?p=179</id>
    <title type="html"><![CDATA[Go Language and Functional Programming]]></title>
    <updated>2009-11-13T19:33:25Z</updated>
    <published>2009-11-13T19:33:25Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/11/13/go-language-and-functional-programming/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/11/13/go-language-and-functional-programming" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[There is a cool new language on the block, coming from The Google courtesy of (among others) Rob Pike and Ken Thompson. The language is called Go (and the debugger is called Ogle, so put &#8216;em together for a secret message) and it attempts to be both a low-level, type-safe, compiled language, like C, while [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/11/13/go-language-and-functional-programming"><![CDATA[<p>There is a cool new language on the block, coming from The Google courtesy of (among others) Rob Pike and Ken Thompson. The language is called <a href="http://golang.org/">Go</a> (and the debugger is called Ogle, so put &#8216;em together for a secret message) and it attempts to be both a low-level, type-safe, compiled language, like C, while being garbage-collected, concise, with high-level structures and idioms like Python and Javascript. There are a lot of things to like in it, and I am exploring what it can and cannot do.  My first question was whether you could use it for functional programming, i.e., are functions first-class objects that can be passed to other functions, returned from functions, stored in variables, etc. This wasn&#8217;t in the <a href="http://golang.org/doc/go_faq.html">FAQ</a> or the <a href="http://golang.org/doc/go_lang_faq.html">Language Design FAQ</a>, but there were some hints of it in the description of channels, so I went ahead and wrote my own tests to see if it would work.</p>
<p><code><br />
    package main</p>
<p>    import fmt "fmt"</p>
<p>    type Stringy func() string</p>
<p>    func foo() string{<br />
         return "Stringy function"<br />
    }</p>
<p>    func takesAFunction(foo Stringy){<br />
        fmt.Printf("takesAFunction: %v\n", foo())<br />
    }</p>
<p>    func returnsAFunction()Stringy{<br />
        return func()string{<br />
            fmt.Printf("Inner stringy function\n");<br />
            return "bar" // have to return a string to be stringy<br />
        }<br />
    }</p>
<p>    func main(){<br />
        takesAFunction(foo);<br />
        var f Stringy = returnsAFunction();<br />
        f();<br />
        var baz Stringy = func()string{<br />
            return "anonymous stringy\n"<br />
        };<br />
        fmt.Printf(baz());<br />
    }<br />
</code></p>
<p>This compiled and ran, giving the right output, so it looks to me like functional programming is indeed possible in Go, and on the <a href="http://golang.org/doc/effective_go.html">Effective Go</a> page we learn, &#8220;In Go, function literals are closures: the implementation makes sure the variables referred to by the function survive as long as they are active.&#8221; So that&#8217;s kind of cool.</p>
<p>Go also has rich, high-level concurrency support similar to <a href="http://erlang.org/">Erlang</a>, several features that prevent random memory from being read or written, and both strings and maps (dictionaries, hash tables) are built-in datatypes. It has a small, but powerful standard library.</p>
<p>One puzzle down, several to go. I still want to explore how I can talk to <a href="http://developer.apple.com/cocoa/">Cocoa</a> from Go (for GUIs), how to wrap libraries such as <a href="http://xmlsoft.org/">libxml2</a> and <a href="http://www.cairographics.org/">cairo</a> for Go, and basically how to map more Python/Javascript library goodness into Go&#8217;s world. </p>
<p>I have smaller questions too: can I add methods to existing types? How do I load the contents of a URL? It&#8217;s looking good so far! Tune in next time for more exploration.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/?p=140</id>
    <title type="html"><![CDATA[Moped Syndrome]]></title>
    <updated>2009-07-23T18:16:37Z</updated>
    <published>2009-07-23T18:16:37Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/07/23/moped-syndrome/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/07/23/moped-syndrome" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[[This is an essay I wrote in 2002, found in an old journal]
What do you get when you cross a clock and a computer: a computer.  An
airplane and computer: computer.  A VCR and computer: computer. [This argument I believe was my summary of something Donald Norman said in The Design of Everyday Things.]
Of [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/07/23/moped-syndrome"><![CDATA[<p>[This is an essay I wrote in 2002, found in an old journal]</p>
<p>What do you get when you cross a clock and a computer: a computer.  An<br />
airplane and computer: computer.  A VCR and computer: computer. [This argument I believe was my summary of something Donald Norman said in The Design of Everyday Things.]</p>
<p>Of course, computer here is used as a code word for Something which is<br />
perverse and complicated, which most computer *are*, but they don&#8217;t have to<br />
be.  It doesn&#8217;t imply that you can program your clock radio with Python, for<br />
instance.</p>
<p>These are examples of moped compromises.  I owned a moped once.  It was too<br />
heavy to pedal and too underpowered to go up hills.  It combined all the<br />
<em>worst features</em> of bicycles and motorcycles, with few of the advantages of<br />
either.</p>
<p>These bad compromises are everywhere. When I studied to be an <abbr title="Emergency Medical Technician">EMT</abbr>, we learned<br />
some Greek and Latin, a little CPR, but mostly we learned how to cover our<br />
asses in case we were sued.  By becoming professionals we would no longer be<br />
covered by Good Samaritan laws, and the nature of the job (trying like hell to<br />
save somebody&#8217;s life, often when it&#8217;s too late) meant lots of times the<br />
patients died or lost a limb or whatever.  Whenever the outcome is less than<br />
optimal, the American knee-jerk reaction is to sue.  So we inadvertently<br />
became lawyers.</p>
<p>What do you get when you cross a paramedic with a lawyer: A paralegal.</p>
<p>Now I&#8217;m in computing and it seems that just writing code, pretty simple and<br />
harmless code, not viruses or anything like that, can get you thrown in jail<br />
or sued in all kinds of remarkable and unpredictable ways.  In fact, you can<br />
break the law without even knowing it, because what you&#8217;ve created is already<br />
a secret.  Add that to the awesome array of software licenses and we&#8217;re<br />
inadvertently becoming lawyers again (or outlaws).</p>
<p>What do you get when you cross a computer scientist with a lawyer: A lawyer.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/aspect-oriented-python</id>
    <title type="html"><![CDATA[Aspect-oriented Python]]></title>
    <updated>2009-02-25T06:09:18Z</updated>
    <published>2009-02-25T06:09:18Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/24/aspect-oriented-python/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/24/aspect-oriented-python" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[A friend asked me for an example of AOP in Python.  I started to write up my response, then realized it might be worth sharing more widely.
Briefly, AOP is about separating out Aspects which are are interspersed throughout your code (in AOP lingo, cross-cutting).  The canonical example is logging, but there are others.
For [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/24/aspect-oriented-python"><![CDATA[<p>A friend asked me for an example of <abbr title="Aspect-Oriented Programming">AOP</abbr> in Python.  I started to write up my response, then realized it might be worth sharing more widely.</p>
<p>Briefly, <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a> is about separating out <em>Aspects</em> which are are interspersed throughout your code (in AOP lingo, cross-cutting).  The canonical example is logging, but there are others.</p>
<p>For Python, as long as you&#8217;re content with before/after aspects, the situation is good.  In Python 2.5 and up there are two main tactics: decorators and context managers.  Decorators use the @ syntax and context managers are used with the &#8220;with&#8221; keyword.</p>
<h3>Decorators</h3>
<p>Decorators are only usable on functions and methods in 2.4 and 2.5, but in 2.6, 3.0 and beyond they can be used on classes as well.  Essentially they are callables (functions, methods, objects) that accept a function object and return a function object.  They are called when the function is defined, so they get a chance to have their way with it: annotate it, replace it, or wrap it.  The common case is to wrap it.</p>
<p>Quick example:</p>
<p><code>
<pre>
import logging
def before(fn):
    def wrapped(*args, **kws):
        logging.warn('about to call function %s' % fn.func_name)
        return fn(*args, **kws)
    return wrapped

def after(fn):
    def wrapped(*args, **kws):
        retVal = fn(*args, **kws)
        logging.warn('just returned from function %s' % fn.func_name)
        return retVal
    return wrapped
</pre>
<p></code></p>
<p>OK, those are three basic wrappers, you can use them like so:</p>
<p><code>
<pre>
@before
def foo():
    logging.warn('inside foo')

@after
def bar():
    logging.warn('inside bar')

@before
@after
def baz():
    logging.warn('inside baz')

foo()
bar()
baz()
</pre>
<p></code></p>
<p>This will result in the following output:</p>
<p><code>
<pre>
WARNING:root:about to call function foo
WARNING:root:inside foo
WARNING:root:inside bar
WARNING:root:just returned from function bar
WARNING:root:about to call function wrapped
WARNING:root:inside baz
WARNING:root:just returned from function baz
</pre>
<p></code></p>
<p>You will note that when we use two decorators on baz, the name of the function called by <code>before</code> is &#8220;wrapped.&#8221; This is because what <code>before</code> is called on is the result of <code>after</code>.  The <code>functools.update_wrapper</code> function is useful in this case to make a wrapped function look more like the original function.</p>
<p>For more, please see <a href="http://www.python.org/dev/peps/pep-0318/#examples">PEP 318 Decorators for Functions and Methods: Examples</a> and <a href="http://www.python.org/dev/peps/pep-3129/">PEP 3129 Class Decorators</a>. For convenience when creating new decorators, see the standard library functions <a href="http://docs.python.org/library/functools.html#functools.update_wrapper">functools.update_wrapper</a> and <a href="http://docs.python.org/library/functools.html#functools.wraps">functools.wraps</a>.</p>
<h3>Context Managers</h3>
<p>Context Managers are used with the <code>with</code> statement, and are handy for resource aquisition and release.  In Python 2.5 you have to &#8220;from __future__ import with_statement&#8221; to use them, but they are built-in in Python versions later than that. Also, objects such as files and locks are context managers now, so you can use patterns like</p>
<p><code>
<pre>
with open('example.txt') as example:
    for line in example:
        do_something(line)
</pre>
<p></code></p>
<p>This will automatically close the file when leaving the <code>with</code> block. And for locks the pattern is similar:</p>
<p><code>
<pre>
with myThreadingLock:
    do_something_threadsafely()
</pre>
<p></code></p>
<p>It is important to note that the lock will be release properly, or the file closed, even if an exception is thrown inside the <code> with</code> block.</p>
<p>If you want to create your own context managers, you can add two methods to your objects: <code>__enter__(self)</code> and <code>__exit__(self, exception_type, exception_value, traceback)</code>.  The return value from <code>__enter__</code> will be passed to the optional <code>as</code> variable (seen in the file example). The <code>__exit__</code> method will be called with exception info if there was an exception.  If no exception is raised in the <code>with</code> block, then all three arguements will be <code>None</code>.  If <code>__exit__</code> returns <code>True</code> then any exception will be &#8220;swallowed&#8221;, otherwise the exception will be re-raised after any cleanup.</p>
<p>For more info, see <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343 The &#8220;with&#8221; Statement</a>, especially the examples section, and also the helper functions in the standard library <a href="http://docs.python.org/library/contextlib.html">contextlib</a>.</p>
<h3>AOP and 80/20</h3>
<p>Full-on aspect-oriented programming is beyond the scope of this post and involves join-points, code weaving, and other such arcanery.  There are multiple Python libraries which target aspect-oriented coding styles, but for my money, the simplicity of the methods in the standard library, coupled with my impression that they cover at least 80% of the uses of AOP, make me favour these built-in techniques over any of the special purpose tools.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/balding-for-dollars-update</id>
    <title type="html"><![CDATA[Balding for Dollars Update]]></title>
    <updated>2009-02-17T05:49:12Z</updated>
    <published>2009-02-17T05:49:12Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/16/balding-for-dollars-update/feed" thr:count="1"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/16/balding-for-dollars-update" />
    <category scheme="http://livingcode.org" term="Projects" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[
Well, my Balding for Dollars event was a success.  I have raised $717.37 for Children&#8217;s Hospital (there is still time to help bring it to my goal of $1000 if you&#8217;d like to donate). Thanks to everyone who helped with donations, words of support, and especially to Frank for his photography, to Berenice for [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/16/balding-for-dollars-update"><![CDATA[<p><img src='http://livingcode.org/wp-content/uploads/2009/02/balding_after.jpg' alt='balding_after.jpg' /></p>
<p>Well, my Balding for Dollars event was a success.  I have raised $717.37 for Children&#8217;s Hospital (there is still time to help bring it to my goal of $1000 if you&#8217;d like to <a href="http://bcchf.kintera.org/balding/livingcode">donate</a>). Thanks to everyone who helped with donations, words of support, and especially to <a href="http://flee.com/">Frank</a> for his photography, to Berenice for helping with the cutting, to my wife <a href="http://strangeplaces.livingcode.org/">Daniela</a> for her encouragement and help, and to our kids for their patience.  I couldn&#8217;t have done it without all of you.</p>
<p>There has been one change of plans.  I had wanted to donate the hair to a Canadian foundation making wigs for kids with cancer, but couldn&#8217;t find it.  Daniela&#8217;s google-fu skills were better and tomorrow my hair will go off to the Eva and Co. <a href="http://www.evaandcowigs.com/page129.htm">hair donation</a> program. And to clarify, my daughter didn&#8217;t shave her head, we&#8217;re sending a ponytail from when she went from a long hairstyle to a short one.</p>
<p>Thanks also, to everyone who offered me a toque, but I&#8217;m well covered.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/balding-for-dollars</id>
    <title type="html"><![CDATA[Balding for dollars]]></title>
    <updated>2009-02-13T18:27:50Z</updated>
    <published>2009-02-12T06:16:55Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/11/balding-for-dollars/feed" thr:count="1"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/11/balding-for-dollars" />
    <category scheme="http://livingcode.org" term="Kids" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[
I usually use this site to try to give back to the community, with Python and Javascript tutorials, software, and the occasional joke. Today I&#8217;m going to ask for something in return.  On Saturday, February 14th, 2009 (Valentine&#8217;s Day, at least in the US and Canada) I will be shaving my head to raise [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/11/balding-for-dollars"><![CDATA[<p><img src='http://livingcode.org/wp-content/uploads/2009/02/balding_profile2.jpg' alt='balding_profile2.jpg' /></p>
<p>I usually use this site to try to give back to the community, with Python and Javascript tutorials, software, and the occasional joke. Today I&#8217;m going to ask for something in return.  On Saturday, February 14th, 2009 (Valentine&#8217;s Day, at least in the US and Canada) I will be shaving my head to raise money for Vancouver Children&#8217;s Hospital as part of their <a href="http://bcchf.kintera.org/balding/livingcode">Balding for Dollars</a> drive.</p>
<p>The picture above was taken today by my friend <a href="http://flee.com/">Frank Lee</a>.  As you can see, my hair is quite long.  I&#8217;ll be sending my ponytail to <a href="http://www.locksoflove.org/">Locks of Love</a>, who make a wigs for kids who have lost their hair due to medical conditions.  This is my second balding for dollars and will be the fourth ponytail I&#8217;ve donated, and my daughter is also donating her ponytail.  As I get older, my hair isn&#8217;t growing in like it used to. This may be my last good ponytail to give, so with your help, I&#8217;d like to make a difference.</p>
<p>You can make donations on the Balding for Dollars site <a href="http://bcchf.kintera.org/balding/livingcode">here</a>.  Saturday is only two days away, so be my valentine and help some kids!</p>
<p>I appreciate any help you can give.  Check back on Monday for before/after photos.  Thank you!</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/unit-testing-in-vancouver</id>
    <title type="html"><![CDATA[Unit Testing in Vancouver]]></title>
    <updated>2009-02-02T18:56:41Z</updated>
    <published>2009-02-02T18:55:49Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/02/02/unit-testing-in-vancouver/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/02/02/unit-testing-in-vancouver" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[Just a quick reminder: Henry Prêcheur will be presenting Unit Testing in Python at the VanPyZ meeting tomorrow, February 3rd. The meeting will be at Workspace in Gastown (see map on VanPyZ page).  Meetings are from 7-8:30, then we head out for beers afterwards.
Hope to see you there!
]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/02/02/unit-testing-in-vancouver"><![CDATA[<p>Just a quick reminder: Henry Prêcheur will be presenting Unit Testing in Python at the <a href="http://vanpyz.org/">VanPyZ</a> meeting tomorrow, February 3rd. The meeting will be at Workspace in Gastown (see map on VanPyZ page).  Meetings are from 7-8:30, then we head out for beers afterwards.</p>
<p>Hope to see you there!</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/tab-dumping-with-applescript-and-back-to-python</id>
    <title type="html"><![CDATA[Tab Dumping with AppleScript and back to Python]]></title>
    <updated>2009-01-31T20:04:19Z</updated>
    <published>2009-01-31T19:58:31Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python" />
    <category scheme="http://livingcode.org" term="Mac" />
    <category scheme="http://livingcode.org" term="Projects" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[
Goal: Iterate through all my (OS X Safari) browser windows and make a list of titles and urls which is then placed in the clipboard ready to be pasted into an email or blog post.
This is an update to Tab Dumping in Safari. That still works well as the basis for extending any Cocoa-based application [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/01/31/tab-dumping-with-applescript-and-back-to-python"><![CDATA[<p><img src='http://livingcode.org/wp-content/uploads/2009/01/rock.jpg' alt='Rock' /></p>
<p><strong>Goal:</strong> Iterate through all my (OS X Safari) browser windows and make a list of titles and urls which is then placed in the clipboard ready to be pasted into an email or blog post.</p>
<p>This is an update to <a href="http://livingcode.org/2006/tab-dumping-in-safari">Tab Dumping in Safari</a>. That still works well as the basis for extending any Cocoa-based application at runtime, but it relies on SIMBL, which while it is a great bit of code, essentially is abusing the InputManager interface.  Some developers and users shun such hacks, and at least one Apple application checks for them at startup and warns you from using them.</p>
<p>I have been running the <a href="http://webkit.org/">WebKit</a> nightlies, which are like Safari, but with newer code and features (most importantly to me right now, a Firebug-like developer toolkit).  WebKit warns at startup that if you&#8217;re running extensions (such as SIMBL plugins) it may make the application less stable.  I was running both <a href="http://haoli.dnsalias.com/">Saft</a> and my own tab dumping plugin, and WebKit was crashing a lot.  So I removed those and the crashes went away.  I miss a handful of the Saft extensions (but not having to update it for every Safari point release), and I found I <em>really</em> miss my little tab-dumping tool.</p>
<p>I toyed with the idea of rewriting it as a service, which would then be available from the services menu, but couldn&#8217;t figure out how to access the application&#8217;s windows and tabs from the service.  So I tried looking at Safari&#8217;s scriptable dictionary, using the AppleScript Script Editor.  Long ago, John Gruber had <a href="http://daringfireball.net/2003/05/safaris_unscriptable_tabs">written</a> about the frustration with Safari&#8217;s tabs not being scriptable, but a glance at the scripting dictionary showed me this was no longer the case (and probably hasn&#8217;t been for years, I haven&#8217;t kept track).</p>
<p>I am a complete n00b at AppleScript.  I find the attempt at English-like syntax just confuses (and irritates) me no end.  But what I wanted looked achievable with it, so I armed myself with some examples from Google searches, and Apple&#8217;s intro pages and managed to get what I wanted working.  It may not be the best possible solution (in fact I suspect the string concatenation may be one of the most pessimal methods), but it Works For Me™.</p>
<p>In Script Editor, paste in the following:</p>
<p><code>
<pre>
set url_list to ""
-- change WebKit to Safari if you are not running nightlies
tell application "WebKit"
  set window_list to windows
  repeat with w in window_list
    try
      set tab_list to tabs of w
      repeat with t in tab_list
        set url_list to url_list &#038; name of t &#038; "\n"
        set url_list to url_list &#038; URL of t &#038; "\n\n"
      end repeat
    on error
      -- not all windows have tabs
    end try
  end repeat
  set the clipboard to url_list
end tell
</pre>
<p></code></p>
<p>I had to use AppleScript Utility to add the script menu to my menu bar.  From there it was easy to create script folders that are specific to both WebKit and Safari and save a copy of the script (with the appropriate substitution, see comment in script) into each folder.  Now I can copy the title and URL of all my open tabs onto the clipboard easily again, without any InputManager hacks.</p>
<p>I had some recollection that is a way to do this from Python, so I looked and found <a href="http://appscript.sourceforge.net/">Appscript</a>.  I was able to install this with a simple <code>easy_install appscript</code> and quickly ported most of the applescript to Python.  The only stumbling block was that I couldn&#8217;t find a way to access the clipboard with appscript, and I didn&#8217;t want to have to pull in the PyObjC framework just to write to the clipboard. So I used <code>subprocess</code> to call the command-line <code>pbcopy</code> utility.</p>
<p><code>
<pre>
#!/usr/local/bin/python
from appscript import app
import subprocess
tab_summaries = []
for window in app('WebKit').windows.get():
    try:
        for tab in window.tabs.get():
            name = tab.name.get().encode('utf-8')
            url = tab.URL.get().encode('utf-8')
            tab_summaries.append('%s\n%s' % (name, url))
    except:
        # not all windows have tabs
        pass
clipboard = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
clipboard.stdin.write('\n\n'.join(tab_summaries))
</pre>
<p></code></p>
<p>The remaining hurdle was simply to put the Python script I&#8217;d written into the same Scripting folder as my AppleScript version. For me this was <code>~/Library/Scripts/Applications/WebKit/</code>. When run from the scripts folder, your usual environment is not inherited, so the <code>#!</code> line must point to the version of Python you are using (and which has Appscript installed). You should also make the script executable.  Adding <code>.py</code> or any other extension is not necessary.</p>
<p>Overall, while I found AppleScript to be very powerful, and not quite as painful as I remembered, I found the Python version (warts and all) to be easier to work with. Combined with the fact that the script folder will run non-Applescript scripts, this opens up new worlds for me.  I have hesitated in the past to write a lot of SIMBL-based plugins, tempting though it may be, because they are hacks, and they run in <em>every</em> Cocoa-based application.  But adding application-specific (or universal) scripts, in Python, is pure, unadulterated goodness.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2009/first-vanpyz-of-2009</id>
    <title type="html"><![CDATA[First VanPyZ of 2009]]></title>
    <updated>2009-01-08T19:06:22Z</updated>
    <published>2009-01-08T06:28:53Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2009/01/07/first-vanpyz-of-2009/feed" thr:count="0"  />
    <link rel="alternate" href="http://livingcode.org/2009/01/07/first-vanpyz-of-2009" />
    <category scheme="http://livingcode.org" term="Python" />
    <summary type="html"><![CDATA[I really need to start blogging these before they happen, but I will at least try to summarize the January Vancouver Python user group meeting.  Our featured speaker wasn&#8217;t able to make it, and it was only with the nudging of Andy and the gracious help of Jim and Dane at Workspace that we [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2009/01/07/first-vanpyz-of-2009"><![CDATA[<p>I really need to start blogging these <em>before</em> they happen, but I will at least try to summarize the January <a href="http://vanpyz.org/">Vancouver Python user group</a> meeting.  Our featured speaker wasn&#8217;t able to make it, and it was only with the nudging of <a href="http://www.agmweb.ca/blog/andy/">Andy</a> and the gracious help of <a href="http://jimpick.com/">Jim</a> and <a href="http://www.abetterplacetowork.com/">Dane</a> at <a href="http://www.abetterplacetowork.com/">Workspace</a> that we even had a January meeting.  But a meeting was had, a surprising number of people braved the heavy rain, and we had a good time talking about our varied interests and explorations, mostly with a Python theme.</p>
<p><strong>What I did over winter vacation</strong></p>
<p>We had an open discussion, starting with the nominal topic of the night, Python packaging.  We discussed some of the pros and cons of <a href="http://docs.python.org/library/distutils.html">distutils</a>, <a href="http://peak.telecommunity.com/DevCenter/setuptools">setuptools</a>, and <a href="http://peak.telecommunity.com/DevCenter/EasyInstall">easy_install</a>. Our casual conclusion was that all of these tools work better if you first use Ian Bicking&#8217;s <a href="http://blog.ianbicking.org/2007/10/10/workingenv-is-dead-long-live-virtualenv/">VirtualEnv</a> to prevent library pollution in your main Python install.  VirtualEnv puts a copy of Python, your required libraries, and any dependencies they have into a separate directory and then runs from that, keeping a project nicely sandboxed.  The OS X Python application builder <a href="http://undefined.org/python/py2app.html">py2app</a>, works similarly, but after the fact as a final build step so you can deliver a complete application without worrying what version of Python and libraries are installed on a user&#8217;s computer.  Ian Bicking also has package installer you can use with (or without) VirtualEnv, called <a href="http://blog.ianbicking.org/2008/10/28/pyinstall-is-dead-long-live-pip/">Pip</a>, and if you check his two links here you may notice a pattern forming for his blog titles.</p>
<p>From there we wandered around, topic-wise, discussing XML/HTML parsing libraries such as <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> and <a href="http://codespeak.net/lxml/">lxml</a>, from there to screen scrapers like <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a>, to web spiders like <a href="http://scrapy.org/">scrapy</a>.</p>
<p>Conversation drifted into 3D for a bit, touching on VRML/X3D and the open-source <a href="http://freewrl.sourceforge.net/">FreeWRL</a> viewer (built by the Canadian Government, yay!).  While it isn&#8217;t really a Python project, there is a Python library to generate VRML as part of the <a href="http://dirac.cnrs-orleans.fr/ScientificPython/ScientificPythonManual/">Scientific</a> library (not to be confused with <a href="http://www.scipy.org/">SciPy</a>.  And if you don&#8217;t want to go the XML route, you can stay in Python because Scientific can also generate <a href="http://vpython.org/">VPython</a> code (although VPython does not yet support things like transparency or texture mapping).</p>
<p>We kept coming back to web frameworks, discussing the tradeoffs between <a href="http://www.djangoproject.com/">Django</a> and <a href="http://www.zope.org/">Zope</a>/<a href="http://plone.org/">Plone</a> and the impact of &#8220;cloud computing&#8221; platforms such as <a href="http://aws.amazon.com/">Amazon Web Services</a> (AWS) and <a href="http://code.google.com/appengine/">Google App Engine</a>.  While the AWS services give a lot more flexibility, they require a substantial amount of planning and configuration.  App Engine has the easy deployment of a PHP app, but with the convenience of Python and the power of Big Table, but the rather substantial disadvantage of still being a beta environment that you can&#8217;t actually buy services on yet (no scaling up).</p>
<p>There are some workarounds for these and other problems (the App Engine 10 app limit, for instance).  <a href="http://hadoop.apache.org/core/">Hadoop</a> was mentioned as an open-source alternative to App Engine.  <a href="http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=101">Amazon Machine Images</a> can give you a head start at deploying on AWS, although you will still need to make arrangements for data persistence. <a href="http://www.10gen.com/">10gen</a> appears to be building using the App Engine model (more or less), but as a smaller player, they may be more responsive to user feedback.  <a href="http://www.lowendbox.com/">LowEndBox</a> is not a provider, but a blog tracking ultra-cheap hosting with root access, so you could conceivably build your own AWS on a shoestring.  </p>
<p>Since I spent part of the holidays building Lego Mindstorms models with my kids (a <a href="http://www.nxtprograms.com/machine_gun/index.html">machine gun</a> and a <a href="http://www.nxtprograms.com/puppy/index.html">puppy</a>), I kept trying to steer the conversation towards robotics. Unfortunately, the <a href="http://pyrorobotics.org/">Python Robotics</a> project does not support Mindstorms yet, but they do support Roombas, so I may still be in luck.  I haven&#8217;t found a Python project for programming Mindstorms yet, but you could probably wrap <a href="http://bricxcc.sourceforge.net/nbc/">Not Exactly C</a> with Python fairly easily, and after the meeting I found this script to <a href="http://code.activestate.com/recipes/498085/">use Bluetooth to control Mindstorms from Python</a>.</p>
<p>After that we continued the discussion at the pub and I don&#8217;t have any browser history to help me remember that part of the discussion.  I do remember that before the meeting started, I did plug <a href="http://scratch.mit.edu/">Scratch</a> again as the best way to introduce 6-12 year olds to programming. </p>
<p>Finally, I want to thank everyone on the <a href="http://lists.livingcode.org/listinfo.cgi/vanpyz-livingcode.org/">VanPyZ mailing list</a> for helping to organize and to re-establish the group&#8217;s web site after recent hack attacks and crashing, especially<a href="http://henry.precheur.org/"> Henry Prêcheur</a> for restoring the content and moving it to the official Python wiki for the <a href="http://wiki.python.org/moin/VanPyZ">new VanPyZ page</a>.</p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/drawing-with-opacity</id>
    <title type="html"><![CDATA[Drawing with opacity]]></title>
    <updated>2009-01-03T19:58:55Z</updated>
    <published>2008-12-14T18:46:20Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/12/14/drawing-with-opacity/feed" thr:count="4"  />
    <link rel="alternate" href="http://livingcode.org/2008/12/14/drawing-with-opacity" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Tutorial" />
    <summary type="html"><![CDATA[This is something of a followup to earlier posts Drawing Hexmaps and Saving PNG from PyGame.  A recent comment from Roger Aisling on the second of those posts asked about drawing with opacity in the Python Image Library (PIL).  A check of the PIL API didn&#8217;t turn up anything, but there is an [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/12/14/drawing-with-opacity"><![CDATA[<p>This is something of a followup to earlier posts <a href="http://livingcode.org/2008/drawing-hexmaps">Drawing Hexmaps</a> and <a href="http://livingcode.org/2008/saving-png-from-pygame">Saving PNG from PyGame</a>.  A recent comment from <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/">Roger Aisling</a> on the second of those posts asked about drawing with opacity in the <a href="http://www.pythonware.com/library/pil/handbook/index.htm">Python Image Library</a> (PIL).  A check of the PIL API didn&#8217;t turn up anything, but there is an optional add-on to the PIL called <a href="http://effbot.org/zone/pythondoc-aggdraw.htm">aggdraw</a>, which is based on <a href="http://www.antigrain.com/">Anti-Grain Geometry</a> (AGG), a graphics library that seems to cover similar ground to <a href="http://www.cairographics.org/">Cairo</a>.  I&#8217;ve been meaning to play with both of these, but don&#8217;t know enough about either project to know what is better about one vs. the other.  I know Cairo is used by Mozilla, GTX+, Mono, Inkscape, and WebKit (under GTX+).  I wasn&#8217;t able to find much about where AGG is used.</p>
<p>Anyway, here are some examples showing how to draw polygons with variable opacity (or alpha).  I&#8217;ve got examples for <a href="http://nodebox.net/code/index.php/Home">NodeBox</a>, aggdraw, and pycairo.  I was going to do some for the browser canvas, <a href="http://processing.org/">Processing</a>, PyObjC, and SVG, but a) I wanted to get this post out, and b) PyCairo can already output to SVG and Cocoa (and Processing will be very similar to NodeBox).  So if there is any interest in those examples, or others I may have forgotten, let me know in the comments.</p>
<p>While the images below look identical (at least they do to me), each was drawn with its respective library.</p>
<p>For each library I will present the drawing function and the main function that sets things up and drives it.  At the end I will present the utility functions used which were the same for all libraries.  No optimizations here, just the simplest thing I could do that worked.</p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/nodebox_example.png' alt='NodeBox Example Image'  title="NodeBox Example"/></p>
<p><strong>NodeBox</strong></p>
<p>I began with NodeBox, because it is so easy work with.  In Processing they call programs &#8220;sketches&#8221; and in NodeBox that is very much what it feels like.  The first thing I worked up was a way to draw &#8220;random&#8221; polygons in the same way for each libary. I could seed the random with a set value, but decided to use random to generate starting values, then just re-use those initial values.  To get 50 different polygons, I used a list of primes, chose from the list at random, then used those selected values to increment each polygon vertex and color value (red, green, blue, and alpha).  All of which was probably more work than was strictly necessary, but should be stable across different versions of Python and different operating systems.</p>
<p>The drawing routines all have the same signature.  They take a tuple of point tuples (x,y) and a tuple of colors (r,g,b,a) as ints between 0 and 255.</p>
<p><code>
<pre>
def nodebox_poly(pts, clr):
    fill(*ints2floats(clr)) # convert ints in range 0-255 into floats between 0.0 and 1.0
    beginpath()             # every time we want to change colours or linewidth we need to start a new path
    moveto(*pts[-1])     # start and end at the last point in the list
    for pt in pts:
        lineto(*pt)
    endpath()

def nodebox_main():
    size(WIDTH, HEIGHT) # nodebox wants to know how big a canvas you are working with
    draw_all(nodebox_poly) # No additional setup needed
</pre>
<p></code></p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/cairo_example.png' alt='Cairo Example Image' title="Cairo Example" /></p>
<p><b>PyCairo</b></p>
<p>The lines in cairo_main where we create the surface and where we save it are all we would have to change if we wanted to generate a Cocoa view, an SVG document, a PDF document, etc.  Two of the main differences between this and the NodeBox example are that there is a bit more setup (Cairo doesn&#8217;t default to a white background) and we need to have a reference to the context for drawing, where NodeBox has an implicit drawing context.</p>
<p><code>
<pre>
def cairo_poly(pts, clr):
    ctx.set_source_rgba(*ints2floats(clr))
    ctx.move_to(*pts[-1])
    for pt in pts:
        ctx.line_to(*pt)
    ctx.close_path()
    ctx.fill()

def cairo_main():
    # Setup Cairo
    import cairo
    global ctx
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    ctx = cairo.Context(surface)
    # fill background white
    cairo_poly(((0,0),(WIDTH,0),(WIDTH,HEIGHT),(0,HEIGHT)),(255,255,255,255))
    draw_all(cairo_poly)
    surface.write_to_png('cairo_example.png')
</pre>
<p></code></p>
<p><img src='http://livingcode.org/wp-content/uploads/2008/12/aggdraw_example.png' alt='Aggdraw Example Image'  title="Aggdraw Example" /></p>
<p><b>aggdraw</b></p>
<p>The aggdraw example is very similar to Cairo.  In fact, if I&#8217;d done either of these first, I would have passed the context object around and simply ignored it in NodeBox to eliminate a global variable.  Aggdraw can draw in memory without using PIL, but doesn&#8217;t appear to have a way to write to a PNG image that way, so we draw to a PIL image (which requires us to flush all drawing operations before writing the file).</p>
<p><code>
<pre>
def aggdraw_poly(pts, clr):
    import aggdraw
    global ctx
    b = aggdraw.Brush(clr, clr[-1])
    pts2 = []
    for p in pts:
        pts2.extend(p)
    ctx.polygon(pts2, b)

def aggdraw_main():
    import aggdraw, Image
    global ctx
    img = Image.new('RGBA', (WIDTH, HEIGHT), "white")
    ctx = aggdraw.Draw(img)
    draw_all(aggdraw_poly)
    ctx.flush()
    img.save('aggdraw_example.png')
</pre>
<p></code></p>
<p><b>Utilites</b></p>
<p>These were the same for all of the examples.  If you put it all in one file (or use mine, linked below) you can choose what library to use by switching which main function is called.</p>
<p><code>
<pre>
MIN_ALPHA = 50
MAX_ALPHA = 100

WIDTH = 500
HEIGHT = 250

#
#   Utilities
#
def hex2tuple(hex_color):
    return tuple([int(hex_color[i:i+2], 16) for i in range(1,9,2)])

def tuple2hex(tuple_color):
    return "#%0.2X%0.2X%0.2X%0.2X" % tuple_color

def ints2floats(tuple_color):
    return tuple([c / 255.0 for c in tuple_color])

def inc_point(p, dp):
    return (p[0] + dp[0]) % WIDTH, (p[1] + dp[1]) % HEIGHT

def inc_triangle(t, dt):
    return tuple([inc_point(t[i], dt[i]) for i in range(3)])

def inc_color(c, dc):
    new_c = [(c[i] + dc[i]) % 256 for i in range(3)]
    new_a = (c[3] + dc[3]) % MAX_ALPHA
    if new_a < MIN_ALPHA: new_a += MIN_ALPHA
    new_c.append(new_a)
    return tuple(new_c)

def draw_all(draw_fn):
    triangle = start_t
    color = start_c
    for i in range(50):
        triangle = inc_triangle(triangle, dt)
        color = inc_color(color, dc)
        draw_fn(triangle, color)

#
#   Starting and incrementing values
#
start_c = hex2tuple('#0xE6A20644')
start_t = (127, 132), (341, 171), (434, 125)
dt = (107, 23), (47, 73), (13, 97)
dc = 61, 113, 109, 41
</pre>
<p></code></p>
<p>As you can see, these libraries are all quite capable of producing nice vector-based, anti-aliased polygons with alpha blending. I have heard anecdotal evidence that AGG is faster than Cairo, but Cairo appears to be more widely used.  Aside from that I don't know why one would be preferred over the other (unless you want to get into language wars: AGG is written in C++, Cairo is written in C).  Both have bindings in a number of languages besides Python, if that's your thing.  NodeBox is still my favourite tool for noodling around in with graphics programming.  All of these are great fun, easy to use, and handy to have in your bag of tricks.</p>
<p>I tested this under OS X (required for NodeBox), using pycairo installed via fink (using fink's Python 2.5) and aggdraw installed via easy_install (using the builtin in Python 2.5).</p>
<p>Here is my test file containing all of the code above: <a href='http://livingcode.org/wp-content/uploads/2009/01/alpha_polygonspy.zip' title='Alpha polygons example code'>Alpha polygons example code</a></p>
]]></content>
        </entry>
    <entry>
    <id>http://livingcode.org/2008/in-earth-dreams</id>
    <title type="html"><![CDATA[in earth dreams]]></title>
    <updated>2008-11-14T05:43:00Z</updated>
    <published>2008-11-14T05:43:00Z</published>
    <author>
      <name>Dethe</name>
      <email>delza@livingcode.org</email>
<uri>http://livingcode.org/</uri>    </author>
    <link rel="replies" type="application/atom+xml" href="http://livingcode.org/2008/11/13/in-earth-dreams/feed" thr:count="1"  />
    <link rel="alternate" href="http://livingcode.org/2008/11/13/in-earth-dreams" />
    <category scheme="http://livingcode.org" term="Mac" />
    <category scheme="http://livingcode.org" term="Presentations" />
    <category scheme="http://livingcode.org" term="Python" />
    <category scheme="http://livingcode.org" term="Web" />
    <summary type="html"><![CDATA[
This is a collaboration that Daniela and I did together.  Her words and voice, my scripting and adding some titles.  The words to the poem can be found on her site here (or actually, on any page of her site since it is currently in her sidebar). The animation itself was done in [...]]]></summary>
      <content type="html" xml:base="http://livingcode.org/2008/11/13/in-earth-dreams"><![CDATA[<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/gybpgqwRHso&#038;color1=0xb1b1b1&#038;color2=0xcfcfcf&#038;hl=en&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/gybpgqwRHso&#038;color1=0xb1b1b1&#038;color2=0xcfcfcf&#038;hl=en&#038;fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p>This is a collaboration that <a href="http://strangeplaces.livingcode.org/">Daniela</a> and I did together.  Her words and voice, my scripting and adding some titles.  The words to the poem can be found on her site <a href="http://strangeplaces.livingcode.org/archives/6/in-earth-dreams">here</a> (or actually, on any page of her site since it is currently in her sidebar). The animation itself was done in <a href="http://nodebox.net/">NodeBox</a> (so this example is Mac-only, but it could probably be adapted easily to Processing.</p>
<p><code>
<pre>
from math import radians, sin, cos
from random import seed

POEM = '''
in earth dreams
her limbs 		are all sky
her body		inhabited
by wild birds		and busy
mammals
an endangered 		species
she lost		 her head
where reason 		gives
the impression 		everything is
clear
she motions 	to dance
a rhythm			spins
and turns		attracted
to light
if she had eyes 		I would see
the stars		she holds
dear
then 		there are 		all
the words		she escapes
slips past 		their curved
seashell ears	as they listen
to capture 		her
on the page		 my words
are already	changing her
while she weaves 	gossamer
and soft moss		to hang
in autumn 	woods
'''.split()

size(320,240)
speed(30)

class Vector(object):

    def __init__(self, idx):
        self._starting_angle = self.angle = radians(random(360))
        self.rate = random(0.5,2.5)
        self.distance = sin(radians(idx * 2) + 180) * 100
        self.x = 0
        self.y = 0

    def step(self):
       self.angle = self._starting_angle + FRAME * radians(self.rate)
       self.x = cos(self.angle) * self.distance
       self.y = sin(self.angle) * self.distance
       return self.rate, self.x, self.y

class Word(object):

    index = []

    def __init__(self, idx, word):
		self.red = random()
		self.green  = random(0.4, 0.75)
		self.blue = 0.4
		self.vector = Vector(idx)
		self.word = word
		self.size = 10 + 2 * len(word)
		self.duration = 3 * (len(word) + 2)
		Word.index += [idx] * self.duration

    def step(self, alpha=1.0):
		fill(self.red, self.green, self.blue, alpha)
		rate, x, y = self.vector.step()
		push()
		rotate(rate * FRAME)
		font('Georgia', self.size)
		text(self.word, x, y)
		pop()

def setup():
    global words
    seed(0)
    words = [Word(idx, word) for idx,word in enumerate(POEM)]

def draw():
    translate(WIDTH/2 -50,HEIGHT/2)
    background(1.0, 0.97, 0.86)
    # Add one word at a time, then show all words for 100 frames more
    if FRAME < len(Word.index):
        last = Word.index[FRAME]
        for word in words[:last]:
            word.step()
    # Now fade out and have blank screen for titles
    elif FRAME < len(Word.index) + 100:
        alpha = 1.0 - 0.01 * (FRAME - len(Word.index))
        for word in words:
            word.step(alpha)
</pre>
<p></code></p>
<p>I used iMovie '08 to mix the voice and animation and to add the titles.  I wasn't very happy with the changes to iMovie, I found the earlier versions were much more flexible and easy to use.  On the other hand, I tried Norrkross Movie, that I actually had to buy, and was unable to do it at all.  Next time I will just add the titles in NodeBox and only use iMovie to add the soundtrack.</p>
<p>My Python script could probably be cleaned up too.  This was what I had after many iterations and experiments to get the timing, color, and rotation where we were both happy with it.</p>
<p>This was my first time uploading to YouTube and the resulting movie is very jumpy, in the original movie I uploaded was not.  If anyone has suggestions how to avoid that (whether pre-processing or a better movie hosting service), please let me know in the comments.  Overall I was happy with how it turned out and I'm looking forward to our next collaboration.</p>
]]></content>
        </entry>
  </feed>
