<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><description /><title>connecting the dots . . .</title><generator>Tumblr (3.0; @mikeivanov)</generator><link>http://www.mikeivanov.com/</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/mikeivanov/VUvI" /><feedburner:info uri="mikeivanov/vuvi" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://tumblr.superfeedr.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item><title>Multimethods in Python</title><description>&lt;p&gt;So, &lt;a href="http://www.python.org/dev/peps/pep-0443/"&gt;PEP-443 aka Single-dispatch generic functions&lt;/a&gt; has made it into Python. There is a &lt;a href="http://lukasz.langa.pl/8/single-dispatch-generic-functions/"&gt;nice writeup&lt;/a&gt; of the &lt;code&gt;singledispatch&lt;/code&gt; package features by &lt;a href="http://lukasz.langa.pl"&gt;Łukasz Langa&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Although I&amp;#8217;m glad that Python is evolving in the right direction, I can&amp;#8217;t see how single dispatch alone could be enough. In essence, PEP-443 defines a way of dynamically extending existing types with externally defined generic functions. Which is nice, of course, but too limited.&lt;/p&gt;

&lt;p&gt;What is &lt;em&gt;really&lt;/em&gt; interesting is &lt;a href="http://en.wikipedia.org/wiki/Multiple_dispatch"&gt;multiple dispatch&lt;/a&gt;. There are a few packages bringing multimethods to Python; all of them are overcomplicated to my taste.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s my take on it. I will not talk much, better show you the code.&lt;/p&gt;

&lt;p&gt;This is the complete implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# multidispatch.py

import operator
from collections import OrderedDict

class DuplicateCondition(Exception): pass

class NoMatchingMethod(Exception): pass

class defmulti(object):
    def __init__(self, predicate):
        self.registry = OrderedDict()
        self.predicate = predicate

    def __call__(self, *args, **kw):
        method = self.dispatch(*args, **kw)
        return method(*args, **kw)

    def dispatch(self, *args, **kw):
        for condition, method in self.registry.items():
            if self.predicate(condition, *args, **kw):
                return method
        return self.notfound

    def notfound(self, *args, **kw):
        raise NoMatchingMethod()

    def when(self, condition):
        if condition in self.registry:
            raise DuplicateCondition()
        def deco(fn):
            self.registry[condition] = fn
            return fn
        return deco

    def default(self, fn):
        self.notfound = fn
        return fn

    @classmethod
    def typedispatch(cls):
        return cls(lambda type, first, *rest, **kw: isinstance(first, type))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here&amp;#8217;s how to use it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import types
from multidispatch import defmulti, NoMatchingMethod

# Exhibit A: Dispatch on the type of the first parameter.
#            Equivalent to `singledispatch`.

cupcakes = defmulti.typedispatch()

@cupcakes.when(types.StringType)
def str_cupcakes(ingredient):
    return "Delicious {0} cupcakes".format(ingredient)

@cupcakes.when(types.IntType)
def int_cupcakes(number):
    return "Integer cupcakes, anyone? I've got {0} of them.".format(number)

@cupcakes.default
def any_cupcakes(thing):
    return ("You can make cupcakes out of ANYTHING! "
            "Even out of {0}!").format(thing)

print cupcakes("bacon")
print cupcakes(4)
print cupcakes(cupcakes)


# Exhibit B: dispatch on the number of args, no default

@defmulti
def jolly(num, *args):
    return len(args) == num

@jolly.when(1)
def single(a):
    return "For {0}'s a jolly old fellow!".format(a)

@jolly.when(2)
def couple(a, b):
    return "{0} and {1} are such a jolly couple!".format(a, b)

print jolly("Lukasz")
print jolly("Fish", "Chips")
try:
    jolly("Good", "Bad", "Ugly")
except NoMatchingMethod:
    print "Noo! Angel Eyes!"
&lt;/code&gt;&lt;/pre&gt;</description><link>http://www.mikeivanov.com/post/52352972836</link><guid>http://www.mikeivanov.com/post/52352972836</guid><pubDate>Thu, 06 Jun 2013 23:23:00 -0400</pubDate><category>python</category><category>multimethods</category><category>pep</category></item><item><title>I will never CNAME my root domain again.

I will never CNAME my root domain again.

I will never...</title><description>&lt;p&gt;I will never CNAME my root domain again.&lt;/p&gt;

&lt;p&gt;I will never CNAME my root domain again.&lt;/p&gt;

&lt;p&gt;I will never CNAME my root domain again.&lt;/p&gt;

&lt;p&gt;NEVER. EVER.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/48254796819</link><guid>http://www.mikeivanov.com/post/48254796819</guid><pubDate>Wed, 17 Apr 2013 23:43:29 -0400</pubDate><category>i-am-so-sorry</category></item><item><title>Hello Tumblr</title><description>&lt;p&gt;Good bye, Posterous. Rest in peace.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/47920167164</link><guid>http://www.mikeivanov.com/post/47920167164</guid><pubDate>Sat, 13 Apr 2013 23:04:32 -0400</pubDate><category>blog</category></item><item><title>A simple callback chain macro for elisp</title><description>&lt;h3&gt;The Problem&lt;/h3&gt;

&lt;p&gt;As usual, it started with a tiny piece of ugly code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(bd-create-stage datafile-id
                 (lambda (stage-id)
                   (bd-insert-rows stage-id 
                                   [[10 20 30] [40 50 60]]
                                   (lambda (stage-id)
                                     (bd-commit-stage stage-id 
                                                      #'ignore)))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The snippet above is basically a callback chain. When &lt;code&gt;bd-create-stage&lt;/code&gt;
finishes its work, it calls the first lambda, which calls
&lt;code&gt;bd-insert-rows&lt;/code&gt; with the second lambda as its callback argument and so
on, until it all stops at the ignore function.&lt;/p&gt;

&lt;p&gt;I wanted to rewrite it as something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(=&amp;gt; datafile-id
    (bd-create-stage it next)
    (bd-insert-rows  it [[1 2 3 4 5] [6 7 8 9 0]] next)
    (bd-commit-stage it next))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where the &lt;code&gt;it&lt;/code&gt; variable would represent the current callback&amp;#8217;s
parameter and next would refer to the next callback in the chain. As
with the
&lt;a href="http://www.mikeivanov.com/thread-operator-in-elisp"&gt;&lt;code&gt;-&amp;gt;&lt;/code&gt; macro&lt;/a&gt;, I
wanted explicit anaphoric variables.&lt;/p&gt;

&lt;h3&gt;The Idea&lt;/h3&gt;

&lt;p&gt;Each line in the snippet above could be wrapped in a lambda, lust like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(=&amp;gt; datafile-id
    (lambda (next it)
      (bd-create-stage it next))
    (lambda (next it)
      (bd-insert-rows it [[1 2 3 4 5] [6 7 8 9 0]] next)
    (lambda (next it)
      (bd-commit-stage it next))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then it should somehow call each function in the list with the
consequent function as the first parameter and the result of execution
of the previous function as the second parameter.&lt;/p&gt;

&lt;h3&gt;The Solution&lt;/h3&gt;

&lt;p&gt;This function chaining thing looks a lot like a binary function fold:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun chain2 (f1 f2)
  (apply-partially f1 f2))

(defun chain (&amp;amp;amp;rest fns)
  (if fns
      (reduce #'chain2 fns :from-end t)
    #'identity))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Applying &lt;code&gt;chain&lt;/code&gt; to a function list creates a new function taking one
parameter and passing it through the whole function list, much like
the &lt;code&gt;-&amp;gt;&lt;/code&gt; macro does.&lt;/p&gt;

&lt;p&gt;In fact, this is enough to start working on the macro.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defmacro =&amp;gt; (initial &amp;amp;amp;rest forms)
  `(funcall ,(build-form-chain forms) ,initial))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;build-form-chain&lt;/code&gt; function wraps each form into a lambda and then
chains them together:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun build-form-chain (forms)
  `(apply #'chain 
          (list ,@(mapcar #'build-form-link forms) #'ignore)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At the end it adds &lt;code&gt;ignore&lt;/code&gt; as a terminator. The terminator is necessary
because the last callback&amp;#8217;s result is almost always ignored.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;build-form-link&lt;/code&gt;&amp;#8217;s implementation is trivial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun build-form-link (form)
  `(lambda (next it) ,form))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Done! Here&amp;#8217;s the full source for your convenience:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun chain2 (f1 f2)
  (apply-partially f1 f2))

(defun chain (&amp;amp;rest fns)
  (if fns
      (reduce #'chain2 fns :from-end t)
    #'identity))

(defun build-form-link (form)
  `(lambda (next it) ,form))

(defun build-form-chain (forms)
  `(apply #'chain 
          (list ,@(mapcar #'build-form-link forms) #'ignore)))

(defmacro =&amp;gt; (initial &amp;amp;rest forms)
  `(funcall ,(build-form-chain forms) ,initial))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let&amp;#8217;s see how the macro expands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ELISP&amp;gt; (macroexpand
     '(=&amp;gt; datafile-id
          (bd-create-stage it next)
          (bd-insert-rows  it [[1 2 3 4 5] [6 7 8 9 0]] next)
          (bd-commit-stage it next)))

(funcall (apply (function chain) 
                (list (lambda (next it) 
                        (bd-create-stage it next))
                      (lambda (next it)
                        (bd-insert-rows it [[1 2 3 4 5] [6 7 8 9 0]] next))
                      (lambda (next it)
                        (bd-commit-stage it next))
                      (function ignore)))
          datafile-id)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Exactly as intended.&lt;/p&gt;

&lt;p&gt;This macro covers 95% of my callback chaining needs. For the rest 5%
there is the all-powerful &lt;a href="https://github.com/kiwanami/emacs-deferred"&gt;deferred.el&lt;/a&gt;
library.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/47902599658</link><guid>http://www.mikeivanov.com/post/47902599658</guid><pubDate>Wed, 06 Jun 2012 00:00:00 -0400</pubDate><category>lisp</category><category>emacs</category></item><item><title>Thread operator in Elisp</title><description>&lt;h3&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;ELISP&amp;gt; (-&amp;gt; 1
           (+ 2 it)
           (* 3 it))
9
ELISP&amp;gt; (macroexpand
           '(-&amp;gt; 1
                (+ 2 it)
                (* 3 it)))
(let* ((it 1) (it (+ 2 it)) (it (* 3 it))) it)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defmacro -&amp;gt; (arg &amp;amp;rest forms)
  `(let* ((it ,arg) .
      ,(mapcar (lambda (form) `(it ,form))
           forms))
     it))
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;&lt;strong&gt;The Long Story&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;When I see code like this, I frown:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun bd-search (api-key query callback)
  (send-request "GET"
            (format "search?%s"
                (make-query-string `(("api_key" . ,api-key)
                             ("query" . ,query))))
        callback))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;#8217;s a very simple case, yet the parameter list is already at the fourth level of indentation. When it gets really ugly I usually wrap the whole thing into a let statement and start moving inner parts into variables.&lt;/p&gt;

&lt;p&gt;What I have noticed, however, is that almost always constructs like this are sequential by their nature, in other words the output of the innermost statement serves as input for the statement one level up, and so on and so forth. This is the very reason why Clojure had its &lt;a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/-&amp;gt;"&gt;thread operator macro&lt;/a&gt; since beginning.&lt;/p&gt;

&lt;p&gt;Remembering that, I started literally morphing my &lt;code&gt;bd-search&lt;/code&gt; function into something more prettier. I came up with this variant:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (-&amp;gt; `(("api_key" . ,api-key)
    ("query" . ,query))
      (make-query-string it)
      (format "search?%s" it)
      (send-request "GET" it callback)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then I put together the -&amp;gt; macro and that was it.&lt;/p&gt;

&lt;p&gt;I decided to make the macro &lt;a href="http://www.bookshelf.jp/texi/onlisp/onlisp_15.html"&gt;anaphoric&lt;/a&gt; instead of implicitly injecting an extra parameter as in Clojure. This allowed me to put the threaded parameter at any place, not just at the beginning or at the end of the parameter list.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/47901990033</link><guid>http://www.mikeivanov.com/post/47901990033</guid><pubDate>Wed, 09 May 2012 00:00:00 -0400</pubDate><category>lisp</category><category>emacs</category><category>clojure</category></item><item><title>How much can be done in four hours</title><description>&lt;p&gt;Today I had an awesome day at the first OpenDataBC hackathon which took place at Mozilla Labs Vancouver.&lt;/p&gt;

&lt;p&gt;Tara Gibbs pitched this wonderful idea of consolidating shelter availability data and displaying it on a few window displays, so the homeless people living DTES would not waste their time going from one shelter to another just to find a free spot.&lt;/p&gt;

&lt;p&gt;This doesn&amp;#8217;t solve all the problems of course, but it does solve a little yet very annoying one.&lt;/p&gt;

&lt;p&gt;So&amp;#8230; At 11:30 we had nothing but an idea. We discussed possible approaches for a while, then came David Eaves and suggested using Twitter as a message queue service.&lt;/p&gt;

&lt;p&gt;At approximately 12:00 we still had nothing but a piece of paper covered with boxes and arrows, then we started coding. Tara did the frontend, I was busy hacking the backend and the Twitter stuff.&lt;/p&gt;

&lt;p&gt;Four hours later we had a fully functional, production ready system - &lt;a href="https://github.com/mikeivanov/vanshelter"&gt;https://github.com/mikeivanov/vanshelter&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How it is supposed to work:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Shelters tweet their availability data (they all have internet access)&lt;/li&gt;
&lt;li&gt;VanShelter monitors &amp;#8212; each of them independently &amp;#8212; receive Twitter updates and&lt;/li&gt;
&lt;li&gt;Refresh their displays when something changes.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;For displays we can use cheap LCD monitors, probably even donated.  The software will run on those amazing Raspberry thingies - &lt;a href="http://www.raspberrypi.org/,"&gt;http://www.raspberrypi.org/,&lt;/a&gt; $25 each. This brings the full cost of installing 10 displays down to $250+.&lt;/p&gt;

&lt;p&gt;Thank you Tara and David. Also, thank you Jeff and all the people who made this hackathon possible.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/47901446886</link><guid>http://www.mikeivanov.com/post/47901446886</guid><pubDate>Sat, 27 Aug 2011 00:00:00 -0400</pubDate><category>python</category><category>shelter</category><category>dtes</category><category>data</category></item><item><title>Pure Python Paillier Homomorphic Cryptosystem Implementation</title><description>&lt;h3&gt;&lt;strong&gt;What&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;This is a very basic &lt;a href="http://en.wikipedia.org/wiki/Paillier_cryptosystem"&gt;Paillier Homomorphic Cryptosystem&lt;/a&gt; implemented in pure Python.&lt;/p&gt;

&lt;p&gt;The idea is, in short, to encrypt two numbers, perform an &amp;#8220;add&amp;#8221; operation on cyphertexts, decrypt the result and find it to be the sum of the original plaintext numbers.&lt;/p&gt;

&lt;h3&gt;&lt;strong&gt;How&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;The code is loosely based on the &lt;a href="http://en.wikipedia.org/wiki/Paillier_cryptosystem"&gt;thep&lt;/a&gt; project and a few &lt;a href="http://code.activestate.com/recipes/"&gt;ActiveState recipes&lt;/a&gt;. The code is pure Python and all objects are serializable.&lt;/p&gt;

&lt;h3&gt;&lt;strong&gt;Where&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;Here: &lt;a href="https://github.com/mikeivanov/paillier"&gt;https://github.com/mikeivanov/paillier&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;&lt;strong&gt;Why&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;I was bored.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/47901014668</link><guid>http://www.mikeivanov.com/post/47901014668</guid><pubDate>Tue, 28 Jun 2011 00:00:00 -0400</pubDate><category>python</category><category>crypto</category></item><item><title>How to mount an NTFS-formatted USB drive in read-write mode on Mac OS X</title><description>&lt;p&gt;Actually, it&amp;#8217;s very easy. No additional software is required. Just seven easy steps:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Attach your USB drive&lt;/li&gt;
&lt;li&gt;Open the Terminal app (Command-Space, then type &amp;#8220;Terminal&amp;#8221;, hit Enter)&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Type or copy/paste these commands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo sh -c "mkdir -p /mnt \
$(mount | grep ntfs | head -n 1 \
   | awk '{ print "&amp;amp;&amp;amp; umount " $3 \
               " &amp;amp;&amp;amp; mount_ntfs -o nosuid,rw " $1 " /mnt" }')"
&lt;/code&gt;&lt;/pre&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Locate your drive in Finder&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;Drag/drop files there&lt;/li&gt;
&lt;li&gt;Unmount the drive as usual&lt;/li&gt;
&lt;li&gt;DONE!&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;The command breakdown, if you&amp;#8217;re interested:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;mkdir -p /mnt&lt;/code&gt; creates a mount point &amp;#8212; a place in the file system where the drive is going to be attached&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;mount&lt;/code&gt; command without parameters gives you a list of the currently attached drives&lt;/li&gt;
&lt;li&gt;&lt;code&gt;grep ntfs&lt;/code&gt; filters non-ntfs drives out the list&lt;/li&gt;
&lt;li&gt;&lt;code&gt;head -n 1&lt;/code&gt; grabs the first line (we&amp;#8217;re assuming only one ntfs drive can be attached at a time)&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;awk&lt;/code&gt; part produces two commands:

&lt;ul&gt;&lt;li&gt;&lt;code&gt;umount /Volumes/&lt;/code&gt; &amp;#8212; unmounts the drive from its original place&lt;/li&gt;
&lt;li&gt;&lt;code&gt;mount_ntfs -o nosuid,rw /dev/ /mnt&lt;/code&gt; &amp;#8212; mounts the drive again, but this time in the read-write mode&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Now, the &lt;code&gt;sudo sh -c "..."&lt;/code&gt; thing allows code execution with superuser privileges.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;That&amp;#8217;s it.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/45894951347</link><guid>http://www.mikeivanov.com/post/45894951347</guid><pubDate>Thu, 09 Jun 2011 00:00:00 -0400</pubDate><category>ntfs</category><category>mac</category><category>terminal</category><category>usb</category></item><item><title>Tail recursion without TCO</title><description>&lt;p&gt;Emacs lisp has no Tail Call Optimization (TCO), neither do many other
lisp dialects. The lack of TCO is not a big deal&amp;#8212;it&amp;#8217;s always possible
to transform a tail recursive algorithm into a loop. However, it makes
functions look uglier. Here is a very simple method of enabling
Clojure-style tail call recursion in Emacs lisp:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;;; A very simple linearized Y combinator.
;; All the state management stuff is incapsulated here.
;; Don't call it directly.
(defun rloop- (body &amp;amp;rest args)
  (let ((res nil))
    (while (progn
             ;; here's the idea: we keep calling body 
             ;; while it returns the recursion marker
             (setq res (apply body args))
             (when (and (consp res)
                        (eq :loop-recur-marker (car res)))
               (progn (setq args (cdr res))
                      t))))
    res))

;; Recursion marker factory
(defun recur (&amp;amp;rest args)
  ;; instead of a real recursive call,
  ;; just signal an intention to make one
  (cons :loop-recur-marker args))

;; The form macro
(defmacro rloop (init body)
  (let ((args (mapcar 'car init)))
    ;; a little courtesy to the macro users
    `(let* ,init
       ;; make a lambda from the body and pass it 
       ;; to the combinator function
       (rloop- (function (lambda (,@args) ,body))
               ,@args))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here&amp;#8217;s how to use it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun factorial (x)
  ;; this is the recursion entry point
  (rloop ((x   x) 
          (acc 1))
         (if (&amp;lt; x 1)
             acc ;; done, just return the result
           ;; not done, start the whole rloop block again
           (recur (1- x) 
                  (* x acc)))))

ELISP&amp;gt; (factorial 10)
3628800
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The funny part is defun is not necessary. You can have as many
sequential inlined rloops as you want. I like this approach: all the
state management stuff is off the sight. The function code is almost
identical to the underlying algorithm. Another classic example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defun fibo (x)
  (rloop ((x    x)
          (curr 0)
          (next 1))
         (if (= x 0)
             curr
           (recur (1- x) 
                   next 
                  (+ curr next)))))

ELISP&amp;gt; (fibo 10)
55
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nice, eh? Of course, this kind of beauty comes with a price. Here is
how the rloop macro expands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ELISP&amp;gt; (macroexpand '(rloop ((n 0)) (if (&amp;gt; n 5) n (recur (1+ n)))))

(let*
    ((n 0))
  (rloop-
   #'(lambda
       (n)
       (if
           (&amp;gt; n 5)
           n
         (recur
          (1+ n))))
   n))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&amp;#8230;which means two extra function calls on each iteration. But
realistically, it&amp;#8217;s not such a big deal. Clarity of the code is way
more important.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/44952159596</link><guid>http://www.mikeivanov.com/post/44952159596</guid><pubDate>Fri, 20 Aug 2010 00:00:00 -0400</pubDate><category>emacs</category><category>lisp</category><category>clojure</category><category>tco</category></item><item><title>Clouds and entropy</title><description>&lt;p&gt;In a post titled &lt;a href="http://www.elasticvapor.com/2009/08/trusted-cloud-entropy-authority.html"&gt;A Trusted Cloud Entropy Authority&lt;/a&gt; Reuven Cohen writes:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;#8230;maybe there an opportunity to create a trusted cloud authority to 
  provide signed verified and certified entropy. Think of it like a certificate 
  authority (CA) but for chaos. Actually, Amazon Web Service itself could 
  act as this entropy authority via a simple encrypted web service call. I 
  even have a name for it, Simple Entropy Service (SES).&amp;#8221;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is really a good idea. Amazon should have provided such a service long time ago.&lt;/p&gt;

&lt;p&gt;When an SSL connection is being established, a browser and a server perform the Handshake protocol. This protocol involves exchanging random bits between the parties. The important thing is that security depends on how random those bits are. If they are not, the connection is effectively insecure.&lt;/p&gt;

&lt;p&gt;In the case of AWS, there is no source of true randomness, therefore SSL on AWS is inherently insecure. Moreover, instances running on the same physical machine can affect each other&amp;#8217;s security by draining the shared random pool in the host system.&lt;/p&gt;

&lt;p&gt;Further he writes:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;a website called &lt;a href="http://random.org"&gt;http://random.org&lt;/a&gt; [is] a true random number service 
  that generates randomness via atmospheric noise. Looks cool, maybe 
  this may help solve the problem.&amp;#8221;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I don&amp;#8217;t think that random.org is a good choice.&lt;/p&gt;

&lt;p&gt;One problem is a connection to such a service. It should be as secure as the most secure secret handled on your system. If the random bit connection is encrypted with 256 bit AES (and it actually is), this is the highest level of security your system can provide. Plus, there should be guarantee that no unencryped random bits are stored anywhere. The same is true for the proposed SAS service, too.&lt;/p&gt;

&lt;p&gt;Another problem with random.org is&amp;#8230; well, randomness is perceptive. What you see as &amp;#8220;random&amp;#8221; can be quite deterministic to the people who run the random.org service. Even though they might not store anything, their present is your future&amp;#8212;just think about relativistic effects. A temptation to tamper with someone&amp;#8217;s future can be, you know, very strong.&lt;/p&gt;

&lt;p&gt;The overall quality of the service is not known. There is no guarantee it is random at all. A quote from their FAQ: &amp;#8220;Q1.2: Is the source code for the generator available? &amp;#8212; Not currently, no. Maybe I&amp;#8217;ll make it available as open source some day.&amp;#8221;&lt;/p&gt;

&lt;p&gt;Even though the Whois database indicates the domain name&amp;#8217;s registrant is located in France, the SSL certificate owner is not specified. I have no reasons for not believing the guy running the service, but I would not entrust my customers&amp;#8217; data into a total stranger&amp;#8217;s hands, even though he or she seems to be a nice person.&lt;/p&gt;

&lt;p&gt;So the conclusion is: while there is no trusted entropy generator on the AWS side, we, the AWS customers, are on our own.&lt;/p&gt;

&lt;p&gt;Here is a hint: entropy seeds can be generated in-house and smuggled into instances over a secure channel. Then those seeds could be fed to a cryptographically secure RNG like &lt;a href="http://www.burtleburtle.net/bob/rand/isaacafa.html"&gt;Isaac&lt;/a&gt; to produce actual &amp;#8220;random&amp;#8221; bits. I think there should be a way of injecting those into the instance&amp;#8217;s random pool.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/45894023169</link><guid>http://www.mikeivanov.com/post/45894023169</guid><pubDate>Tue, 06 Apr 2010 00:00:00 -0400</pubDate><category>amazon</category><category>cloud</category><category>crypto</category><category>ssl</category><category>random</category></item><item><title>Dynamic queries: the Postgres way</title><description>&lt;p&gt;Have you ever been in a situation when you needed a query to be
generated and executed dynamically as a result of another query?&lt;/p&gt;

&lt;p&gt;If yes, read further: there is a simple and elegant way to achieve
that.&lt;/p&gt;

&lt;p&gt;First, create this function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE OR REPLACE FUNCTION dselect(varchar)
  RETURNS SETOF record AS $$
    DECLARE rec record;
    BEGIN
      FOR rec IN EXECUTE $1 LOOP
        RETURN NEXT rec;
      END LOOP;
    END
  $$ LANGUAGE 'plpgsql';
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Second, umm.. well, that&amp;#8217;s it.&lt;/p&gt;

&lt;p&gt;Anything you pass as a parameter will be interpreted and executed as
an SQL statement.&lt;/p&gt;

&lt;p&gt;The function is SELECT-able. That is, you can use it in SELECTs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM dselect('SELECT id, name FROM users') AS t(id int, name varchar);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the &lt;code&gt;AS t(id int, name varchar)&lt;/code&gt; part. Postgres has no idea about
what this function returns, so a column definition list should be
provided. If not, Postgres will complain:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM dselect('SELECT id, name FROM users');
ERROR:  a column definition list is required for functions returning "record"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, the column definition list depends on the query and should
match the actual query results.&lt;/p&gt;

&lt;p&gt;So why this function is needed at all?&lt;/p&gt;

&lt;p&gt;Because of situations like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE SCHEMA sc_foo;
CREATE TABLE sc_foo.activity (date date, descr text);
INSERT INTO sc_foo.activity (date, descr) VALUES ('2009-08-07', 'went there');
INSERT INTO sc_foo.activity (date, descr) VALUES ('2009-06-04', 'hanging around');

CREATE SCHEMA sc_bar;
CREATE TABLE sc_bar.activity (date date, descr text);
INSERT INTO sc_bar.activity (date, descr) VALUES ('2009-10-11', 'came here');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It allows you to do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT 
    nspname 
FROM
    pg_namespace 
WHERE
    nspname LIKE 'sc_%'  AND
    (SELECT date FROM 
        dselect('SELECT max(date) FROM ' || nspname || '.activity') AS t(date date)) &amp;amp;lt; '2009-09-09';

 nspname 
---------
 sc_bar
(1 row)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In one pass this query goes over all the schemas whose names start
with &lt;code&gt;sc_&lt;/code&gt;, grabs the latest date from the schema&amp;#8217;s activity tables
and matches the result against the provided date.&lt;/p&gt;

&lt;p&gt;Of course, this approach is quite ineffective. Each time the function
is called, a query is parsed and executed using a separate plan. A
simple UNION of two queries would do the same, but&amp;#8230; what if there
are ten schemas? How about a hundred? I&amp;#8217;m actually working with a
database containing thousands of them.&lt;/p&gt;

&lt;p&gt;I use this function when I need to collect statistics or do some db
administration tasks, it saves me a lot of time.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/44950520359</link><guid>http://www.mikeivanov.com/post/44950520359</guid><pubDate>Fri, 17 Jul 2009 13:00:00 -0400</pubDate><category>postgres</category><category>sql</category></item><item><title>Why Tk matters</title><description>&lt;p&gt;Tk probably is one of the most underlooked GUI toolkits. It is a nice small toolkit which is really, I mean REALLY simple to use.&lt;/p&gt;

&lt;p&gt;Tk by the way, has something common with Vi. Oh no, it&amp;#8217;s not that it beeps all the time; I meant that it works everywhere. I bet you can find Tk ported to any single platform having a GUI and it will work consistently on all of them.&lt;/p&gt;

&lt;p&gt;Tk is ubiquitous. Guess what? Almost certainly you have Tk already installed on your computer. Got Python? Go look into /usr/lib/python2.5/lib-tk, it&amp;#8217;s right there!&lt;/p&gt;

&lt;p&gt;Using it is very easy. Here is a &amp;#8216;Hello, world&amp;#8217; program in Python (using Tk bindings called Tkinter):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from Tkinter import *
Label(text='Hi there').pack()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Expectedly, this program pops up a window with some text inside. Yes, it&amp;#8217;s that simple. And this is the area where Tk shines: quick, small GUI tools.&lt;/p&gt;

&lt;p&gt;Yet Tk is very powerful. People create big, sophisticated systems using just this toolkit. The most prominent example is definitely &lt;a href="http://www.inivis.com/"&gt;AC3D&lt;/a&gt;, a 3D modeling program.&lt;/p&gt;

&lt;p&gt;Tk, however, has some issues. I think nobody will argue that Tk looks ugly on the Linux platform. While the Windows and Mac versions got the native look, the Linux port looks unattractive. Some work is being done in this department but it&amp;#8217;s not quite completed.&lt;/p&gt;

&lt;p&gt;Somebody might ask why use Tk if there is wxPython. Well, for the same reason why there are bicycles and airplanes. They are good for different purposes. Tk is way more lightweight and much easier to learn and use than wxPython.&lt;/p&gt;

&lt;p&gt;Tk is very well documented. Here is the official Tkinter documentation with links to tutorials and such: &lt;a href="http://docs.python.org/library/tkinter.html"&gt;http://docs.python.org/library/tkinter.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you&amp;#8217;re going to learn Tk, it&amp;#8217;s worth to mention that Tk is actually a part of something called &lt;a href="http://tcl.tk"&gt;Tcl/Tk&lt;/a&gt;. Tcl stands for Tool Command Language, a Shell-like scripting language easy to learn and fun to use. Even though all you want might be just Tkinter, some knowledge of Tcl will be rewarding.&lt;/p&gt;</description><link>http://www.mikeivanov.com/post/1052071152</link><guid>http://www.mikeivanov.com/post/1052071152</guid><pubDate>Wed, 17 Dec 2008 13:00:00 -0500</pubDate><category>tk</category><category>tcl</category><category>python</category><category>tkinter</category></item></channel></rss>
