<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>Lucumr Articles</title>
    <link>http://lucumr.pocoo.org/articles/</link>
    <description>Recently written articles on lucumr.pocoo.org</description>
    <language>en-us</language>
    <pubDate>Sun, 10 Jun 2007 08:22:00 GMT</pubDate>
    <lastBuildDate>Sun, 10 Jun 2007 08:22:00 GMT</lastBuildDate>
    <generator>awesome python generation script, fuck you PHP/Rails/Django.</generator>
    <item>
      <title>Internationalized PyGTK Applications</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  Python is an awesome programming language, GTK is an incredible GUI toolkit.
  Python ships gettext, GTK supports gettext in the glade interface builder.
  So the logical conclusion is using gettext in your PyGTK application. This
  article will show you how to create and translate your PyGTK application in
  no time.
</p>
  
  <h3>Prerequisites</h3>
  <p>
    Things you have to have installed on your computer in order to make the
    following examples work correctly:
  </p>
  <ul>
    <li><a href="http://pygtk.org/">PyGTK</a> &mdash; in a quite new version.
        Don't ask me which version we need here but I doubt that older versions
        will work.</li>
    <li><a href="http://glade.gnome.org/">Glade</a> &mdash; for designing the
        user interface. Doing that in the sourcecode is just dumb.</li>
    <li><a href="http://www.python.org/">Python</a> &mdash; and in version 2.4
        or higher.</li>
  </ul>
  <h3>Motivation</h3>
  <p>
    Although I have <tt>en_GB.UTF-8</tt> as my locale and publish articles on
    this webpage in English my mother-tongue is German. As a result of that I
    love applications that are available in more than one language. And the
    OpenSource community has plenty of applications, libraries and online
    platforms for creating multilanguage GUI and web applications. When I tried
    to translate one of my applications some days ago I was surprised that
    there were no tutorials (or maybe I'm too stupid for googleing) that
    explained the issue. I then checked other projects and read some man
    pages.
  </p>
  <p>
    So I hope that this article will make life easier for you.
  </p>
  <h3>Organizing the Application</h3>
  <p>
    The first (and hardest) part of any application is the organization. It's
    that hard because the organization should support development and
    production mode. Having to symlink or copy files into global folders
    makes things a lot harder and is usually a stupid idea. For my application
    I decided to not put the translation files into the locale folder but the
    application shared data directory.
  </p>
  <p>
    My idea (or better, the idea of <a href="http://www.leonard-ritter.com/">
    Leonard Ritter</a>, who did a similar thing for his aldrin project) was
    that you have the whole folder structure in your development folder and
    just copy the files to <tt>prefix</tt> (usually <tt>/usr</tt>) when
    installing the application.
  </p>
  <p>
    So basically the folder structure looks like this:
  </p>
  <pre>
bin/
  APPLICATION             the executable that starts the application
share/
  APPLICATION/
    glade/                the folder that contains all the glade files
    lib/
      APPLICATION/        the python package with the application data
        __init__.py       make it a package and add bootstrapping code.
        application.py    the actual application code.
        ...               other files.
      ...                 dependencies you maybe want to bundle
    i18n/                 contains all the compiled translations
    res/                  other resources (images etc)
</pre>
  <p>
    The executable (<tt>bin/APPLICATION</tt>) now looks at it's own filename,
    and looks up the parent folder of the folder the executable is located in.
    So for the development mode this will be <tt>.</tt>, for production mode
    it will probably be something like <tt>/usr</tt>, <tt>/usr/local</tt> etc.
  </p>
  <p>
    Then it calculates the absolute path to the lib folder and adds it to the
    pythonpath to import the main function from the package and call it:
  </p>
<div class="highlight"><pre><span class="c">#!/usr/bin/env python</span>
<span class="k">import</span> <span class="nn">sys</span>
<span class="k">from</span> <span class="nn">os.path</span> <span class="k">import</span> <span class="n">dirname</span><span class="p">,</span> <span class="n">join</span><span class="p">,</span> <span class="n">pardir</span>
<span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mf">0</span><span class="p">,</span> <span class="n">join</span><span class="p">(</span><span class="n">dirname</span><span class="p">(</span><span class="n">__file__</span><span class="p">),</span> <span class="n">pardir</span><span class="p">,</span> <span class="s">&#39;share&#39;</span><span class="p">,</span>
                        <span class="s">&#39;APPLICATION&#39;</span><span class="p">,</span> <span class="s">&#39;lib&#39;</span><span class="p">))</span>
<span class="k">from</span> <span class="nn">APPLICATION</span> <span class="k">import</span> <span class="n">main</span>
<span class="n">main</span><span class="p">()</span>
</pre></div>

  <p>
    The <tt>main()</tt> function comes directly from the <tt>__init__.py</tt>
    file of the <tt>APPLICATION</tt> package located in the lib folder.
  </p>
  <h3>Bootstrapping</h3>
  <p>
    Now it comes to the second hard part. Before we can use all the libraries
    we have to do some bootstrapping to get the gettext system working in the
    python interpreter and the GTK system. This happens in the <tt>__init__.py</tt>
    file of the package. There we set up gettext for the whole python interpreter,
    get the path to the shared files and import the main function from the
    <tt>application</tt> submodule:
  </p>
<div class="highlight"><pre><span class="k">from</span> <span class="nn">os.path</span> <span class="k">import</span> <span class="n">abspath</span><span class="p">,</span> <span class="n">dirname</span><span class="p">,</span> <span class="n">join</span><span class="p">,</span> <span class="n">pardir</span>

<span class="c"># here we define the path constants so that other modules can use it.</span>
<span class="c"># this allows us to get access to the shared files without having to</span>
<span class="c"># know the actual location, we just use the location of the current</span>
<span class="c"># file and use paths relative to that.</span>
<span class="n">SHARED_FILES</span> <span class="o">=</span> <span class="n">abspath</span><span class="p">(</span><span class="n">join</span><span class="p">(</span><span class="n">dirname</span><span class="p">(</span><span class="n">__file__</span><span class="p">),</span> <span class="n">pardir</span><span class="p">,</span> <span class="n">pardir</span><span class="p">))</span>
<span class="n">LOCALE_PATH</span> <span class="o">=</span> <span class="n">join</span><span class="p">(</span><span class="n">SHARED_FILES</span><span class="p">,</span> <span class="s">&#39;i18n&#39;</span><span class="p">)</span>
<span class="n">RESOURCE_PATH</span> <span class="o">=</span> <span class="n">join</span><span class="p">(</span><span class="n">SHARED_FILES</span><span class="p">,</span> <span class="s">&#39;res&#39;</span><span class="p">)</span>

<span class="c"># the name of the gettext domain. because we have our translation files</span>
<span class="c"># not in a global folder this doesn&#39;t really matter, setting it to the</span>
<span class="c"># application name is a good idea tough.</span>
<span class="n">GETTEXT_DOMAIN</span> <span class="o">=</span> <span class="s">&#39;APPLICATION&#39;</span>

<span class="c"># setup PyGTK by requiring GTK2</span>
<span class="k">import</span> <span class="nn">pygtk</span>
<span class="n">pygtk</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="s">&#39;2.0&#39;</span><span class="p">)</span>

<span class="c"># set up the gettext system and locales</span>
<span class="k">from</span> <span class="nn">gtk</span> <span class="k">import</span> <span class="n">glade</span>
<span class="k">import</span> <span class="nn">gettext</span>
<span class="k">import</span> <span class="nn">locale</span>

<span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">module</span> <span class="ow">in</span> <span class="n">glade</span><span class="p">,</span> <span class="n">gettext</span><span class="p">:</span>
    <span class="n">module</span><span class="o">.</span><span class="n">bindtextdomain</span><span class="p">(</span><span class="n">GETTEXT_DOMAIN</span><span class="p">,</span> <span class="n">LOCALE_PATH</span><span class="p">)</span>
    <span class="n">module</span><span class="o">.</span><span class="n">textdomain</span><span class="p">(</span><span class="n">GETTEXT_DOMAIN</span><span class="p">)</span>

<span class="c"># register the gettext function for the whole interpreter as &quot;_&quot;</span>
<span class="k">import</span> <span class="nn">__builtin__</span>
<span class="n">__builtin__</span><span class="o">.</span><span class="n">_</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">gettext</span>

<span class="c"># import the main function</span>
<span class="k">from</span> <span class="nn">APPLICATION.application</span> <span class="k">import</span> <span class="n">main</span>
</pre></div>

  <p>
    Alright. The code above should be straightforward, what you probably not
    know is the <tt>__builtin__</tt> module. Basically if python cannot find
    a name in the locale or global namespace (and also not in a closure) it
    will look for it in the <tt>__builtin__</tt> module before giving up. This
    is the module where the stuff like <tt>float</tt>/<tt>dir</tt> etc. comes
    from.
  </p>
  <p>By binding the gettext function to <tt>__builtin__._</tt> we can
    use <tt>_('Hello World')</tt> to mark as translatable and translatate a
    string from every module in the python interpreter without having to
    import the function first.
  </p>
  <h3>Writing Internationalizable Code</h3>
  <p>
    i18n of Linux works pretty well because it's something gettext solves in a
    very good way. The only problem you have is that there are usually
    situations where something looks like it would work for your language but
    certainly not in another language. This usually affects pluralization. The
    rule "n != 1" for plural forms is something you have in English and German
    and some other languages but not in Slavic and also not in Asian languages.
  </p>
  <p>
    Also it's possible that you have two strings that look exactly the same but
    mean different things in the source language. In that case you <em>have</em>
    to "annotate" them by adding additional information to it to have two
    differnent strings. In that case you will have to introduce an translation
    file for your source language too and cut of the annotated stuff. An example
    for that is "May" and "May" in Calendars. One of them is the three letter
    version, the other is the full version. Unfortunately both look the same
    in English because too short. Solution:
  </p>
  <p>
    <tt>_('May::abbreviated')</tt> and <tt>_('May::full')</tt>
  </p>
  <p>
    I won't cover plural forms here because that would make this article too
    long but if you have the situation that you must distinquish between singular
    and plural have a look at the ngettext function provided.
  </p>
  <p>
    So what you have to do now is wrapping all translatable stuff in
    <tt>_()</tt> as explained here:
  </p>
<div class="highlight"><pre><span class="c"># this:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;Hello World!&#39;</span>
<span class="c"># becomes:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Hello World!&#39;</span><span class="p">)</span>

<span class="c"># and this:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;Hello </span><span class="si">%s</span><span class="s">!&#39;</span> <span class="o">%</span> <span class="n">bar</span>
<span class="c"># becomes:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Hello </span><span class="si">%s</span><span class="s">!&#39;</span><span class="p">)</span> <span class="o">%</span> <span class="n">bar</span>

<span class="c"># because placeholders could move in other languages, this:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="s">&#39;Expected </span><span class="si">%d</span><span class="s"> items, got </span><span class="si">%d</span><span class="s">.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">expected</span><span class="p">,</span> <span class="n">found</span><span class="p">)</span>
<span class="c"># becomes:</span>
<span class="n">foo</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Expected </span><span class="si">%(expected)d</span><span class="s"> items, got </span><span class="si">%(found)s</span><span class="s">.&#39;</span><span class="p">)</span> <span class="o">%</span> <span class="p">{</span>
    <span class="s">&#39;expected&#39;</span><span class="p">:</span>   <span class="n">expected</span><span class="p">,</span>
    <span class="s">&#39;found&#39;</span><span class="p">:</span>      <span class="n">found</span>
<span class="p">}</span>
</pre></div>

  <h3>Creating Internationalizable GTK GUIs using Glade</h3>
  <p>
    Alright. That's easy. It happens out of the box. What you can do
    additionally is leaving comments for translators or marking strings as
    untranslatable in the property editor but otherwise all labels etc are
    marked as translatable automatically.
  </p>
  <h3>Collecting Strings</h3>
  <p>
    Once the application is created we have to collect all the translatable
    strings and create so-called "pot" files (po templates). A translator can
    then use that pot file to translate the application and send it back with
    the translated strings in. A pot file with translations is called a "po"
    file.
  </p>
  <p>
    For python there is a cool called pygettext in the distribution that helps
    collecting translatable strings and creating a pot file. For glade there
    should be a configuration to generate pot files too but I was unable to find
    that in my Glade version (3.0.2). But even if there was such a setting or
    button it would still generate two pot files which are more complex to
    merge (requires some POTFILES.in foobar and tools with manpages longer than
    I want to read) I wrote a small tool myself especially for PyGTK which
    scans all python and glade files for translatable strings.
  </p>
  <p>
    You can find this tool here: <a
    href="http://pocoo.org/~mitsuhiko/generate_pot.py">generate_pot.py</a>.
    Usage is quite simple:
  </p>
  <pre>$ python generate_pot.py share/APPLICATION APPLICATION VERSION &gt; APPLICATION.pot</pre>
  <p>
    Replace APPLICATION and VERSION with your application name of course.
  </p>
  <h3>Translating</h3>
  <p>
    So the process of translating an pot file is straigtforward. If it's a new
    translation (so there is now <tt>it.po</tt> or <tt>de.po</tt>) by now you
    can simply copy the pot file to it's target name and open it with your
    favorite translator application or text editor. The format is
    straightfoward, it's easily possible to translate it with vim or whatever
    editor you use. the <tt>msgid</tt> part is the source string, the
    <tt>msgstr</tt> part is the translated string.
  </p>
  <p>
    If you already have an translated po file and you added or modified
    translatable strings in the application (and an updated pot file generated
    by <tt>generate_pot.py</tt>) you can use the <tt>msgmerge</tt> utility
    that comes with the gettext system:
  </p>
  <pre>$ msgmerge -U de.po APPLICATION.pot</pre>
  <p>
    If you changed the casing of an source string or did another minor
    modification msgmerge resolves that and marks the string as fuzzy. Just
    have a look at the comment above the string.
  </p>
  <h3>Compiling Translations</h3>
  <p>
    Now you have to compile a mo file gettext can use. It's basically a binary
    version of the po file with the translated strings in. For that you can use
    the <tt>msgfmt</tt> application:
  </p>
  <pre>$ msgfmt do.po -o share/APPLICATION/i18n/de/LC_MESSAGES/GETTEXT_DOMAIN.mo</pre>
  <p>
    As you can see you need a quite complicated folder structure for gettext so
    make sure that de/LC_MESSAGES exists in the i18n folder. and replace
    GETTEXT_DOMAIN with the domain you defined in the package's <tt>__init__.py</tt>.
  </p>
  <h3>Testing Translations</h3>
  <p>
    If you have a system with a different default locale and you don't want to
    logout and login with another locale just use the <tt>LANG</tt> variable to
    tell gettext to use another language:
  </p>
  <pre>$ LANG=de_DE.UTF-8 ./bin/APPLICATION</pre>
  <p>
    Note that this requires that you have the German locales installed on your
    system because otherwise the setlocale call will raise an error.
  </p>
  <h3>Deployment</h3>
  <p>
    So now where the application is ready to distribute all you have to do is
    to create a Makefile (or what ever you want to use) and copy <tt>bin</tt>
    and <tt>share</tt> to the specified prefix.
  </p>
  <h3>Get the Code, Don't get Lost</h3>
  <p>
    I uploaded a small example application that uses the foundation explained
    above. You can download it here: <a href="http://pocoo.org/~mitsuhiko/pygtki18nexample.tar.gz">pygtki18nexample.tar.gz</a>
  </p>
  <p>
    It contains a small application that just displays a window and connects
    some basic signals.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/internationalized-pygtk-applications</link>
      <guid>http://lucumr.pocoo.org/articles/internationalized-pygtk-applications</guid>
      <author>Armin Ronacher</author>
      <pubDate>Sun, 10 Jun 2007 08:22:00 GMT</pubDate>
    </item>
    <item>
      <title>Getting Started with WSGI</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  I finally finished the written matura and have some more time to work on
  projects and write articles. One of the things I wanted to write for a long
  time is a WSGI tutorial that does not require a specific framework or
  implementation. So here we go.
</p>
  
  <img src="/static/wsgi-snake.png" alt="Getting Stated with WSGI">
  <h3>What's WSGI?</h3>
  <p>
    Basically WSGI is lower level than CGI which you probably know. But in
    difference to CGI, WSGI does scale and can work in both multithreaded and
    multi process environments because it's a specification that doesn't
    mind how it's implemented. In fact WSGI is not CGI because it's between your
    web application and the webserver layer which can be CGI, mod_python, FastCGI
    or a webserver that implements WSGI in the core like the python stdlib
    standalone WSGI server called wsgiref.
  </p>
  <p>
    WSGI is specified in the <a href="http://www.python.org/dev/peps/pep-0333/">PEP
    333</a> and adapted by various frameworks including the well known frameworks
    django and pylons.
  </p>
  <p>
    If you are too lazy to read the pep 333 here's a short summary:
  </p>
  <ul>
    <li>WSGI application are callable python objects (functions or classes with a
        <tt>__call__</tt> method that are passed two arguments: a WSGI environment
        as first argument and a function that starts the response.</li>
    <li>the application has to start a response using the function provided and
        return an iterable where each yielded item means writing and flushing.</li>
    <li>The WSGI environment is like a CGI environment just with some additional
        keys that are either provided by the server or a middleware.</li>
    <li>you can add middlewares to your application by wrapping it.</li>
  </ul>
  <p>
    Because that's a lot of information let's ignore it for now and have a look
    at a basic WSGI application:
  </p>
  <h3>Extended Hello World</h3>
  <p>
    Here a simple, but not too simple example of a WSGI application that says
    <tt>Hello World!</tt> where World can be specified via url parameter.
  </p>
<div class="highlight"><pre><span class="k">from</span> <span class="nn">cgi</span> <span class="k">import</span> <span class="n">parse_qs</span><span class="p">,</span> <span class="n">escape</span>

<span class="k">def</span> <span class="nf">hello_world</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">parameters</span> <span class="o">=</span> <span class="n">parse_qs</span><span class="p">(</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;QUERY_STRING&#39;</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">))</span>
    <span class="k">if</span> <span class="s">&#39;subject&#39;</span> <span class="ow">in</span> <span class="n">parameters</span><span class="p">:</span>
        <span class="n">subject</span> <span class="o">=</span> <span class="n">escape</span><span class="p">(</span><span class="n">parameters</span><span class="p">[</span><span class="s">&#39;subject&#39;</span><span class="p">][</span><span class="mf">0</span><span class="p">])</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">subject</span> <span class="o">=</span> <span class="s">&#39;World&#39;</span>
    <span class="n">start_response</span><span class="p">(</span><span class="s">&#39;200 OK&#39;</span><span class="p">,</span> <span class="p">[(</span><span class="s">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s">&#39;text/html&#39;</span><span class="p">)])</span>
    <span class="k">return</span> <span class="p">[</span><span class="s">&#39;&#39;&#39;&lt;title&gt;Hello </span><span class="si">%(subject)s</span><span class="s">&lt;/title&gt;</span>
<span class="s">    &lt;p&gt;Hello </span><span class="si">%(subject)s</span><span class="s">!&lt;/p&gt;&#39;&#39;&#39;</span> <span class="o">%</span> <span class="p">{</span><span class="s">&#39;subject&#39;</span><span class="p">:</span> <span class="n">subject</span><span class="p">}]</span>
</pre></div>

  <p>
    As you can see the <tt>start_response</tt> function takes two arguments.
    A status string and a list of tuples that represent the response headers.
    What you cannot see because it's not used here and nowhere else is that
    the <tt>start_response</tt> function returns something. It returns a
    <tt>write</tt> function that directly writes to the webserver output
    stream. Because it bypasses middlewares (we'll cover that later) it's
    a terrible bad idea to use that function. For debugging purposes however
    it can be useful.
  </p>
  <p>
    But how to start that application now? A webserver doesn't know how to
    handle that and neither does python because nothing calls that function.
    Because we're lazy we don't setup a server with WSGI support now but use
    the <tt>wsgiref</tt> WSGI standalone server bundled with python2.5 and
    higher. (You can also download it for python2.3 or 2.4)
  </p>
  <p>
    Just add this to your file:
  </p>
<div class="highlight"><pre><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="k">from</span> <span class="nn">wsgiref.simple_server</span> <span class="k">import</span> <span class="n">make_server</span>
    <span class="n">srv</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="mf">8080</span><span class="p">,</span> <span class="n">hello_world</span><span class="p">)</span>
    <span class="n">srv</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>

  <p>
    When you now start the file you should be able to get a <tt>Hello John!</tt>
    on <tt>http://localhost:8080/?subject=John</tt>.
  </p>
  <h3>Path Dispatching</h3>
  <p>
    You probably worked with CGI or PHP before. If you did so you know that
    you most of the time have multiple public files (<tt>.pl</tt> /
    <tt>.php</tt>) a user can access and that do something. Not so in WSGI.
    There you only have one file which consumes all paths. Thus if you have
    your server from the previous example still running you should get the
    same content on <tt>http://localhost:8080/foo?subject=John</tt>.
  </p>
  <p>
    The accessed path is saved in the <tt>PATH_INFO</tt> variable in the
    WSGI environment, the real path to the application in <tt>SCRIPT_NAME</tt>.
    In case of the development server <tt>SCRIPT_NAME</tt> will be empty,
    but if you have a wiki that is mounted on <tt>http://example.com/wiki</tt>
    the <tt>SCRIPT_NAME</tt> variable would be <tt>/wiki</tt>. This information
    can now be used to serve multiple indepentent pages with nice URLs.
  </p>
  <p>
    In this example we have a bunch of regular expressions and match the
    current request against that:
  </p>
<div class="highlight"><pre><span class="k">import</span> <span class="nn">re</span>
<span class="k">from</span> <span class="nn">cgi</span> <span class="k">import</span> <span class="n">escape</span>

<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;This function will be mounted on &quot;/&quot; and display a link</span>
<span class="sd">    to the hello world page.&quot;&quot;&quot;</span>
    <span class="n">start_response</span><span class="p">(</span><span class="s">&#39;200 OK&#39;</span><span class="p">,</span> <span class="p">[(</span><span class="s">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s">&#39;text/html&#39;</span><span class="p">)])</span>
    <span class="k">return</span> <span class="p">[</span><span class="s">&#39;&#39;&#39;&lt;title&gt;Hello World Application&lt;/title&gt;</span>
<span class="s">               &lt;p&gt;This is the Hello World application:&lt;/p&gt;</span>
<span class="s">               &lt;p&gt;&lt;a href=&quot;hello/&quot;&gt;continue&lt;/a&gt;&lt;/p&gt;&#39;&#39;&#39;</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Like the example above, but it uses the name specified in the URL.&quot;&quot;&quot;</span>
    <span class="c"># get the name from the url if it was specified there.</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">environ</span><span class="p">[</span><span class="s">&#39;myapp.url_args&#39;</span><span class="p">]</span>
    <span class="k">if</span> <span class="n">args</span><span class="p">:</span>
        <span class="n">subject</span> <span class="o">=</span> <span class="n">escape</span><span class="p">(</span><span class="n">args</span><span class="p">[</span><span class="mf">0</span><span class="p">])</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">subject</span> <span class="o">=</span> <span class="s">&#39;World&#39;</span>
    <span class="n">start_response</span><span class="p">(</span><span class="s">&#39;200 OK&#39;</span><span class="p">,</span> <span class="p">[(</span><span class="s">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s">&#39;text/html&#39;</span><span class="p">)])</span>
    <span class="k">return</span> <span class="p">[</span><span class="s">&#39;&#39;&#39;&lt;title&gt;Hello </span><span class="si">%(subject)s</span><span class="s">&lt;/title&gt;</span>
<span class="s">            &lt;p&gt;Hello </span><span class="si">%(subject)s</span><span class="s">!&lt;/p&gt;&#39;&#39;&#39;</span> <span class="o">%</span> <span class="p">{</span><span class="s">&#39;subject&#39;</span><span class="p">:</span> <span class="n">subject</span><span class="p">}]</span>

<span class="k">def</span> <span class="nf">not_found</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Called if no URL matches.&quot;&quot;&quot;</span>
    <span class="n">start_response</span><span class="p">(</span><span class="s">&#39;404 NOT FOUND&#39;</span><span class="p">,</span> <span class="p">[(</span><span class="s">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s">&#39;text/plain&#39;</span><span class="p">)])</span>
    <span class="k">return</span> <span class="p">[</span><span class="s">&#39;Not Found&#39;</span><span class="p">]</span>

<span class="c"># map urls to functions</span>
<span class="n">urls</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s">r&#39;^$&#39;</span><span class="p">,</span> <span class="n">index</span><span class="p">),</span>
    <span class="p">(</span><span class="s">r&#39;hello/?$&#39;</span><span class="p">,</span> <span class="n">hello</span><span class="p">),</span>
    <span class="p">(</span><span class="s">r&#39;hello/(.+)$&#39;</span><span class="p">,</span> <span class="n">hello</span><span class="p">)</span>
<span class="p">]</span>

<span class="k">def</span> <span class="nf">application</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    The main WSGI application. Dispatch the current request to</span>
<span class="sd">    the functions from above and store the regular expression</span>
<span class="sd">    captures in the WSGI environment as  `myapp.url_args` so that</span>
<span class="sd">    the functions from above can access the url placeholders.</span>

<span class="sd">    If nothing matches call the `not_found` function.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">path</span> <span class="o">=</span> <span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;PATH_INFO&#39;</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s">&#39;/&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">regex</span><span class="p">,</span> <span class="n">callback</span> <span class="ow">in</span> <span class="n">urls</span><span class="p">:</span>
        <span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">path</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">match</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">environ</span><span class="p">[</span><span class="s">&#39;myapp.url_args&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
            <span class="k">return</span> <span class="n">callback</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">not_found</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
</pre></div>

  <p>
    Now that's a bunch of code. But you should get the idea how URL
    dispatching works. Basically if you now visit
    <tt>http://localhost:8080/hello/John</tt> you should get the same as above
    but with a nicer URL and a error 404 page if you enter the wrong url.
    Now you could improve that further by encapsulating
    <tt>environ</tt> in a request object and replacing the <tt>start_response</tt>
    call and the return iterator with a response objects. This is also what
    WSGI libraries like <a href="http://werkzeug.pocoo.org/">werkzeug</a>
    and <a href="http://www.pythonpaste.org/">paste</a> do.
  </p>
  <p>
    By adding something to the environment we did something normally middlewares
    do. So let's try to write one that catches exceptions and renders them in the
    browser:
  </p>
<div class="highlight"><pre><span class="c"># import the helper functions we need to get and render tracebacks</span>
<span class="k">from</span> <span class="nn">sys</span> <span class="k">import</span> <span class="n">exc_info</span>
<span class="k">from</span> <span class="nn">traceback</span> <span class="k">import</span> <span class="n">format_tb</span>

<span class="k">class</span> <span class="nc">ExceptionMiddleware</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;The middleware we use.&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">app</span> <span class="o">=</span> <span class="n">app</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Call the application can catch exceptions.&quot;&quot;&quot;</span>
        <span class="n">appiter</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="c"># just call the application and send the output back</span>
        <span class="c"># unchanged but catch exceptions</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">appiter</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
            <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">appiter</span><span class="p">:</span>
                <span class="k">yield</span> <span class="n">item</span>
        <span class="c"># if an exception occours we get the exception information</span>
        <span class="c"># and prepare a traceback we can render</span>
        <span class="k">except</span><span class="p">:</span>
            <span class="n">e_type</span><span class="p">,</span> <span class="n">e_value</span><span class="p">,</span> <span class="n">tb</span> <span class="o">=</span> <span class="n">exc_info</span><span class="p">()</span>
            <span class="n">traceback</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;Traceback (most recent call last):&#39;</span><span class="p">]</span>
            <span class="n">traceback</span> <span class="o">+=</span> <span class="n">format_tb</span><span class="p">(</span><span class="n">tb</span><span class="p">)</span>
            <span class="n">traceback</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%s</span><span class="s">: </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">e_type</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">e_value</span><span class="p">))</span>
            <span class="c"># we might have not a stated response by now. try</span>
            <span class="c"># to start one with the status code 500 or ignore an</span>
            <span class="c"># raised exception if the application already started one.</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">start_response</span><span class="p">(</span><span class="s">&#39;500 INTERNAL SERVER ERROR&#39;</span><span class="p">,</span> <span class="p">[</span>
                               <span class="p">(</span><span class="s">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s">&#39;text/plain&#39;</span><span class="p">)])</span>
            <span class="k">except</span><span class="p">:</span>
                <span class="k">pass</span>
            <span class="k">yield</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">traceback</span><span class="p">)</span>

        <span class="c"># wsgi applications might have a close function. If it exists</span>
        <span class="c"># it *must* be called.</span>
        <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">appiter</span><span class="p">,</span> <span class="s">&#39;close&#39;</span><span class="p">):</span>
            <span class="n">appiter</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>

  <p>
    So how can we use that middleware now? If our WSGI application is
    called <tt>application</tt> like in the previous example all we
    have to do is to wrap it:
  </p>
<div class="highlight"><pre><span class="n">application</span> <span class="o">=</span> <span class="n">ExceptionMiddleware</span><span class="p">(</span><span class="n">application</span><span class="p">)</span>
</pre></div>

  <p>
    Now all occouring exceptions will be catched and displayed in the
    browser. Of course you don't have to do that because there are
    many libraries that do exactly that and with more features.
  </p>
  <h3>Deployment</h3>
  <p>
    Now where the application is "finished" it must be installed on the
    production server somehow. You can of course use wsgiref behind mod_proxy
    but there are also more sophisticated solutions available. Many people for
    example prefer using WSGI applications on top of FastCGI. If you have
    <a href="http://trac.saddi.com/flup">flup</a> installed all you have to
    do is to defined a <tt>myapplication.fcgi</tt> with this code in:
  </p>
<div class="highlight"><pre><span class="c">#!/usr/bin/python</span>
<span class="k">from</span> <span class="nn">flup.server.fcgi</span> <span class="k">import</span> <span class="n">WSGIServer</span>
<span class="k">from</span> <span class="nn">myapplication</span> <span class="k">import</span> <span class="n">application</span>
<span class="n">WSGIServer</span><span class="p">(</span><span class="n">application</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>

  <p>
    The apache config then could look like this:
  </p>
<div class="highlight"><pre><span class="nt">&lt;VirtualHost</span> <span class="s">*</span><span class="nt">&gt;</span>
    <span class="nb">ServerName</span> www.example.com
    <span class="nb">Alias</span> <span class="sx">/public</span> <span class="sx">/path/to/the/static/files</span>
    <span class="nb">ScriptAlias</span> / <span class="sx">/path/to/myapplication.fcgi/</span>
<span class="nt">&lt;/VirtualHost&gt;</span>
</pre></div>

  <p>
    As you can see there is also a clause for static files. If you are in
    development mode and want to serve static files in your WSGI application
    there are a couple of middlewares (werkzeug and paste as well as "static"
    from Luke Arno's tools provide that) available.
  </p>
  <h3>NIH / DRY</h3>
  <p>
    Avoid the "Not Invented Here" problem and don't repeat yourself. Use the
    libraries that exist and their utilities! But there are so many! Which
    one to use? Here my suggestions:
  </p>
  <h4>Frameworks</h4>
  <p>
    Since Ruby on Rails appeared on the web everybody is talking about
    frameworks. Python has two major ones too. One that abstracts stuff
    very much and is called <a href="http://www.djangoproject.com/">Django</a>
    and the other that is much nearer to WSGI and called
    <a href="http://www.pylonshq.com/">pylons</a>. Django is an awesome
    framework but only as long as you don't want to distribute your
    application. It's if you have to create a webpage in no time. Pylons
    on the other hand requires more developer interaction and your applications
    are a lot easier to deploy.
  </p>
  <p>
    There are other frameworks too but <strong>my</strong> experiences
    with them are quite bad or the community is too small.
  </p>
  <h4>Utility Libraries</h4>
  <p>
    For many situations you don't want a full blown framework. Either because
    it's too big for your application or your application is too complex that
    you can solve it with a framework. (You can solve any application with a
    framework but it could be that the way you have to solve it is a lot more
    complex than without the "help" of the framework)
  </p>
  <p>
    For that some utility libraries exist:
  </p>
  <ul>
    <li><a href="http://pythonpaste.org/">paste</a> &mdash; used by pylons
        behind the scenes. Implements request and response objects. Ships
        many middlewares.</li>
    <li><a href="http://werkzeug.pocoo.org/">werkzeug</a> &mdash; minimal
        WSGI library we wrote for pocoo. Ships unicode away request and
        response objects as well as an advanced URL mapper and a interactive
        debugger.</li>
    <li><a href="http://lukearno.com/projects/">Luke Arno's WSGI helpers</a> &mdash;
        various WSGI helpers in independent modules by Luke Arno.</li>
  </ul>
  <p>
    There are also many middlewares out there. Just look for them at the
    <a href="http://cheeseshop.python.org/pypi?:action=search&term=wsgi">cheeseshop</a>.
  </p>
  <h4>Template Engines</h4>
  <p>
    Here a list of template engines I often use and recommend:
  </p>
  <ul>
    <li><a href="http://genshi.edgewall.org/">Genshi</a> &mdash; the world's
        best XML template engine. But quite slow, so if you need a really
        good performance you have to go with something else.</li>
    <li><a href="http://www.makotemplates.org/">Mako</a> &mdash; stupidely
        fast text based template engine. It's a mix of ERB, Mason and
        django templates.</li>
    <li><a href="http://jinja.pocoo.org/">Jinja</a> &mdash; sandboxed,
        designer friendly and quite fast, text based template engine. Of
        course my personal choice :D</li>
  </ul>
  <h3>Conclusion</h3>
  <p>
    WSGI rocks. You can simply create your own personal stack. If you think
    it's too complicated have a look at werkzeug and paste, they make things
    a lot easier without limiting you.
  </p>
  <p>
    I hope this article was useful.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/getting-started-with-wsgi</link>
      <guid>http://lucumr.pocoo.org/articles/getting-started-with-wsgi</guid>
      <author>Armin Ronacher</author>
      <pubDate>Mon, 21 May 2007 05:53:00 GMT</pubDate>
    </item>
    <item>
      <title>Evolve JavaScript, don't reinvent it</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  It's interesting how much buzz is out there about JavaScript currently. And
  you can read about possible successors more often as it seems. But i doubt
  that adding keywords like <tt>class</tt> or packages to that language would
  make it better.
</p>
  
  <p>
    JavaScript is a great language! But there are many design mistakes in, but
    probably different mistakes than you think. Having no class syntax etc is
    not a flaw, it's genious. Also one namespace is no issue at all since you
    can easly add closures around your stuff and return <em>one</em> element
    to the global namespace that has multiple members and substructures. This
    works pretty much like ruby namespaces if used in a sane way.
  </p>
  <p>
    But where are the mistakes then?
  </p>
  <h3>this</h3>
  <p>
    <tt>this</tt> is the biggest mistake in that language. It always points to
    something and in most situations it points to the global namespace which
    makes no sense since it makes working with closures a lot harder.
  </p>
  <p>
    In a situation where you call a function without sending a message from an
    object (just <tt>bar()</tt> and not <tt>foo.bar()</tt>) <tt>this</tt>
    should point to the this of the scope where the function is defined in:
  </p>
<div class="highlight"><pre><span class="c">/* current solution, one has to bind this to a different variable */</span>
<span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">User</span><span class="p">.</span><span class="nx">makeCounter</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">var</span> <span class="nx">counter</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>
  <span class="k">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="o">;</span>
  <span class="k">return</span> <span class="k">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="p">.</span><span class="nx">userCounter</span> <span class="o">&gt;</span> <span class="nx">counter</span><span class="p">)</span>
      <span class="nx">counter</span> <span class="o">=</span> <span class="nx">self</span><span class="p">.</span><span class="nx">userCounter</span><span class="o">;</span>
    <span class="k">return</span> <span class="o">++</span><span class="nx">counter</span><span class="o">;</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c">/* would make much more sense when this points to the outer this: */</span>
<span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">User</span><span class="p">.</span><span class="nx">makeCounter</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">var</span> <span class="nx">counter</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>
  <span class="k">return</span> <span class="k">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">userCounter</span> <span class="o">&gt;</span> <span class="nx">counter</span><span class="p">)</span>
      <span class="nx">counter</span> <span class="o">=</span> <span class="nx">self</span><span class="p">.</span><span class="nx">userCounter</span><span class="o">;</span>
    <span class="k">return</span> <span class="o">++</span><span class="nx">counter</span><span class="o">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>

  <h3>Inheritance</h3>
  <p>
    Inheritance in JavaScript works via prototypes. But it doesn't work in a
    nice way because there is no syntax for it. It would help if you have a
    syntax for inheriting stuff:
  </p>
<div class="highlight"><pre><span class="c">/* old school inheritance by setting the internal link to</span>
<span class="c">   an existing object by creating a new instance of an object: */</span>
<span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">NewClass</span> <span class="o">=</span> <span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">var</span> <span class="nx">cls</span> <span class="o">=</span> <span class="k">function</span><span class="p">()</span> <span class="p">{};</span>
  <span class="nx">cls</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">ParentClass</span><span class="o">;</span>
  <span class="nx">cls</span><span class="p">.</span><span class="nx">fooMethod</span> <span class="o">=</span> <span class="k">function</span><span class="p">()</span> <span class="p">{</span> <span class="p">...</span> <span class="p">};</span>
  <span class="nx">cls</span><span class="p">.</span><span class="nx">barMember</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
  <span class="k">return</span> <span class="k">new</span> <span class="nx">cls</span><span class="p">();</span>
<span class="p">})();</span>

<span class="c">/* with syntactic sugar: */</span>
<span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">NewClass</span> <span class="o">=</span> <span class="nx">MyNamespace</span><span class="p">.</span><span class="nx">ParentClass</span> <span class="o">&gt;&gt;</span> <span class="p">{</span>
  <span class="nx">fooMethod</span> <span class="o">:</span> <span class="k">function</span><span class="p">()</span> <span class="p">{</span> <span class="p">...</span> <span class="p">}</span><span class="o">,</span>
  <span class="nx">barMemner</span> <span class="o">:</span> <span class="mi">42</span>
<span class="p">};</span>
</pre></div>

  <p>
    That syntax might not be the best one but it says what happens. If if
    there is no syntax, at least there should be a factory function that
    does something similar (<tt>Object.extend</tt>).
  </p>
  <h3>More Functional Helpers</h3>
  <p>
    JavaScript is a functional language. That's what the intenion was and
    what it does best. So please add <tt>partial</tt>/<tt>curry</tt>,
    <tt>map</tt> and some other helpers either to the global namespace or
    to the arrays/functions itself.
  </p>
  <h3>Better Lambda</h3>
  <p>
    JavaScript has a function keyword that works exactly like a lambda
    should work. But it could be better by removing that keyword or making
    it a lot smaller. Possible solutions:
  </p>
<div class="highlight"><pre><span class="c">/* current solution */</span>
<span class="k">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">map</span><span class="p">([</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="p">]</span><span class="o">,</span> <span class="k">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="nx">item</span> <span class="o">*</span> <span class="nx">item</span><span class="o">;</span>
<span class="p">});</span>

<span class="c">/* ruby like solution */</span>
<span class="k">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">map</span><span class="p">([</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="p">]</span><span class="o">,</span> <span class="p">{</span> <span class="o">|</span><span class="nx">item</span><span class="o">|</span> <span class="nx">item</span> <span class="o">*</span> <span class="nx">item</span> <span class="p">});</span>

<span class="c">/* just making the keyword smaller */</span>
<span class="k">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">map</span><span class="p">([</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="p">]</span><span class="o">,</span> <span class="nx">def</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">item</span> <span class="o">*</span> <span class="nx">item</span> <span class="p">});</span>
</pre></div>

  <p>
    As you can see one of them has implicit defaults. And the ruby like
    solution would rewrite the pipe symbols, even if no arguments are
    passed because otherwise it would have a different meaning.
  </p>
  <h3>Iteration</h3>
  <p>
    JavaScript iteration works the wrong way. Especially since arrays are
    objects and iterate over their keys which is wrong and silly. Do what
    ruby does, call `each()` and pass it a function:
  </p>
<div class="highlight"><pre><span class="c">/* old solution for array iteration */</span>
<span class="k">for</span> <span class="p">(</span><span class="k">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">,</span> <span class="nx">n</span> <span class="o">=</span> <span class="nx">foo</span><span class="p">.</span><span class="nx">length</span><span class="o">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">n</span><span class="o">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">var</span> <span class="nx">item</span> <span class="o">=</span> <span class="nx">foo</span><span class="p">[</span><span class="nx">i</span><span class="p">];</span>
  <span class="p">...</span>
<span class="p">}</span>

<span class="c">/* old solution for object iteration */</span>
<span class="k">for</span> <span class="p">(</span><span class="k">var</span> <span class="nx">key</span> <span class="k">in</span> <span class="nx">foo</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">var</span> <span class="nx">value</span> <span class="o">=</span> <span class="nx">foo</span><span class="p">[</span><span class="nx">key</span><span class="p">];</span>
  <span class="p">...</span>
<span class="p">}</span>

<span class="c">/* ruby like solution for iteration */</span>
<span class="k">for</span> <span class="p">(</span><span class="k">var</span> <span class="nx">key</span><span class="o">,</span> <span class="nx">value</span> <span class="k">in</span> <span class="nx">foo</span><span class="p">)</span> <span class="p">{</span>
  <span class="p">...</span>
<span class="p">}</span>

<span class="c">/* which would be the same as */</span>
<span class="nx">foo</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="k">function</span><span class="p">(</span><span class="nx">key</span><span class="o">,</span> <span class="nx">value</span><span class="p">)</span> <span class="p">{</span> <span class="p">...</span> <span class="p">})</span>
</pre></div>

  <p>
    This of corse raises the question how <tt>continue</tt> and
    <tt>break</tt> should work then. The continue statement would translate
    to <tt>return</tt> and break to <tt>throw new StopIteration()</tt>.
  </p>
  <h3>Everything as Object / Operators</h3>
  <p>
    Throw away that stupid <tt>typeof</tt> operator and make Numbers, Booleans
    null, undefined whatever objects. Operator overloading would be a nice to
    have but it would make things much more complicated. At least the <tt>+</tt>
    Operator should not add and concatenate at the same time. The simple
    rshift Operator would be extend for other objects as seen above.
  </p>
  <p>
    Also <tt>==</tt> should become <tt>===</tt> and vice versa. Likewise for
    <tt>!=</tt> and <tt>!==</tt>.
  </p>
  <h3>Conclusion</h3>
  <p>
    This might not be the answer but it makes a lot more sense for a web
    centric language (which JavaScript certainly is) than another Java like
    language implementation.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/evolve-javascript-dont-reinvent-it</link>
      <guid>http://lucumr.pocoo.org/articles/evolve-javascript-dont-reinvent-it</guid>
      <author>Armin Ronacher</author>
      <pubDate>Tue, 08 May 2007 20:03:00 GMT</pubDate>
    </item>
    <item>
      <title>Why jQuery is The Answer</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  There are dozens of JavaScript libraries out there and god, I tried them all.
  And I have to say: No library solves problems in a nicer way than
  <a href="http://jquery.com/">jQuery</a>.
</p>
  
  <h3>What jQuery looks like</h3>
  <p>
    The most important part regarding JavaScript libraries in my eye is how
    verbose they are. I don't want to have cryptic constructs but I also don't
    want to type too much. Especially since it's pretty easy to create huge
    files and I don't want my application to load hundreds of kilobytes of
    JavaScript to the client's browser.
  </p>
  <p>
    So here a pretty nice example for jQuery that adds an anchor to all headlines:
  </p>
<div class="highlight"><pre><span class="nb">document</span><span class="p">.</span><span class="nx">ready</span><span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">for</span> <span class="p">(</span><span class="k">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">6</span><span class="o">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span>
    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;h&#39;</span> <span class="o">+</span> <span class="nx">i</span> <span class="o">+</span> <span class="s1">&#39; [@id]&#39;</span><span class="p">).</span><span class="nx">each</span><span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span>
      <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;&lt;a class=&quot;anchorlink&quot;&gt;\u00B6&lt;/a&gt;&#39;</span><span class="p">).</span>
        <span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;href&#39;</span><span class="o">,</span> <span class="s1">&#39;#&#39;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">id</span><span class="p">).</span>
        <span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;title&#39;</span><span class="o">,</span> <span class="s1">&#39;Permalink to this headline&#39;</span><span class="p">).</span>
        <span class="nx">appendTo</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
    <span class="p">});</span>
<span class="p">});</span>
</pre></div>

  <p>
    This is beautyful code in my mind. For several reasons. For one I can simply
    query elements by a mixture of XPath and CSS syntax. Then I can iterate over
    all result elements by passing an anonymous function to the <tt>each</tt>
    method. I don't even have to give it an variable name because jQuery
    automatically binds the value to <tt>this</tt>. Furthermore I can use
    <tt>$()</tt> to create an element and use the chaining possibilities to
    add attributes and append it to the headline in one go. Gorgeous!
  </p>
  <h3>Doing Things Right</h3>
  <p>
    I like cherrypicking a lot. Just combine the best of different libraries to
    do what you want. And JavaScript allows you to do that. Unlike PHP it's
    possible to have multiple namespaces (by adding objects to <tt>window</tt>)
    and binding values to that. jQuery uses that. It just creates
    <strong>one</strong> global objects and plays nice with others. The default
    alias from <tt>jQuery</tt> to <tt>$</tt> is completely optional, thus you
    can combine jQuery with many other libraries without triggering namespace
    clashes etc.
  </p>
  <p>
    It doesn't patch a single builtin. That's awesome. Also jQuery includes basic
    support for effects and nice event support. While the library itself is
    quite big with 57KB, the compressed version is only 19KB big.
  </p>
  <p>
    It's also darn fun to work with. I don't want to miss this and firebug
    any more :-)
  </p>
  <h3>Plugins</h3>
  <p>
    jQuery has a <a href="http://docs.jquery.com/Plugins">list of plugins</a> in
    the wiki and that page is really awesome long :-) From Since jQuery was
    developed in an extensible way plugins integrate nicely into the jQuery
    core. For example if you have <a href="http://interface.eyecon.ro/">interface</a>
    loaded you can do this:
  </p>
<div class="highlight"><pre><span class="nb">document</span><span class="p">.</span><span class="nx">ready</span><span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#message&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">Fold</span><span class="p">(</span><span class="mi">500</span><span class="o">,</span> <span class="mi">30</span><span class="p">);</span>
  <span class="p">});</span>
<span class="p">});</span>
</pre></div>

  <p>
    This will fold the element with id <tt>message</tt> once it's clicked.
  </p>
  <h3>What I don't like about Others</h3>
  <dl>
    <dt><a href="http://www.prototypejs.org/">prototype.js</a></dt>
    <dd><p>
      Prototype, the default answer you get these days by any rails developer.
      It's one of the first flashy javascript libraries but it sucks for many
      reasons. Until the most recent version it was nearly impossible to find
      a good documentation of it. Also the way you work with the library is
      too rubysh. That's not bad if you are a rails developer but it makes no
      sense outside the rails environment. JavaScript itself behaves a lot more
      like Python or LISP due to first class functions.</p>
      <p>It also includes dozens of functions I really don't use or want to use.
      So why do I have to add those to my requirements too? A huge stdlib makes
      sense for an offline language but clearly not for javascript.</p>
    </dd>
    <dt><a href="http://orangoo.com/labs/AJS/">AJS</a></dt>
    <dd>
      We used it in pocoo before we discovered jQuery. Really a nice library
      but the lack of XPath support is a real show stopper over jQuery. If
      you don't need chainability or XPath you could go with this library.
      It provides some nice things like <tt>forceArray</tt> :-)
    </dd>
    <dt><a href="http://mootools.net/">mootools</a></dt>
    <dd>
      Awesome library but I still like jQuery better. If there wasn't jQuery
      I would use Mootools :-) It's also a bit too flashy for my needs. I want
      a non sucking javascript and not blinking elements everywhere ^^
    </dd>
    <dt><a href="http://mochikit.com/">mochikit</a></dt>
    <dd>
      Was a nice library some years ago but it's not lightweight any more.
    </dd>
    <dt><a href="http://dojotoolkit.org/">dojo</a></dt>
    <dd>
      Awesome but huge library. The API sucks in comparison with jQuery but
      it provides stunning stuff. Especially regarding vector graphics.
      But it's huge...
    </dd>
  </dl>
  <h3>Conclusion</h3>
  <p>
    jQuery is really the answer. For my requirements :-) Maybe you have similar
    and don't know jQuery so far, give it a try. It's more than fun to work with.
  </p>
  <p>
    I know that there are many other libraries out there but most of them have
    different views of some things (especially patching prototypes of public
    objects) which are not compatible with my point of view. This doesn't
    mean that those libraries are bad. But they just don't work that well for
    me.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/why-jquery-is-the-answer</link>
      <guid>http://lucumr.pocoo.org/articles/why-jquery-is-the-answer</guid>
      <author>Armin Ronacher</author>
      <pubDate>Tue, 24 Apr 2007 16:32:00 GMT</pubDate>
    </item>
    <item>
      <title>Imagecode — Stop That Shit</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  <a href="http://redhanded.hobix.com/bits/gem_mirror_only.html">Looks</a>
  <a href="http://redhanded.hobix.com/inspect/nostrils.html">like</a>
  <a href="http://redhanded.hobix.com/cult/ahaNoticeTheExpandoWhichPrecludes.html">it's</a>
  <a href="http://redhanded.hobix.com/inspect/hpricotAndMarkabyElope.html">modern</a>
  <a href="http://redhanded.hobix.com/inspect/okayWhichBrowserWillRunThisCodeAndCanYouGetItToDoItsThing.html">to</a>
  <a href="http://redhanded.hobix.com/inspect/streamCopyYoutubeRevverEtc.html">lock out</a>
  <a href="http://redhanded.hobix.com/inspect/randomNumberInAFeedForPipesMaybe.html">disabled</a>
  <a href="http://www.rubyinside.com/rubyscript-or-running-ruby-scripts-in-the-browser-459.html">persons</a>.
</p>
  
  <p>
    And it breaks copy/paste too. And i cannot read it from my mobile phone. And
    it's awefully slow to download it via GPRS (and expensive too). And it's hard
    to read, makes my eyes sick et cetera.
  </p>
  <p>
    <strong>So please:</strong>
  </p>
  <img class="standalone" src="/static/pictures/stop_that_shit.png"
       alt="could you do me a favor? Stop that shit! It keeps killing
       my ponies^W lobsters^W eyes!">
  <p>
    <small>This image has an alt tag!</small>
  </p>
  <h3>Update</h3>
  <p>
    <a href="http://www.rubyinside.com/">Peter Cooper</a>
    <a href="http://redhanded.hobix.com/bits/gem_mirror_only.html#comments">wants
    you to know</a> that:
  </p>
  <blockquote>
    There was no point in including the Ruby Inside link in that post.
    It’s not a code example, it's a /screenshot/ to give an impression.
    The actual code is on the page linked to ready to copy and paste.
  </blockquote>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/imagecode-stop-that-shit</link>
      <guid>http://lucumr.pocoo.org/articles/imagecode-stop-that-shit</guid>
      <author>Armin Ronacher</author>
      <pubDate>Sat, 21 Apr 2007 13:23:00 GMT</pubDate>
    </item>
    <item>
      <title>Digital Fortress — Stranger Than Fiction</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  I don't rant that often about books. But when I read
  <a href="http://www.danbrown.com/novels/digital_fortress/reviews.html">that</a>
  book I nearly had to vomit. I seldom read such a piece of crap.
</p>
  
  <h3>Synopsis</h3>
  <p>
    "Digital Fortress" is a book by Dan Brown, written back in 1998.
  </p>
  <p>
    Susan Fletcher, a brilliant, beautiful mathematician and head of the National
    Security Agency's cryptography departement, finds herself faced with an
    unbreakable code resistant to brute-force attacks by the NSA's 3 million
    processor supercomputer.
  </p>
  <p>
    The code is written by Japanese cryptographer Ensei Tankado, a former employee
    of her departement, who now uses his knowledge to work against the NSA to avoid
    further intrusion into people's privacy. Tankado publishes the algorithm on his
    website, encrypted with itself. He sells the passphrase for encrypted data on
    an auction platform, threatening that his accomplice, "North Dakota", will
    release the algorithm for free if he dies.
  </p>
  <p>
    This algorithm would be the end of the NSA and the TRANSLTR supercomputer.
    Unfortunately Tankado is found dead in Seville, Spain. Susan Fletcher, along
    with her boyfriend, David Becker, a skilled linguist, must find a solution
    to stop the spread of the code.
  </p>
  <h3>Sounds Interesting. What's the Problem?</h3>
  <p>
    Alright. Here comes the problem. But first a small information: I'm not a
    cryptographer and thus not completely informed about that topic.
    Nonetheless I did enough encryption/decryption for my IT lessons in the
    past that I can accuse Dan Brown for not having the slightest knowledge
    about cryptography, information technology, computer viruses, worms and
    also not Spain. So let's start with non technology related bullshit in that book.
  </p>
  <h3>Seville &mdash; Spain</h3>
  <p>
    I personally was never in Seville itself but I'm darn sure that the description
    of Spain in that book is terrible wrong. On my last visit to Spain it was a
    country like Italy or any other southern European country thus quite safe,
    friendly and modern.
  </p>
  <p>
    There are two sentences in that book that would hurt every Spanish:
  </p>
  <blockquote><p>
    "He'd forgotten: Getting an international connection from Spain was like
    roulette, all a matter of timing and luck. He'd have to try again in a
    few minutes."
  </p>
  <p>
    "A punctured lung was fatal, maybe not in more medically advanced parts
    of the world, but in Spain, it was fatal."
  </p></blockquote>
  <p>
    I don't think I have to further comment that sentence.
  </p>
  <h3>Technology</h3>
  <p>
    Before heading over to cryptography let's have a look at the dozens of
    other flaws in that book. Let's start with the obvious ones.
  </p>
  <h4>About Viruses And Worms</h4>
  <p>
    Half of the story is about a computer that overheats because it's
    processing a virus instead of an encrypted file. Now this is not a
    virus, it's not even a worm like mentioned later. It's just bullshit.
    First of all in order to brute-force something you have to know how
    it works, but that's covered later. However if you then brute force
    something you don't execute it. Say that this file contains indeed
    malicious code. Then nobody would have executed it with root rights.
    I doubt NSA would break code in something that is not a sandboxed
    environment.
  </p>
  <p>
    Also that this program then heads over to the database in order to
    bypass the security systems is not only unlikely, it's impossible.
    If it was possible for the program (and TRANSLATR would execute
    the code during the decoding process) to gain access to the database it
    would not be able to shut down the security systems of that database.
    Not even in the worst computer setup the database software would run in
    the same security context as the security systems like the firewall.
  </p>
  <p>
    Reading those parts of the book really hurts. Especially at the end
    when he starts throwing buzzwords around. Then there is a countdown
    and the security systems for X11 and FTP go down. Not before all
    systems are down anyone can gain access. Well, and then the hackers
    try to break into that system all day long. Thus as soon as the system
    is down the first attacker would already have access to all data.
  </p>
  <p>
    An attacker would still need credentials to log into an FTP system.
    And I doubt that NSA would use FTP and X11 in their mainframe. FTP is a
    insecure protocol and X11 is the system used by UNIX systems to display
    graphical user interfaces over either the network or on the local
    computer. I doubt they would make X11 listen on anything else than
    localhost...
  </p>
  <h4>Mutation Strings</h4>
  <p>
    Now what the hell are mutation strings? The only thing I know sounding
    familiar are mutable strings. But I doubt Dan Brown thought about that,
    especially since those are not virus specific. There is one thing viruses
    do that has to do with mutation: Changing executables at runtime, but
    that's not called mutation string.
  </p>
  <h4>Passwords and Keyloggers</h4>
  <p>
    Greg Hale installed a keylogger in nearly every keyboard on the NSA
    complex according to the book. While this is a realistic scenario there
    is still something you should think about: We're talking about the NSA,
    they should use more sophisticated logon mechanisms than 5 character long
    passwords.
  </p>
  <p>
    I know many people (including myself) who use passwords with more than
    15 characters. I doubt someone working for the NSA would use a 5 character
    password.
  </p>
  <h4>Tracers</h4>
  <p>
    According to the book it's possible to find out the real address of a
    person by sending him a "tracer". A small programm forwarded via the
    remailer to the destination address which then sends an invisible message
    back to the NSA revealing the real mail address. This is complete bullshit
    of course. Unless there is a security hole in the mail client that
    executes the code, deletes the mail and sends a message back this
    can never happen. And that the mail client is that buggy is doubtable.
    This could be possible via social engineering but since the target is
    neither stupid nor alive Susan won't have received a mail.
  </p>
  <h3>Cryptography</h3>
  <p>
    Now things are getting worse. If you don't have a clue about what you're
    writing regarding technology that's bad. But if your book is all about
    cryptograhy and you don't know anything about it and mix up words that's
    really bad.
  </p>
  <h4>Brute Force</h4>
  <p>
    Dan Brown thinks you can break everything with brute force, out of the
    box. That's wrong. In order to break something using Brute Force you have
    to know how it works. Brute Force is a great method to recover passwords
    to break into systems as long as nobody locks you out because of those
    many login attempts, but you cannot break ciphers using brute force if
    you don't know how they works.
  </p>
  <p>
    And Dan Brown is looking for a method you cannot break: That's called
    One-Time-Pad, is mathematically unbreakable and easily implemented. The
    idea is that you use a polyalphabethic cipher where the key is completely
    random and as long as the clear text and only used one time.
  </p>
  <h4>Rotating Cleartext</h4>
  <p>
    Flaw 1: the rotating cleartext algorithm. There is no such thing. There
    is an addition to the Vigenère cipher which is called "autokey" and uses
    the cleartext to expand the key instead of repeating the key. As soon as
    the key is exhausted it appends the cleartext. But it's breakable too.
  </p>
  <h4>bit ≠ characters ≠ passphrase</h4>
  <p>
    A 64bit key does not mean that the passphrase is 64 characters long. And
    breaking a 64bit key takes quite long. Today we're using more than 64bit
    to encode messages. Wikipedia has a nice example calculation of a
    bruteforcing 256bit key:
  </p>
  <blockquote><p>
    AES permits the use of 256 bit keys. A 256 bit key requires not merely
    twice as long to crack as a 128 bit key, but rather 2<sup>128</sup> times
    as long. If a device could be built that could check a billion billion
    (10<sup>18</sup>) AES keys per second, it would require
    3,671,743,063,080,802,746,815,416,825,491,118,336,290,905,145,409,708
    years to exhaust the 256 bit key space.
  </p></blockquote>
  <p>
    That in mind smashes the whole plot of the book.
  </p>
  <h4>Bergofsky Principle</h4>
  <p>
    Something Dan Brown mentiones often in the book which says that
    "if a computer tried enough keys, it was mathematically guaranteed to
    find the right one.". As mentioned about that is wrong. (One-Time Pad)
  </p>
  <h4>Public-Key Encryption</h4>
  <p>
    Dan thinks that you need the senders pass key to decrypt a message
    encrypted using public-key cryptography. This is just wrong...
  </p>
  <h4>Auctioning the Pass-Key</h4>
  <p>
    The "bad guy" sells the key on ebay. But the algorithm is encoded
    with itself. So how should someone every unlock that algorithm if
    you need the algorithm to unlock it which is locked by itself?
  </p>
  <h3>Conclusion</h3>
  <p>
    Normally I don't mind if a book contains wrong facts. But this book uses
    wrong facts in an inflationary way. It would be easy to add new items to
    this rant since there are enough inconsistencies and other wrong things
    in the book, but I'm out of time.
  </p>
  <p>
    The book is boring and the plot childish. Not worth the money.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/digital-fortress-stranger-than-fiction</link>
      <guid>http://lucumr.pocoo.org/articles/digital-fortress-stranger-than-fiction</guid>
      <author>Armin Ronacher</author>
      <pubDate>Thu, 19 Apr 2007 16:23:00 GMT</pubDate>
    </item>
    <item>
      <title>Vim as Development Environment</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  I do all of my development (well, except of some Java stuff for school)
  using <a href="http://www.vim.org/">vim</a>. This small article should show
  some of the plugins I use because quite a few people asked me for them.
</p>
  
  <h3>Introduction</h3>
  <p>
    First of all I have to defend vim. Many people think vim is a hacker tool
    and real developers (apparently hackers are not developers?) use IDEs.
    Well, that's only partially true. I use a IDE for C# and Java too but that
    has to do with the fact that those languages are completely different to
    ruby, python, HTML markup or whatever I use vim for. And if there would be
    an vim Ecplipse plugin I'm sure that I would use it.
  </p>
  <p>
    Vim is still the best editor for me. The graphical version has support for
    many colors (i like them ^^), many different syntax schemes and it handles
    nested syntax blocks hell (eg, jinja templates in HTML).
  </p>
  <h3>Theme</h3>
  <p>
    For the plugins listened below I wrote a theme for myself which adds
    more colors to the syntax elements provided by them. The theme has different
    colors for most of the syntax elements and is optimized for python, HTML,
    django/Jinja, JavaScript and Ruby.
  </p>
  <p>
    It's quite colorful (too colorful for many ^^) and is a GUI only theme.
    See the screenshots below for some examples.
  </p>
  <ul>
    <li><a href="http://pocoo.org/~mitsuhiko/fruity.vim">fruity.vim</a></li>
  </ul>
  <h3>Syntax Files</h3>
  <p>
    The default vim syntax files are nice but not colorful enough for me.
    Especially the default HTML and Python files are crap in comparison what
    you can get on <a href="http://www.vim.org/">vim.org</a>. However I did
    some local changes on some of the files for my needs and I don't upgrade
    those scripts because of that. If you want exactly the files I use have
    a look at them.
  </p>
  <p>
    Note that some of them mainly exist because they are a requirement for
    another file (all those svn files belong to each other, mathml and svg
    belong to html). The eruby.vim file is my own one with support for
    <tt>%</tt> lines not supported in the version from the vim webpage and
    it also handles comments correctly.
  </p>
  <ul>
    <li><a href="http://pocoo.org/~mitsuhiko/eruby.vim">eruby.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/html.vim">html.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/javascript.vim">javascript.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/mathml.vim">mathml.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/python.vim">python.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/svg.vim">svg.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/svnannotate.vim">svnannotate.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/svnlog.vim">svnlog.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/svn.vim">svn.vim</a></li>
  </ul>
  <h3>Plugins</h3>
  <p>
    The same applies for the plugins. I use the minibufexplorer (interestingly
    I don't use vim 7 tab feature myself), the close tag plugin and the textmate
    snippets emulation called SnippetsEmu. Both plugin unchanged from the
    vimscripts webpage:
  </p>
  <ul>
    <li><a href="http://www.vim.org/scripts/script.php?script_id=1318">SnippetsEmu</a></li>
    <li><a href="http://www.vim.org/scripts/script.php?script_id=159">minibufexplorer</a></li>
    <li><a href="http://www.vim.org/scripts/script.php?script_id=13">closetag</a></li>
    <li><a href="http://www.vim.org/scripts/script.php?script_id=1856">Jinja Highlight Suppoprt</a></li>
  </ul>
  <h3>Snippets for SnippetsEmu</h3>
  <p>
    I don't use the original snippets because when I first tried out SnippetsEmu
    it shipped some i don't wanted to use and those I would have used were
    completely broken. Because I haven't upgraded the plugin I still use mine.
    If are interested in, here they are:
  </p>
  <ul>
    <li><a href="http://pocoo.org/~mitsuhiko/css_snippets.vim">css_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/eruby_snippets.vim">eruby_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/htmljinja_snippets.vim">htmljinja_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/javascript_snippets.vim">javascript_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/python_snippets.vim">python_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/django_snippets.vim">django_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/htmldjango_snippets.vim">htmldjango_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/html_snippets.vim">html_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/jinja_snippets.vim">jinja_snippets.vim</a></li>
    <li><a href="http://pocoo.org/~mitsuhiko/ruby_snippets.vim">ruby_snippets.vim</a></li>
  </ul>
  <h3>vimrc</h3>
  <p>
    Okay. Now to my vimrc. In order to get that thing working you have to
    install all of the plugins from that page. At least I guess so because it
    configures a lot of the plugins here.
  </p>
  <ul>
    <li><a href="http://pocoo.org/~mitsuhiko/_vimrc">.vimrc</a></li>
  </ul>
  <h3>Tips And Tricks</h3>
  <p>
    Here some various tips and tricks for vim I use every day.
  </p>
  <h4>The * and # Keys</h4>
  <p>
    In normal mode you can use <tt>*</tt> and <tt>#</tt> to search for the
    word under the cursor. <tt>*</tt> search forwards, <tt>#</tt> backwards.
  </p>
  <h4>The . Key</h4>
  <p>
    Also useful is the <tt>.</tt> key. In normal mode it repeats the last
    change. Very useful for XML editing and where you have to do similar stuff.
  </p>
  <h4>The % Key</h4>
  <p>
    Pressing the <tt>%</tt> key in normal mode while being on a parenthesis or
    a similar construct jumps to the opposite parenthesis. There are a couple
    of plugins that extend that functionallity but the default behavior is
    usually good enough for most of the programming languages.
  </p>
  <h4>The &lt; and &gt; Keys</h4>
  <p>
    When working with Python you often have to indent or outdent a couple
    of lines. Just mark them using the visual mode and press <tt>&gt;</tt>
    to indent them. press <tt>4&lt;</tt> to outdent them 4 steps etc.
  </p>
  <h4>Advanced Undo Features</h4>
  <p>
    Vim has a different system of undoing changes. The normal undo is
    <tt>u</tt> in normal mode and <tt>^r</tt> is redo. But what happens if
    you undo a few things and then change something? A normal editor forgets
    about the new changes. It's not possible to redo that again.
  </p>
  <p>
    In Vim it's different. Vim starts a new undo branch. Using
    <tt>:undolist</tt> you can have a look at the possible undo states.
    With <tt>:earlier 20s / 1m / 2h</tt> you can then go back 20 seconds,
    one minute etc. Traveling forward in time works using <tt>:later</tt>
    and a timedelta as argument.
  </p>
  <h4>The Search Feature</h4>
  <p>
    I really like the firefox search feature. Just hit "/" and you can
    search in the current file and get the results in real time. That
    works with vim exactly the same. All you have to to is to either add
    <tt>:set incsearch</tt> into your vimrc or type it into the command
    prompt. Using <tt>n</tt> you can go to the next result. If you want
    to have all the search results highlighted use <tt>:set hlsearch</tt>.
    Hiding the results works using <tt>:nohl</tt>
  </p>
  <h4>Closing XML Tags</h4>
  <p>
    If you have the closetag.vim plugin installed (link above) you can add
    this to your vimrc in order to get the feature working:
    <tt>autocmd FileType html,xhtml,xml source ~/.vim/scripts/closetag.vim</tt>
    (update the path to your installation and your filetypes of course)
    Once this is done you can close open tags using <tt>^_</tt>.
  </p>
  <h4>Regexp Replacement after Search</h4>
  <p>
    If you searched for a text using <tt>/foo</tt> and you now want
    to replace the found results with something you don't have to write
    this regexp again. Just do <tt>:%s/&lt;c-r&gt;//replacement/g</tt>
    and <tt>&lt;c-r&gt;</tt> is automatically replaced with the last
    search regular expression.
  </p>
  <h4>Using Bookmarks</h4>
  <p>
    Bookmarking in vim is darn easy. If you are on the current line just
    bookmark it with <tt>mX</tt> where <tt>X</tt> is a lowercase letter
    from a to z. Go to that mark using <tt>'X</tt> where X is the same
    letter again. Using <tt>''</tt> you can jump back to the position
    you were before jumping to the bookmark. You can get the list of
    bookmarks using <tt>:marks</tt>.
  </p>
  <h4>The Vim File Browser</h4>
  <p>
    The Vim File browser is a nice thing. If you open a file using
    <tt>:e</tt> and that file is a directory you get a nice file browser
    for the files in that directory. If you are a python developer you
    probably want to filter some files out (<tt>*.pyc</tt> etc).
    Add this to your vimrc:
    <tt>let g:explHideFiles='^\.,.*\.pyc$'</tt> This hides pyc files as
    well as hidden files.
  </p>
  <h4>The Wildmenu</h4>
  <p>
    The best vim feature is the wildmenu. Add a <tt>set wildmenu</tt>
    to your vimrc and discover the possibilities of filesystem surfing ^^
    Enter <tt>:e </tt> in the command line and press <tt>^D</tt>.
    Vim will show you all possibitilites in a nice little window. By
    entering the start of a filename and pressing tab it completes for
    you then. If it was a folder you can now press <tt>^D</tt> again
    to get the contents. Once you finished the command this window
    will disappear again and you can continue working. Works of course
    for all commands not only the open command.
  </p>
  <h4>Vim Completion Features</h4>
  <p>
    Last tip but maybe the most powerful one :). If you have vim7 and
    omni completion for your language you can use <tt>^X^O</tt> to get
    the completion similar to intelli sense or how it's called. Note
    that the default color (pink) can be overridden in the theme.
    In my fruity.vim file i use this to get white letters on a dark
    red background: <tt>hi Pmenu guifg=#ffffff guibg=#cb2f27</tt>
  </p>
  <p>
    Also nice is <tt>^N</tt>. It looks up all used words in the open
    buffers and presents then in a dropdown completion. Useful if you
    have long variable names and don't remember them. Just type in the
    start of the variable name and press <tt>^N</tt>. Vim will either
    complete it or show the list of possibilities.
  </p>
  <h3>Screenshots</h3>
  
  <div class="gallery" id="screenshots" title="Screenshots">
  
    <a href="/static/pictures/vim_pocoo_dev.png" title="Vim for Pocoo Development"><img src="/static/pictures/vim_pocoo_dev_thumb.png" alt="Vim for Pocoo Development"></a>
  
    <a href="/static/pictures/vim_ruby_dev.png" title="Ruby Development using Vim"><img src="/static/pictures/vim_ruby_dev_thumb.png" alt="Ruby Development using Vim"></a>
  
    <a href="/static/pictures/vim_wildmenu.png" title="Using the Vim Wildmenu"><img src="/static/pictures/vim_wildmenu_thumb.png" alt="Using the Vim Wildmenu"></a>
  
    <a href="/static/pictures/vim_completion.png" title="Vim with Omni Completion"><img src="/static/pictures/vim_completion_thumb.png" alt="Vim with Omni Completion"></a>
  
    <a href="/static/pictures/jinja_in_vim.png" title="Jinja Syntax in Vim"><img src="/static/pictures/jinja_in_vim_thumb.png" alt="Jinja Syntax in Vim"></a>
  
  </div>
  <script type="text/javascript">
    if (typeof window.jQuery != 'undefined')
      $(document).ready(function() {
        Lucumr.PictureBox.init(['screenshots']);
      });
  </script>


  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/vim-as-development-environment</link>
      <guid>http://lucumr.pocoo.org/articles/vim-as-development-environment</guid>
      <author>Armin Ronacher</author>
      <pubDate>Mon, 02 Apr 2007 10:23:00 GMT</pubDate>
    </item>
    <item>
      <title>Why I Still Choose Python</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  If you have a look at the <a href="/projects/">projects</a> sections you
  will find out that most of the projects I'm working on are implemented in
  the python programming language. Because of that I'm earing lots of
  criticism on <tt>#ruby-lang</tt>. But there are in fact reasons for that.
</p>
  
  <h3>Language Design</h3>
  <p>
    A recent discussion with someone (which will go unnamed) again showed up
    that many people think python has a bad language design. Things that
    are "wrong" or missing in python are:
  </p>
  <ul>
    <li>continuation support</li>
    <li>ruby like blocks</li>
    <li>anonymous functions</li>
    <li>weak functional programming support</li>
    <li>statements that aren't expressions (assignments)</li>
    <li>bad object orientation</li>
  </ul>
  <p>
    Interestingly just one of this points is a problem for me. The latter.
    I would really like to have assignments as expressions but I can also
    understand Guido who wants to avoid mistakes in the application logic
    that are caused by an assignment which should be an comparison.
  </p>
  <p>
    Now to the items on the list. Especially the missing continuation support.
    Because I never was in a situation where I needed them. By now I could
    solve all of my problems using generators or context managers.
  </p>
  <p>
    Because of the fact that python functions are objects I can define them
    in any namespace. A function in a function doesn't look like an anonymous
    one but semantically there are few differences. And if you say there is
    a weak functional programming support I cannot assent. Python has list
    comprehensions, generator expressions, first class functions and there
    are libraries that enable currying.
  </p>
  <p>
    And now to the bad object orientation. Some people think the python object
    system is bad because it's flange mounted (the explicit self) or because
    some functions like <tt>len()</tt> are globals and not instance methods.
    The excplicit self is something you have to live with. There are some
    reasons for that implementation detail, one of them is that python doesn't
    have a ruby like <tt>super</tt>. Instead of calling a method of the
    superclass you just call a method of any class in the MRO and provide the
    self (<tt>MyClass.my_method(self, arguments, go='here')</tt>). That is
    much nicer than  <tt>MyClass.method(:my_method).bind(self).call(arguments,
    :go =&gt; "here")</tt> like you do in ruby.
  </p>
  <p>
    The global functions on the other side are something that is indeed
    interesting. When I first worked with Python i wondered why some functions
    are global. Among those are <tt>len()</tt>, <tt>str()</tt>, <tt>abs()</tt>
    etc. But the idea is in my eyes a very good one. Instead of adding a
    property called <tt>.length</tt> to an object you provide a method
    named <tt>__len__()</tt> which will be called by the global <tt>len()</tt>
    function. The big advantage: You can still use <tt>.length</tt> for
    whatever you want, type checks for <tt>hasattr(foo, '__len__')</tt>
    won't yield wrong results because <tt>__len__</tt> is a special method
    and doing something else than returning the length of an object is just
    silly. I know a lot of programming languages (For example C#) where
    different objects have different size methods/properties (<tt>Size</tt>,
    <tt>Length</tt>, <tt>Count</tt>) and without and IDE or a good memory
    you have to have a look at the documentation then.
  </p>
  <p>
    The <tt>str()</tt> in the last paragraph is global too. But not a
    function. It's the class of strings and because of that not an instance
    method. To control the string conversion you can however provide a
    <tt>__str__</tt> method. This is something i personally really like.
  </p>
  <p>
    Things I miss in ruby are:
  </p>
  <ul>
    <li>support for boolean value overloading</li>
    <li>support for overloading the function call operator</li>
    <li>unicode support</li>
    <li>slightly better threading support (at least native threads)</li>
    <li>native generators</li>
    <li>first-class methods. (I'm not talking about Proc or code blocks)</li>
    <li>slightly cleaner syntax</li>
  </ul>
  <h3>Maintainability</h3>
  <p>
    Say what you want but python is easier to maintain. For sure there are
    some libraries that are written like the developer was stoned but those
    are exceptions. Python doesn't support complex constructs like assignments
    in expressions, magic local variables like <tt>$~</tt> and there is no
    implicit return value which can screw things up or make it hard to find
    out where exactly the return value is coming from. There is also no
    callcc which might be a cool thing but is hard to understand for people
    not using it. But there are also constructs in python that can really
    fuck up semantics. For example metaclasses. They are really great if you
    use them wisely but never try to do something with them nobody undestands.
  </p>
  <h3>Object System</h3>
  <p>
    Python and Ruby are both object orientated languages. But there are a few
    differences. Ruby doesn't have metaclasses and no multiple inheritance. On
    the other side there are special "singleton" objects which support some
    basic "per class" manipulation. This might be enough for ActiveRecord and
    other libraries to modify classes but I don't really like the idea of it
    because it's not clean in my eyes. Here the difference explained.
  </p>
  <p>
    The following example shows how metaclasses in python work:
  </p>
<div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">ClassOfFoo</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">method_of_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>  <span class="k">print</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="gp">... </span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ClassOfFoo</span>
<span class="gp">... </span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">Foo</span><span class="p">,</span> <span class="n">ClassOfFoo</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Foo</span><span class="o">.</span><span class="n">method_of_foo</span><span class="p">()</span>
<span class="go">&lt;class &#39;__main__.Foo&#39;&gt;</span>
</pre></div>

  <p>
    And here the same functionallity in ruby:
  </p>
<div class="highlight"><pre><span class="gp">irb(main):001:0&gt; </span><span class="k">class</span> <span class="nc">Foo</span>
<span class="gp">irb(main):002:1&gt; </span> <span class="k">class</span> <span class="o">&lt;&lt;</span> <span class="nb">self</span>
<span class="gp">irb(main):003:2&gt; </span>  <span class="k">def</span> <span class="nf">method_of_foo</span>
<span class="gp">irb(main):004:3&gt; </span>   <span class="nb">puts</span> <span class="nb">self</span><span class="o">.</span><span class="n">inspect</span>
<span class="gp">irb(main):005:3&gt; </span>  <span class="k">end</span>
<span class="gp">irb(main):006:2&gt; </span> <span class="k">end</span>
<span class="gp">irb(main):007:1&gt; </span><span class="k">end</span>
<span class="go">=&gt; nil</span>
<span class="gp">irb(main):008:0&gt; </span><span class="no">Foo</span><span class="o">.</span><span class="n">method_of_foo</span>
<span class="go">Foo</span>
<span class="go">=&gt; nil</span>
</pre></div>

  <p>
    But that's not the class of a class. This just modifies the singleton
    of a class object to add a new method. Metaclasses as such don't work,
    also not without syntactic sugar because you cannot subclass
    <tt>Class</tt>:
  </p>
<div class="highlight"><pre><span class="gp">irb(main):009:0&gt; </span><span class="k">class</span> <span class="nc">FooType</span> <span class="o">&lt;</span> <span class="no">Class</span>
<span class="gp">irb(main):010:1&gt; </span><span class="k">end</span>
<span class="go">TypeError: can&#39;t make subclass of Class</span>
<span class="go">        from (irb):9</span>
<span class="go">        from :0</span>
</pre></div>

  <p>
    This might be only a small detail but I like it a lot and I don't want to
    miss it.
  </p>
  <h3>Regular Expressions</h3>
  <p>
    In Ruby 1.8 regular expressions are terrible limited. For me (who uses
    regular expressions in nearly every library) this is a major annoyance.
    fullstop.
  </p>
  <h3>Libraries and Webdevelopment</h3>
  <p>
    At least for the moment Python has the bigger library database. And even
    although <tt>easy_install</tt> is something I find a bit broken it's a lot
    better designed than <tt>gems</tt>. Especially because it doesn't require
    changes in the ruby libraries that use gems and it doesn't have to unpack
    eggs to import them. (Which is also faster)
  </p>
  <p>
    Also webdevelopment with python makes more fun. At least for the moment.
    For basic CRUD stuff you can use django, for advanced applications there
    are hundreds of libraries and the great WSGI specs. Ruby got a WSGI clone
    too some time ago called <a href="http://rack.rubyforge.net/">Rack</a>,
    but it's still not as accepted as WSGI.
  </p>
  <h3>Access To Internals</h3>
  <p>
    Python allows accessing many aspects of the interpreter core. Some of them
    are forwarded to python (frames via <tt>sys._getframe</tt> or tracebacks),
    tracebacks itself, a python compiler and parser (via the <tt>compiler</tt>
    package or the new <tt>_ast</tt> module). Some of them are only available
    via the C API. But that doesn't really matter since you can use
    <tt>ctypes.pythonapi</tt> to access the python C API. (Still, you don't
    really have to do that)
  </p>
  <h3>Conclusion</h3>
  <p>
    I hope you can now understand why I personally like Python more than ruby.
    But don't get me wrong. I like ruby too and I already wrote some libs for
    it and love to play with it. But for real applications I prefer Python.
  </p>
  <p>
    <strong>Disclaimer:</strong> I wrote this article not to tell anybody how
    great python is. I don't want to tell anybody how stuipd Ruby is. And I
    certainly don't want to convert any Ruby developer into a Python
    developer! The world isn't black and white and I'm pretty sure other
    people have different requirements and will love Ruby more than Python.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/why-i-still-choose-python</link>
      <guid>http://lucumr.pocoo.org/articles/why-i-still-choose-python</guid>
      <author>Armin Ronacher</author>
      <pubDate>Mon, 26 Mar 2007 14:03:00 GMT</pubDate>
    </item>
    <item>
      <title>Unicode in Rich Text Format</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  Today I wrote an <a href="http://trac.pocoo.org/browser/pygments/trunk/pygments/formatters/rtf.py">RTF Formatter</a>
  for <a href="http://pygments.pocoo.org/">pygments</a>. By doing this I
  not only found out that the most recent specification of RTF is basically
  just about Microsoft® Word® but also that Unicode is really tricky.
</p>
  
  <p>
    RTF is really one of the worst markup languages ever created. It looks like
    the human unreadable version of LaTeX and is heavily bound to Microsoft®
    Word®. Until I guess Microsoft® Word® 97 RTF just saved documents in ANSI
    charset. So. What the hell is an ANSI charset? I have no idea. Looks like
    ANSI is a mixin charset where each font definition can refer to a different
    codepage. In fact I don't mind because there is a way to embed unicode:
  </p>
  <pre>Binärcode</pre>
  <p>Looks like this in RTF:</p>
  <pre>Bin\ud{\u228\'e4}rcode</pre>
  <p>
    First you start the small adventure by opening a new block prefixed with
    the <tt>\ud</tt> keyword that let the RTF reader know that here starts an
    Unicode Part. The next one is the 16 bit signed integer number of the character
    code point in the unicode table. Yeah. Singed. And 16 bit long... So not even
    utf8 fits into what RTF thinks is unicode.
  </p>
  <p>
    Anyway. The next part after the unicode codepoint number is the ANSI
    codepoint number. Because I'm lazy in my example I just encoded that again
    into iso-8859-1. If the character isn't in ANSI it should use the closest
    possible character. (Just replace it with ? ^^)
  </p>
  <p>
    Check out the <a href="http://trac.pocoo.org/browser/pygments/trunk/pygments/formatters/rtf.py">module</a>
    for more information about the implementation if you like.
  </p>
  <p>
    And here some funny facts from the specification (which is btw a Microsoft®
    Word® document packed in a zip exe file which is packed in a cab extract
    exe file):
  </p>
  <blockquote>
    The hidden style property can only be accessed using Microsoft® Visual
    Basic® for Applications.
  </blockquote>
  <p>That's the footnote for the <tt>\shidden</tt> style control word</p>
  <blockquote><dl><dt><tt>\oldas</tt></dt>
  <dd>Use Word 95 Auto spacing</dd>
  <dt><tt>\lnbrkrule</tt></dt>
  <dd>Don’t use Word 97 line breaking rules for Asian text.</dd>
  <dt><tt>\bdrrlswsix</tt></dt>
  <dd>Use Word 6.0/Word 95 borders rules.</dd></blockquote>
  <p>
    Great huh? I'm looking forward to discover the differences in the spacing
    and text breaking rules between different Microsoft® Word® versions.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/unicode-in-rich-text-format</link>
      <guid>http://lucumr.pocoo.org/articles/unicode-in-rich-text-format</guid>
      <author>Armin Ronacher</author>
      <pubDate>Sat, 16 Dec 2006 21:32:00 GMT</pubDate>
    </item>
    <item>
      <title>Transfering Jabber Rosters</title>
      <description>
        <![CDATA[
        
  <p class="intro">
  After two hours of playing with ejabberd i found out that the new
  server was unable to read the ejabberd database from the old one.
  great -.- Because neither me nor Georg were able to fix that issue i
  wrote a script that dumps the account data from one jabber account so
  that you can import it into another one.
</p>
  
  <p>
    Here the code for dumping and restoring a roster. It requires that you
    have <a href="http://xmpppy.sourceforge.net/">xmpppy</a> installed
  </p>
<div class="highlight"><pre><span class="k">import</span> <span class="nn">sys</span>
<span class="k">from</span> <span class="nn">xmpp</span> <span class="k">import</span> <span class="n">JID</span><span class="p">,</span> <span class="n">Client</span>
<span class="k">from</span> <span class="nn">pickle</span> <span class="k">import</span> <span class="n">dump</span><span class="p">,</span> <span class="n">load</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">MODE</span><span class="p">,</span> <span class="n">FILE</span><span class="p">,</span> <span class="n">USERNAME</span><span class="p">,</span> <span class="n">PASSWORD</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:</span><span class="mf">5</span><span class="p">]</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;usage: </span><span class="si">%s</span><span class="s"> &lt;mode&gt; &lt;file&gt; &lt;username&gt; &lt;password&gt; </span><span class="si">% s</span><span class="s">ys.argv[0]</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>

<span class="n">jid</span> <span class="o">=</span> <span class="n">JID</span><span class="p">(</span><span class="n">USERNAME</span><span class="p">)</span>
<span class="n">cl</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">jid</span><span class="o">.</span><span class="n">getDomain</span><span class="p">(),</span> <span class="n">debug</span><span class="o">=</span><span class="p">[])</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">cl</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">cl</span><span class="o">.</span><span class="n">auth</span><span class="p">(</span><span class="n">jid</span><span class="o">.</span><span class="n">getNode</span><span class="p">(),</span> <span class="n">PASSWORD</span><span class="p">):</span>
    <span class="k">print</span> <span class="s">&#39;couldn not connect to server&#39;</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">cl</span><span class="o">.</span><span class="n">sendInitPresence</span><span class="p">()</span>
    <span class="n">roster</span> <span class="o">=</span> <span class="n">cl</span><span class="o">.</span><span class="n">getRoster</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">MODE</span> <span class="o">==</span> <span class="s">&#39;dump&#39;</span><span class="p">:</span>
        <span class="n">data</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">for</span> <span class="n">jid</span> <span class="ow">in</span> <span class="n">roster</span><span class="o">.</span><span class="n">getItems</span><span class="p">():</span>
            <span class="n">data</span><span class="p">[</span><span class="n">jid</span><span class="p">]</span> <span class="o">=</span> <span class="n">roster</span><span class="o">.</span><span class="n">getRawItem</span><span class="p">(</span><span class="n">jid</span><span class="p">)</span>
        <span class="n">f</span> <span class="o">=</span> <span class="nb">file</span><span class="p">(</span><span class="n">FILE</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
        <span class="n">dump</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
        <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">elif</span> <span class="n">MODE</span> <span class="o">==</span> <span class="s">&#39;load&#39;</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">jid</span><span class="p">,</span> <span class="n">data</span> <span class="ow">in</span> <span class="n">load</span><span class="p">(</span><span class="nb">file</span><span class="p">(</span><span class="n">FILE</span><span class="p">))</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
            <span class="n">roster</span><span class="o">.</span><span class="n">setItem</span><span class="p">(</span><span class="n">jid</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="s">&#39;name&#39;</span><span class="p">],</span> <span class="n">data</span><span class="p">[</span><span class="s">&#39;groups&#39;</span><span class="p">]</span> <span class="ow">or</span> <span class="p">[])</span>
            <span class="n">roster</span><span class="o">.</span><span class="n">Authorize</span><span class="p">(</span><span class="n">jid</span><span class="p">)</span>
            <span class="n">roster</span><span class="o">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">jid</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">&#39;error: mode must be load or dump&#39;</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>
</pre></div>

  <p>Use it like this:</p>
  <pre>python rosterdump.py dump roster.dump yourname@example.com yourpassword</pre>
  <p>And restore it using this command:</p>
  <pre>python rosterdump.py load roster.dump yourname@otherserver.com yournewpassword</pre>
  <p>
    Note that i won't further work on that script and it's possible that are some
    errors in the script. I don't guarantee that it actually works :D Nevertheless
    I hope it might be useful for you.
  </p>

  
        ]]>
      </description>
      <link>http://lucumr.pocoo.org/articles/transfering-jabber-rosters</link>
      <guid>http://lucumr.pocoo.org/articles/transfering-jabber-rosters</guid>
      <author>Armin Ronacher</author>
      <pubDate>Sun, 22 Oct 2006 12:23:00 GMT</pubDate>
    </item>
  </channel>
</rss>