<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Average Blog</title>
    <link href="http://www.average.org/blog//atom.xml" rel="self" />
    <link href="http://www.average.org/blog/" />
    <id>http://www.average.org/blog//atom.xml</id>
    <author>
        <name>Eugene Crosser</name>
        <email>crosser@average.org</email>
    </author>
    <updated>2014-04-25T12:00:00Z</updated>
    <entry>
    <title>FizzBuzz with Composition. In C.</title>
    <link href="http://www.average.org/blog//2014/04/25/fizzbuzz-with-continuations/index.html" />
    <id>http://www.average.org/blog//2014/04/25/fizzbuzz-with-continuations/index.html</id>
    <published>2014-04-25T12:00:00Z</published>
    <updated>2014-04-25T12:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Just for the heck of it. Nothing fancy, aside from mild cognitive dissonance.</p>
<p><strong>Correction:</strong> The result was of course closer to <em>composition</em> than to <em>continuations</em>, as was pointed out to me by a colleague.</p>
<pre class="sourceCode C"><code class="sourceCode c"><span class="ot">#include &lt;stdio.h&gt;</span>
<span class="ot">#include &lt;string.h&gt;</span>

<span class="co">/* Copyright (c) 2014 Eugene Crosser.                                      */</span>
<span class="co">/* License: CC0 (http://creativecommons.org/choose/zero/)                  */</span>

<span class="co">/* Toungue in cheek &quot;continuation passing&quot; implementation of FizzBuzz      */</span>
<span class="co">/* Inspired by this:                                                       */</span>
<span class="co">/* http://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf          */</span>

<span class="co">/* With Strings and garbage collection we would have used strings objects. */</span>
<span class="co">/* As we don&#39;t want to muddle the code with memory managenemt, we just use */</span>
<span class="co">/* static buffers here. Make them long enogh for the longest output.       */</span>
<span class="kw">typedef</span> <span class="kw">struct</span> {
	<span class="dt">char</span> value[<span class="dv">16</span>];
	<span class="dt">char</span> dflt[<span class="dv">16</span>];
} fbstate_t;

fbstate_t test(<span class="dt">int</span> what, <span class="dt">int</span> against, <span class="dt">char</span> *v, fbstate_t ost) {
	fbstate_t nst;

	<span class="kw">if</span> (what % against == <span class="dv">0</span>) {
		strncpy(nst.value, v, <span class="kw">sizeof</span>(nst.value));
		strncat(nst.value, ost.value, <span class="kw">sizeof</span>(nst.value));
		nst.dflt[<span class="dv">0</span>] = &#39;\<span class="dv">0</span>&#39;;
	} <span class="kw">else</span> {
		nst = ost;
	}
	<span class="kw">return</span> nst;
}

fbstate_t dflt(<span class="dt">int</span> what) {
	fbstate_t nst;

	nst.value[<span class="dv">0</span>] = &#39;\<span class="dv">0</span>&#39;;
	snprintf(nst.dflt, <span class="kw">sizeof</span>(nst.dflt), <span class="st">&quot;%d&quot;</span>, what);
	<span class="kw">return</span> nst;
}

fbstate_t final(fbstate_t ost) {
	fbstate_t nst;

	strncat(nst.value, nst.dflt, <span class="kw">sizeof</span>(nst.value));
	nst.dflt[<span class="dv">0</span>] = &#39;\<span class="dv">0</span>&#39;;
	<span class="kw">return</span> nst;
}

fbstate_t run(<span class="dt">int</span> what) {
	<span class="kw">return</span> final(
		test(what, <span class="dv">3</span>, <span class="st">&quot;Fizz&quot;</span>,
		  test(what, <span class="dv">5</span>, <span class="st">&quot;Buzz&quot;</span>,
		    dflt(what))));
}

<span class="dt">int</span> main(<span class="dt">int</span> argc, <span class="dt">char</span> *argv[]) {
	<span class="dt">int</span> i;

	<span class="kw">for</span> (i = <span class="dv">1</span>; i &lt;= <span class="dv">100</span>; i++) {
		fbstate_t st = run(i);
		printf(<span class="st">&quot;%s</span><span class="ch">\n</span><span class="st">&quot;</span>, st.value);
	}
	<span class="kw">return</span> <span class="dv">0</span>;
}</code></pre>]]></summary>
</entry>
<entry>
    <title>Migrating to Hakyll</title>
    <link href="http://www.average.org/blog//2013/08/03/migrating-to-hakyll/index.html" />
    <id>http://www.average.org/blog//2013/08/03/migrating-to-hakyll/index.html</id>
    <published>2013-08-03T14:10:00Z</published>
    <updated>2013-08-03T14:10:00Z</updated>
    <summary type="html"><![CDATA[<p>I tend to generally prefer static content on the web when possible, so wordpress was a source of irritation for me for some time. After moving the site to a different hosting provider, I decided that it’s time for a cleanup. <a href="http://jaspervdj.be/hakyll/">Hakyll</a> seemed to tick the right checkboxes, and offered another opportunity to play with haskell.</p>
<p>After some fiddling with <a href="https://github.com/thomasf/exitwp">exitwp</a>, I noticed <a href="https://github.com/mloskot/exitwp">this fork</a> which addressed hackyll’s specific idiosyncrasy to the tag names containing underscore, and allowed to preserve the document tree structure that I had for my permalinks (it was my goal to preserve permalinks).</p>
<p>This is what I came up with by now:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">{-# LANGUAGE OverloadedStrings #-}</span>
<span class="kw">import</span>           Data.Monoid (mappend)
<span class="kw">import</span>           Hakyll


<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span> hakyll <span class="fu">$</span> <span class="kw">do</span>
    match <span class="st">&quot;images/*&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
        route   idRoute
        compile copyFileCompiler

    match <span class="st">&quot;css/*&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
        route   idRoute
        compile compressCssCompiler

    match <span class="st">&quot;about/index.markdown&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
        route   <span class="fu">$</span> constRoute <span class="st">&quot;about.html&quot;</span>
        compile <span class="fu">$</span> pandocCompiler
            <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/default.html&quot;</span> defaultContext
            <span class="fu">&gt;&gt;=</span> relativizeUrls

    match <span class="st">&quot;posts/*/*/*/*&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
        route <span class="fu">$</span> gsubRoute <span class="st">&quot;posts/&quot;</span> (<span class="fu">const</span> <span class="st">&quot;&quot;</span>) <span class="ot">`composeRoutes`</span>
                gsubRoute <span class="st">&quot;.markdown&quot;</span> (<span class="fu">const</span> <span class="st">&quot;/index.html&quot;</span>)
        compile <span class="fu">$</span> pandocCompiler
            <span class="fu">&gt;&gt;=</span> saveSnapshot <span class="st">&quot;content&quot;</span>
            <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/post.html&quot;</span>    postCtx
            <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/default.html&quot;</span> postCtx
            <span class="fu">&gt;&gt;=</span> relativizeUrls

    create [<span class="st">&quot;archive.html&quot;</span>] <span class="fu">$</span> <span class="kw">do</span>
        route idRoute
        compile <span class="fu">$</span> <span class="kw">do</span>
            <span class="kw">let</span> archiveCtx <span class="fu">=</span>
                    field <span class="st">&quot;posts&quot;</span> (\_ <span class="ot">-&gt;</span> postList recentFirst) <span class="ot">`mappend`</span>
                    constField <span class="st">&quot;title&quot;</span> <span class="st">&quot;Archives&quot;</span>              <span class="ot">`mappend`</span>
                    defaultContext

            makeItem <span class="st">&quot;&quot;</span>
                <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/archive.html&quot;</span> archiveCtx
                <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/default.html&quot;</span> archiveCtx
                <span class="fu">&gt;&gt;=</span> relativizeUrls
                <span class="fu">&gt;&gt;=</span> removeIndexHtml


    match <span class="st">&quot;index.html&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
        route idRoute
        compile <span class="fu">$</span> <span class="kw">do</span>
            <span class="kw">let</span> indexCtx <span class="fu">=</span> field <span class="st">&quot;posts&quot;</span> <span class="fu">$</span> \_ <span class="ot">-&gt;</span>
                                postListCont <span class="fu">$</span> <span class="fu">fmap</span> (<span class="fu">take</span> <span class="dv">3</span>) <span class="fu">.</span> recentFirst

            getResourceBody
                <span class="fu">&gt;&gt;=</span> applyAsTemplate indexCtx
                <span class="fu">&gt;&gt;=</span> loadAndApplyTemplate <span class="st">&quot;templates/default.html&quot;</span> postCtx
                <span class="fu">&gt;&gt;=</span> relativizeUrls
                <span class="fu">&gt;&gt;=</span> removeIndexHtml

    match <span class="st">&quot;templates/*&quot;</span> <span class="fu">$</span> compile templateCompiler

    create [<span class="st">&quot;atom.xml&quot;</span>] <span class="fu">$</span> <span class="kw">do</span>
    route idRoute
    compile <span class="fu">$</span> <span class="kw">do</span>
        <span class="kw">let</span> feedCtx <span class="fu">=</span> postCtx <span class="ot">`mappend`</span> bodyField <span class="st">&quot;description&quot;</span>
        posts <span class="ot">&lt;-</span> feedList
        renderAtom myFeedConfiguration feedCtx posts

    create [<span class="st">&quot;rss.xml&quot;</span>] <span class="fu">$</span> <span class="kw">do</span>
    route idRoute
    compile <span class="fu">$</span> <span class="kw">do</span>
        <span class="kw">let</span> feedCtx <span class="fu">=</span> postCtx <span class="ot">`mappend`</span> bodyField <span class="st">&quot;description&quot;</span>
        posts <span class="ot">&lt;-</span> feedList
        renderRss myFeedConfiguration feedCtx posts


<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">postCtx ::</span> <span class="dt">Context</span> <span class="dt">String</span>
postCtx <span class="fu">=</span>
    dateField <span class="st">&quot;date&quot;</span> <span class="st">&quot;%B %e, %Y&quot;</span> <span class="ot">`mappend`</span>
    defaultContext


<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">postList ::</span> ([<span class="dt">Item</span> <span class="dt">String</span>] <span class="ot">-&gt;</span> <span class="dt">Compiler</span> [<span class="dt">Item</span> <span class="dt">String</span>]) <span class="ot">-&gt;</span> <span class="dt">Compiler</span> <span class="dt">String</span>
postList sortFilter <span class="fu">=</span> <span class="kw">do</span>
    posts   <span class="ot">&lt;-</span> sortFilter <span class="fu">=&lt;&lt;</span> loadAll <span class="st">&quot;posts/*/*/*/*&quot;</span>
    itemTpl <span class="ot">&lt;-</span> loadBody <span class="st">&quot;templates/archive-item.html&quot;</span>
    list    <span class="ot">&lt;-</span> applyTemplateList itemTpl postCtx posts
    <span class="fu">return</span> list

<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">postListCont ::</span> ([<span class="dt">Item</span> <span class="dt">String</span>] <span class="ot">-&gt;</span> <span class="dt">Compiler</span> [<span class="dt">Item</span> <span class="dt">String</span>]) <span class="ot">-&gt;</span> <span class="dt">Compiler</span> <span class="dt">String</span>
postListCont sortFilter <span class="fu">=</span> <span class="kw">do</span>
    posts   <span class="ot">&lt;-</span> sortFilter <span class="fu">=&lt;&lt;</span> loadAllSnapshots <span class="st">&quot;posts/*/*/*/*&quot;</span> <span class="st">&quot;content&quot;</span>
    itemTpl <span class="ot">&lt;-</span> loadBody <span class="st">&quot;templates/post-item.html&quot;</span>
    list    <span class="ot">&lt;-</span> applyTemplateList itemTpl postCtx posts
    <span class="fu">return</span> list

<span class="fu">--------------------------------------------------------------------------------</span>
<span class="co">--feedList :: ([Item String] -&gt; Compiler [Item String]) -&gt; Compiler String</span>
feedList <span class="fu">=</span> <span class="fu">fmap</span> (<span class="fu">take</span> <span class="dv">10</span>) <span class="fu">.</span> recentFirst
    <span class="fu">=&lt;&lt;</span> loadAllSnapshots <span class="st">&quot;posts/*/*/*/*&quot;</span> <span class="st">&quot;content&quot;</span>

<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">removeIndexHtml ::</span> <span class="dt">Item</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Compiler</span> (<span class="dt">Item</span> <span class="dt">String</span>)
removeIndexHtml item <span class="fu">=</span> <span class="fu">return</span> <span class="fu">$</span> <span class="fu">fmap</span> cuttail item
  <span class="kw">where</span>
    cuttail <span class="fu">=</span> withUrls <span class="fu">$</span> replaceAll <span class="st">&quot;/index.html&quot;</span> (<span class="fu">const</span> <span class="st">&quot;/&quot;</span>)


<span class="fu">--------------------------------------------------------------------------------</span>
<span class="ot">myFeedConfiguration ::</span> <span class="dt">FeedConfiguration</span>
myFeedConfiguration <span class="fu">=</span> <span class="dt">FeedConfiguration</span>
    { feedTitle       <span class="fu">=</span> <span class="st">&quot;Average Blog&quot;</span>
    , feedDescription <span class="fu">=</span> <span class="st">&quot;Random Ramblings&quot;</span>
    , feedAuthorName  <span class="fu">=</span> <span class="st">&quot;Eugene Crosser&quot;</span>
    , feedAuthorEmail <span class="fu">=</span> <span class="st">&quot;crosser@average.org&quot;</span>
    , feedRoot        <span class="fu">=</span> <span class="st">&quot;http://www.average.org/blog/&quot;</span>
    }</code></pre>
<p>There is a thing that I’ll need to address at some point: I’d prefer to keep the markdown source in a flat directory, and the posts be put in the tree based on the posting date. In the existing code, the route to the article is derived directly from the path to the markdown source.</p>]]></summary>
</entry>
<entry>
    <title>Monitoring with Event Correleation</title>
    <link href="http://www.average.org/blog//2012/11/22/monitoring-with-event-correleation/index.html" />
    <id>http://www.average.org/blog//2012/11/22/monitoring-with-event-correleation/index.html</id>
    <published>2012-11-22T18:51:40Z</published>
    <updated>2012-11-22T18:51:40Z</updated>
    <summary type="html"><![CDATA[<p>Maybe this is an obvious and/or well known thing for the experts in the field, but I did not realize how to do event correlation <em>properly</em>, and that was one of the reasons why I did not do it at all in <a href="http://netwatcher.sourceforge.net/">NetWatcher</a>.</p>
<p>Now I know.</p>
<p>What is event correlation? Imagine that you are monitoring the responsiveness of the web server, disk space, load average and “pingability” on a machine. If this machine is disconnected from the network or crashes, without event correlation, you will get four alarms, one for each of the monitored attributes. You don’t want that, you want to know just that the machine is down (“unpingable”), the rest is unhelpful noise. To avoid superfluous notifications, you need to arrange the monitored attributes into a dependency tree, and if some attribute becomes “failed”, suppress notifications about the failures of its dependent attributes. Quite simple, and, yes, the term “event correlation” is misleading, but never mind that.</p>
<p>My monitoring tool reports status change immediately when the probing completes, and different attributes are probed independently and in parallel. I could check if any of the upstream dependencies of an attribute are in “failed” state before reporting, but it is quite probable that after a failure, a dependent attribute will be probed earlier than its dependency, and be reported nevertheless.</p>
<p>And here, at last, is the solution to this problem:</p>
<p>When we notice status change of an attribute that has dependencies, queue the report without sending it. When we have “success” of a probe of an attribute that has dependants, and the previous status was “success” as well, send the queued reports of the dependants; if the combination of the current and previous statuses is different, discard queued reports. State changes of an attribute that has no dependencies are reported right away without queueing.</p>
<p>When there is more than one level of dependencies the scheme becomes only a little bit more complicated: when you need to release the queued reports, you don’t send them but rather re-queue them up to your upstream dependency.</p>
<p>And that’s it.</p>]]></summary>
</entry>
<entry>
    <title>DNSSEC Validating Resolver on OpenWRT</title>
    <link href="http://www.average.org/blog//2012/07/06/dnssec-validating-resolver-on-openwrt/index.html" />
    <id>http://www.average.org/blog//2012/07/06/dnssec-validating-resolver-on-openwrt/index.html</id>
    <published>2012-07-06T19:30:28Z</published>
    <updated>2012-07-06T19:30:28Z</updated>
    <summary type="html"><![CDATA[<p>I have been running <code>bind</code> in resolver mode, with <a href="http://dnssec.net/"><code>DNSSEC</code></a> validation enabled on my home computer for some years. The home router was <em>not</em> set up to point the rest of the devices to that, so they all used non-validating <a href="http://dnsmasq.org/"><code>dnsmasq</code></a> on the router.</p>
<p>Recently I got a new router and installed fresh version of <a href="http://openwrt.org/"><code>openwrt</code></a>. It has <a href="http://unbound.net/"><code>unbound</code></a> in the default app repo so I soon switched off the DNS part of dnsmasq and enabled <code>unbound</code> instead.</p>
<p>This has a drawback of not having the local network served by dynamic dns of <code>dnsmasq</code>, so I could no longer access mobile devices by their names. It is not such a big deal, but it irritated me. So I decided to chain the two dns servers together, to have both a validating resolver and a properly handled domain for the home network.</p>
<p>Unfortunately, the build of <code>unbound</code> on <code>openwrt</code> is quite rough. It is not integrated with <code>Luci</code>, and does not even <em>work</em> out of the box until you manually disable the dns functionality of <code>dnsmasq</code> by setting the listen port to <code>0</code>. There is a <a href="http://lunesu.com/index.php?/archives/128-Finally-unbound-+-dnsmasq.html">howto</a> on the web on chaining unbound “behind” dnsmasq. I wanted it the other way around, something that the guy could not achieve.</p>
<p>First, we want to put <code>dnsmasq</code> on the side. The easiest way is to change the listening port to something non-standard. This can be done from the GUI:</p>
<p><code>Network -&gt; DHCP and DNS -&gt; Advanced Settings</code></p>
<p>set <code>DNS Server Port</code> to <code>5553</code>, and hit <code>Save&amp;Apply;</code>. (At this point <code>DNS</code> will stop working on your network until you configure and launch <code>unbound</code>.)</p>
<p>Now, to the magic part. We will be configuring <code>unbound</code> to serve all the world as a normal caching resolver, except the local domain and the reverse zone for the local network, for which it will act as a forwarder. In the examples we assume that the local domain is ‘<code>lan</code>’ and the local network is <code>192.168.&lt;something&gt;</code>. We will need to add something to the configuration file “<code>/etc/unbound/unbound.conf</code>”.</p>
<p>First, the basic forwarding directives:</p>
<pre><code>forward-zone:
        name: &quot;lan.&quot;
        forward-addr: 127.0.0.1@5553
	
forward-zone:
        name: &quot;168.192.in-addr.arpa.&quot;
        forward-addr: 127.0.0.1@5553</code></pre>
<p>These are self-explanatory. But this is not enough. We have to add a number of directives to the server section. First, <code>unbound</code> refuses to send <code>DNS</code> requests to <code>localhost</code> by default. To persuade it, we need this directive:</p>
<pre><code>        do-not-query-localhost: no</code></pre>
<p>Then, by default, <code>unbound</code> will try to establish trust chain. Serving a query in the “<code>lan.</code>” domain, it will try to get the <code>DS</code> record form the parent domain, in this case “<code>.</code>”. Of course the Internet root servers have no idea about our local “<code>lan.</code>” domain and will respond with <code>NXDOMAIN</code>. Which will break the trust chain. To prevent <code>unbound</code> from attempting to build the trust chain, we need to write these directives (second is for the reverse zone):</p>
<pre><code>        domain-insecure: &quot;lan.&quot;
        domain-insecure: &quot;168.192.in-addr.arpa.&quot;</code></pre>
<p>Next, by default, <code>unbound</code> refuses to return <code>A</code>s and <code>AAAA</code>s that point to private (RFC1918) addresses. We have such addresses in the “<code>lan.</code>” domain, so tell it to <code>unbound</code>:</p>
<pre><code>        private-domain: &quot;lan.&quot;</code></pre>
<p>On the other side, <code>unbound</code> refuses to deal with <code>PTR</code>s that come from private addresses, so we must override that too:</p>
<pre><code>        local-zone: &quot;168.192.in-addr.arpa&quot; nodefault</code></pre>
<p>That’s all. Now save the file, “<code>Enable</code>” and “<code>Start</code>” the “<code>unbound</code>” service in <code>System -&gt; Startup</code> and it should work.</p>
<p>Should you need to troubleshoot, run <code>&quot;unbound -vvv&quot;</code> and <code>&quot;logread -f&quot;</code>. With some luck, the messages will hint to the problem.</p>]]></summary>
</entry>
<entry>
    <title>Another Haskell exercise</title>
    <link href="http://www.average.org/blog//2012/04/15/another-haskell-exercise/index.html" />
    <id>http://www.average.org/blog//2012/04/15/another-haskell-exercise/index.html</id>
    <published>2012-04-15T20:46:52Z</published>
    <updated>2012-04-15T20:46:52Z</updated>
    <summary type="html"><![CDATA[<p>A few days ago there was a link on reddit: some company asked applicants to send resume to an address that is the first seven-digit Prime number taken from the consecutive digits of Pi which is also a palindrome. I cannot find the link anymore, but I wrote this just for fun:</p>
<pre class="sourceCode literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">module</span> <span class="dt">Main</span> <span class="kw">where</span>

Generate digits of Pi as an infinite list.
Use Unbounded Spigot Algorithm from this article:
http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf

<span class="ot">&gt; piDigits ::</span> [<span class="dt">Integer</span>]
<span class="ot">&gt;</span> piDigits <span class="fu">=</span> g(<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">3</span>,<span class="dv">3</span>) <span class="kw">where</span>
<span class="ot">&gt;</span> g(q,r,t,k,n,l) <span class="fu">=</span> <span class="kw">if</span> <span class="dv">4</span><span class="fu">*</span>q<span class="fu">+</span>r<span class="fu">-</span>t<span class="fu">&lt;</span>n<span class="fu">*</span>t
<span class="ot">&gt;</span>   <span class="kw">then</span> n <span class="fu">:</span> g(<span class="dv">10</span><span class="fu">*</span>q,<span class="dv">10</span><span class="fu">*</span>(r<span class="fu">-</span>n<span class="fu">*</span>t),t,k,<span class="fu">div</span>(<span class="dv">10</span><span class="fu">*</span>(<span class="dv">3</span><span class="fu">*</span>q<span class="fu">+</span>r))t<span class="fu">-</span><span class="dv">10</span><span class="fu">*</span>n,l)
<span class="ot">&gt;</span>   <span class="kw">else</span> g(q<span class="fu">*</span>k,(<span class="dv">2</span><span class="fu">*</span>q<span class="fu">+</span>r)<span class="fu">*</span>l,t<span class="fu">*</span>l,k<span class="fu">+</span><span class="dv">1</span>,<span class="fu">div</span>(q<span class="fu">*</span>(<span class="dv">7</span><span class="fu">*</span>k<span class="fu">+</span><span class="dv">2</span>)<span class="fu">+</span>r<span class="fu">*</span>l)(t<span class="fu">*</span>l),l<span class="fu">+</span><span class="dv">2</span>)

Find palindromes of specified length in an infinite list of digits.
Result is returned as an infinite list of Integers, each element
a palindrome when represented as digital characters. E.g.:
&quot;findPali 3 [1,2,3,2,1,7,9,7]&quot; returns &quot;[232,797]&quot;.

<span class="ot">&gt; findPali ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> [<span class="dt">Integer</span>] <span class="ot">-&gt;</span> [<span class="dt">Integer</span>]
<span class="ot">&gt;</span> findPali n x
<span class="ot">&gt;</span>   <span class="fu">|</span> <span class="fu">length</span> pref <span class="fu">&lt;</span> n      <span class="fu">=</span> []  <span class="co">-- Not necessary for infinite lists</span>
<span class="ot">&gt;</span>   <span class="fu">|</span> pref <span class="fu">==</span> <span class="fu">reverse</span> pref <span class="fu">=</span> toint pref<span class="fu">:</span>findPali n (<span class="fu">tail</span> x)
<span class="ot">&gt;</span>   <span class="fu">|</span> <span class="fu">otherwise</span>            <span class="fu">=</span> findPali n (<span class="fu">tail</span> x)
<span class="ot">&gt;</span>     <span class="kw">where</span>
<span class="ot">&gt;</span>       pref <span class="fu">=</span> <span class="fu">take</span> n x
<span class="ot">&gt;</span>       toint <span class="fu">=</span> <span class="fu">foldl</span> (\acc x <span class="ot">-&gt;</span> acc<span class="fu">*</span><span class="dv">10</span><span class="fu">+</span>x) <span class="dv">0</span>

Check if an Integer is a Prime number. Function copied from here:
http://stackoverflow.com/questions/4541415/haskell-prime-test
It is a &quot;naive&quot; implementaion but fast enough for our case, and
readily understandable.

<span class="ot">&gt; isPrime ::</span> <span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>
<span class="ot">&gt;</span> isPrime x <span class="fu">=</span> <span class="fu">not</span> <span class="fu">$</span> <span class="fu">any</span> divisible <span class="fu">$</span> <span class="fu">takeWhile</span> notTooBig [<span class="dv">2</span><span class="fu">..</span>]
<span class="ot">&gt;</span>   <span class="kw">where</span>
<span class="ot">&gt;</span>     divisible y <span class="fu">=</span> x <span class="ot">`mod`</span> y <span class="fu">==</span> <span class="dv">0</span>
<span class="ot">&gt;</span>     notTooBig y <span class="fu">=</span> y<span class="fu">*</span>y <span class="fu">&lt;=</span> x

Find and return the first element in a list based on predicate.
Our list is infinite so we don&#39;t need the result to be of &quot;Maybe&quot;
type like the &quot;canonical&quot; implementation in Data.List.

<span class="ot">&gt; find&#39; ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> a
<span class="ot">&gt;</span> find&#39; p (x<span class="fu">:</span>xs)
<span class="ot">&gt;</span>   <span class="fu">|</span> p x       <span class="fu">=</span> x
<span class="ot">&gt;</span>   <span class="fu">|</span> <span class="fu">otherwise</span> <span class="fu">=</span> find&#39; p xs

Print the first 7-digit palindrome of consecutive digits of Pi
that is a Prime number.

<span class="ot">&gt;</span> main <span class="fu">=</span> <span class="fu">putStrLn</span> <span class="fu">$</span> <span class="fu">show</span> <span class="fu">$</span> find&#39; isPrime <span class="fu">$</span> findPali <span class="dv">7</span> piDigits</code></pre>
<p>This is not the fastest thing you can invent (prime check is very simplistic), but it gives the result in under a minute on my system.</p>
<p>UPDATE 2012-04-16: Found the link. Not writing it here ;)</p>]]></summary>
</entry>
<entry>
    <title>Using ebook reader as a wall display</title>
    <link href="http://www.average.org/blog//2012/02/08/using-ebook-reader-as-a-wall-display/index.html" />
    <id>http://www.average.org/blog//2012/02/08/using-ebook-reader-as-a-wall-display/index.html</id>
    <published>2012-02-08T19:57:00Z</published>
    <updated>2012-02-08T19:57:00Z</updated>
    <summary type="html"><![CDATA[<p>My mom, who is of advanced age, sadly has her memory weakening. This of course creates a number of problems, but just one I decided that I can handle by technical means. This one problem is that she likes me to call her by phone every evening, and gets nervous when I don’t. Or when she forgets that I did. Then she cannot sleep, and finally calls me in the middle of the night.</p>
<p>So I got this idea: I have the call log in my phone. If I could make a wall display at my mom’s place that shows when the last call happened that might help. For good measure, I could analyse my location and show if I am at home, or at work, or elsewhere.</p>
<p>The first question that arised was what to use as the display. A computer monitor or an electronic photo frame would irritate mom with the glow. Ideally I would want e-ink display like in an ebook reader. Making custom electronics to drive the display is out of my league (or at least would require much more effort than I was ready to invest), and most existing readers would be difficult to hack to show the data that I need. But not all. I learned that Sony PRS-T1 runs Android, has WiFi, and <a href="http://www.the-ebook.org/forum/viewtopic.php?t=21458">can be easily rooted</a>. So it was settled.</p>
<p>With Android systems on both ends, using Google services for intermediary was an obvious choice. I already had Latitude enabled on my phone, and the call log synched to a dedicated Google calendar by <a href="https://github.com/jberkel/sms-backup-plus/#readme">SMS Backup+</a>. (The latter I later replaced with <a href="http://asterdroidmobile.com/">CallTrack</a> because it creates the calendar events in near-real-time when the phone call completes.)</p>
<p>The next question was where to process the data. For a while, I considered the idea of running the processing “in the cloud” (on my own collocated server), making API calls to Google services, and cooking the text for displaying on the reader device. Or even the image. The latter would be the only choice if I was using a photo frame. In the end, I decided to cut the number of intermediaries and do the job on the reader device itself.</p>
As of this writing, the app works, but there are some troubles that I need to address before I install the thing at mom’s place. Anyway, this is how it looks:
<p align="center">
<img src="/images/WhereAmI-screenshot-180x240.png" alt="Screenshot ofWhereAmI&quot; Android app“" />
</p>

<p>And here is the <a href="http://www.average.org/gitweb/?p=WhereAmI.git;a=summary">git repository</a>.</p>
<p>Edit Feb 10: <a href="https://groups.google.com/d/topic/google-api-java-client/iSL2bzoy9jw/discussion">this is the problem</a> that I mentioned above. So far, I just introduced a couple of retries in case of error, but I hate it this way.</p>]]></summary>
</entry>
<entry>
    <title>One man's +1 is another man's -1</title>
    <link href="http://www.average.org/blog//2011/11/01/one-mans-1-is-another-mans-1/index.html" />
    <id>http://www.average.org/blog//2011/11/01/one-mans-1-is-another-mans-1/index.html</id>
    <published>2011-11-01T10:16:40Z</published>
    <updated>2011-11-01T10:16:40Z</updated>
    <summary type="html"><![CDATA[<blockquote>
<p>(This was posted as a comment in a <a href="https://plus.google.com/117377434815709898403/posts/eJQ5yzaxQqb">discussion</a> about the redesigned Google Reader on G+)</p>
</blockquote>
<p>I’ve been mulling this idea for a long time. In one line:</p>
<p><strong>One man’s +1 is another man’s -1</strong></p>
<p>When reddit became popular, the biggest frustration for me was the abundance of kittens. (Don’t get me wrong, I <em>love</em> kittens, I just come to reddit for other things.) Now, if I consistently downvote kittens, then the system should be able to determine that my taste is opposite to the users who consistently upvote them, and count their <em>up</em>votes as if they where <em>down</em>votes, when creating the display for me. Conversely, my downvote will be counted as upvote in relation to those people.</p>
<p>This way, people with opposite tastes will <em>help</em> produce better experience for each other, instead of <em>disrupting</em> it like they do in all current rating-based systems.</p>
<p>Next step will be automatic grouping of people with similar tastes. Friend suggestions based on actual personal qualities instead of incidental features of the social graph, isn’t it fascinating?</p>
<p>Of course, for this idea to work, there needs to be a -1 button like on reddit. Google ±, anyone?</p>
<p><strong>Update Aug 3 2013:</strong> nice <a href="http://www.abstrusegoose.com/527">illustration</a>!</p>]]></summary>
</entry>
<entry>
    <title>'"Lucky tickets" exercise'</title>
    <link href="http://www.average.org/blog//2011/06/14/lucky-tickets-exercise/index.html" />
    <id>http://www.average.org/blog//2011/06/14/lucky-tickets-exercise/index.html</id>
    <published>2011-06-14T18:07:34Z</published>
    <updated>2011-06-14T18:07:34Z</updated>
    <summary type="html"><![CDATA[<p>OK, I know this is stupid. I am toying with Haskell, and this task is a textbook example of list comprehensions. Create a list of “lucky ticket numbers”, where the number is six decimal digits, and lucky is when the sum of the first three digits is equal to the sum of the last three digits:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">lucky_list <span class="fu">=</span>
    [[a,b,c,x,y,z] <span class="fu">|</span> a<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>], b<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>], c<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>],
                     x<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>], y<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>], z<span class="ot">&lt;-</span>[<span class="dv">0</span><span class="fu">..</span><span class="dv">9</span>],
                     a<span class="fu">+</span>b<span class="fu">+</span>c <span class="fu">==</span> x<span class="fu">+</span>y<span class="fu">+</span>z]
main <span class="fu">=</span> <span class="fu">putStrLn</span> <span class="fu">$</span> <span class="fu">show</span> <span class="fu">$</span> <span class="fu">length</span> lucky_list</code></pre>
<p>this runs in 650+ ms on my system. Can we improve on that? Let’s iterate over possible sums (which are from 0 to 27 since <code>9+9+9=27</code>). For each sum, combine the distinct triples that sum to that. We can iterate over possible <em>pairs</em> of digits <code>(x,y)</code>, getting the third digit as <code>(z = sum-x-y)</code>. Here is what we get:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">lucky_list <span class="fu">=</span>
    [x<span class="fu">++</span>y <span class="fu">|</span> s <span class="ot">&lt;-</span> [<span class="dv">0</span><span class="fu">..</span><span class="dv">27</span>], x <span class="ot">&lt;-</span> triples_with_sum s, y <span class="ot">&lt;-</span> triples_with_sum s ]
  <span class="kw">where</span>
    triples_with_sum s <span class="fu">=</span>
      [[x,y,s<span class="fu">-</span>x<span class="fu">-</span>y] <span class="fu">|</span> x<span class="ot">&lt;-</span>[lx <span class="fu">..</span> hx], y<span class="ot">&lt;-</span>[ly x <span class="fu">..</span> hy x]]
        <span class="kw">where</span>
          lx   <span class="fu">|</span> s <span class="fu">&lt;</span> <span class="dv">18</span>     <span class="fu">=</span> <span class="dv">0</span>
               <span class="fu">|</span> otherwise  <span class="fu">=</span> s<span class="fu">-</span><span class="dv">18</span>
          hx   <span class="fu">|</span> s <span class="fu">&gt;</span> <span class="dv">9</span>      <span class="fu">=</span> <span class="dv">9</span>
               <span class="fu">|</span> otherwise  <span class="fu">=</span> s
          ly x <span class="fu">|</span> s<span class="fu">-</span>x<span class="fu">-</span><span class="dv">9</span> <span class="fu">&lt;</span> lx <span class="fu">=</span> lx
               <span class="fu">|</span> otherwise  <span class="fu">=</span> s<span class="fu">-</span>x<span class="fu">-</span><span class="dv">9</span>
          hy x <span class="fu">|</span> s<span class="fu">-</span>x <span class="fu">&gt;</span> <span class="dv">9</span>    <span class="fu">=</span> <span class="dv">9</span>
               <span class="fu">|</span> otherwise  <span class="fu">=</span> s<span class="fu">-</span>x
    <span class="co">-- This expression is less optimized but is much simpler:</span>
    <span class="co">-- a &lt;- [0..9], b &lt;- [0..9], let c = s-a-b, c &gt;= 0, c &lt;= 9]</span>
    <span class="co">-- Speed difference is not noticable</span>
main <span class="fu">=</span> <span class="fu">putStrLn</span> <span class="fu">$</span> <span class="fu">show</span> <span class="fu">$</span> <span class="fu">length</span> lucky_list</code></pre>
<p>That’s better: about 80 ms. Now we try to do it in C:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="ot">#include &lt;stdio.h&gt;</span>

<span class="kw">typedef</span> <span class="dt">void</span> (*iterator_t)(<span class="dt">int</span> a, <span class="dt">int</span> b, <span class="dt">int</span> s, <span class="dt">void</span> (*func)(), <span class="dt">int</span> x, <span class="dt">int</span> y);

<span class="dt">static</span> <span class="dt">int</span> count = <span class="dv">0</span>;
<span class="ot">#define lsize 65535</span>
<span class="dt">static</span> <span class="dt">char</span> lucky_list [lsize][<span class="dv">6</span>];

<span class="dt">static</span> <span class="dt">void</span>
give_result(<span class="dt">int</span> a, <span class="dt">int</span> b, <span class="dt">int</span> s, iterator_t iterator, <span class="dt">int</span> x, <span class="dt">int</span> y)
{
	<span class="co">//printf(&quot;[%d,%d,%d,%d,%d,%d]\n&quot;, a, b, s-a-b, x, y, s-x-y);</span>
	<span class="kw">if</span> (count &lt; lsize) {
		lucky_list[count][<span class="dv">0</span>] = a;
		lucky_list[count][<span class="dv">1</span>] = b;
		lucky_list[count][<span class="dv">2</span>] = s-a-b;
		lucky_list[count][<span class="dv">3</span>] = x;
		lucky_list[count][<span class="dv">4</span>] = y;
		lucky_list[count][<span class="dv">5</span>] = s-x-y;
	}
	count++;
}

<span class="dt">static</span> <span class="dt">void</span>
iterate_triplets(<span class="dt">int</span> a, <span class="dt">int</span> b, <span class="dt">int</span> s, iterator_t iterator, <span class="dt">int</span> p, <span class="dt">int</span> q)
{
	<span class="dt">int</span> lx = s<span class="dv">-18</span>;
	<span class="dt">int</span> hx = s;
	<span class="kw">if</span> (lx &lt; <span class="dv">0</span>) lx = <span class="dv">0</span>;
	<span class="kw">if</span> (hx &gt; <span class="dv">9</span>) hx = <span class="dv">9</span>;

	<span class="co">//if (a &gt;= 0)</span>
	<span class="co">//	printf(&quot;%d: %d, %d, %d [%d..%d]\n&quot;,</span>
	<span class="co">//		s, a, b, s-a-b, lx, hx);</span>

	<span class="kw">for</span> (<span class="dt">int</span> x = lx; x &lt;= hx; x++) {
		<span class="dt">int</span> ly = s-x<span class="dv">-9</span>;
		<span class="dt">int</span> hy = s-x;
		<span class="kw">if</span> (ly &lt; lx) ly = lx;
		<span class="kw">if</span> (hy &gt; x) hy = x;

		<span class="kw">for</span> (<span class="dt">int</span> y = ly; y &lt;= hy; y++) {
			(*iterator)(x, y, s, give_result, a, b);
			<span class="kw">if</span> (x != y) {
				(*iterator)(y, x, s, give_result, a, b);
			}
		}
	}
}

<span class="dt">int</span>
main(<span class="dt">int</span> argc, <span class="dt">char</span> *argv[])
{
	<span class="kw">for</span> (<span class="dt">int</span> s = <span class="dv">0</span>; s&lt;=<span class="dv">27</span>; s++) {
		iterate_triplets(-<span class="dv">1</span>, -<span class="dv">1</span>, s, iterate_triplets, -<span class="dv">1</span>, -<span class="dv">1</span>);
	}
	printf(<span class="st">&quot;%d</span><span class="ch">\n</span><span class="st">&quot;</span>, count);
	<span class="kw">return</span> <span class="dv">0</span>;
}</code></pre>
<p>This was so much longer! And harder to understand. But the speed is so high we could not measure it!.</p>]]></summary>
</entry>
<entry>
    <title>More about Federated Social Networking</title>
    <link href="http://www.average.org/blog//2010/10/06/more-about-federated-social-networking/index.html" />
    <id>http://www.average.org/blog//2010/10/06/more-about-federated-social-networking/index.html</id>
    <published>2010-10-06T19:52:18Z</published>
    <updated>2010-10-06T19:52:18Z</updated>
    <summary type="html"><![CDATA[<p>In 2006, I was <a href="/blog/2006/12/22/on-social-networking/">mulling</a> the idea of applying concept of federation to social networking. Four years passed, and lo and behold! We have <a href="http://status.net/">status.net</a> in production, <a href="http://gitorious.org/social/pages/Home">GnuSocial(/daisychain)</a>, <a href="http://onesocialweb.org/">OneSocialWeb</a>, <a href="http://www.joindiaspora.com/">Diaspora</a> and probably others in development.</p>
<p>Not that everyhting is rosy - centralized propriatory “social networks” are still far ahead in terms of usability and feature-completeness, but at least there is some progress.</p>]]></summary>
</entry>
<entry>
    <title>Data Backup and Recovery in Post-Terabyte Era</title>
    <link href="http://www.average.org/blog//2007/12/07/data-backup-and-recovery-in-post-terabyte-era/index.html" />
    <id>http://www.average.org/blog//2007/12/07/data-backup-and-recovery-in-post-terabyte-era/index.html</id>
    <published>2007-12-07T12:48:00Z</published>
    <updated>2007-12-07T12:48:00Z</updated>
    <summary type="html"><![CDATA[<blockquote>
<p>Disclaimer: I am now employed by a company for which data storage and backup are parts of its business, but the ideas in this post are from earlier time, when I worked for a (relatively big) ISP, and are not connected with my current job.</p>
</blockquote>
<p>We have been backing up the data from our disks to tapes ever since the disks came to existence (we already had tapes by that time). But with the development of technology during the past decade or two, this approach is becoming increasingly problematic. The main trouble is that the density of data on disk storage devices grows faster than the speed at which this data can be copied to/from tape backup devices. It may be tolerable when backing up some database takes several hours (if you can do that without taking it offline), but if recovering it from the backup, in case of loss of “online” data, takes several hours, it means that the disaster recovery procedure becomes a disaster of its own.</p>
<p>On the other hand, the price of disk storage is falling at a higher rate than that of tape storage, and proposition of buying twice or thrice more disk arrays instead of a tape library looks more and more viable. Disks are still more expensive than tape, but not that much. There are even commercially available “solutions” that do backup on disks instead of on tapes. The problem is, just replacing the medium does not help that much with speeding up the process.</p>
<p>Now, let’s try to decompose the problem that we are solving when we establish backup on our system. There are two kinds of errors that a proper backup can mitigate if they happen: equipment imposed and application imposed. I am not calling the former “hardware errors” because I also include firmware/software errors (RAID implementation, block device drivers, filesystem code) into this class. And I am not calling the latter “human errors” because, well, errors in the filesystem code are human errors too, and I am clumping together a sloppy sysadmin who accidentally typed “<strong>rm * .bak</strong>” and a sloppy web application programmer who failed to validate input and allowed an <a href="http://xkcd.com/327/">sql injection</a>.</p>
<p>For the first class of errors, “equipment errors”, there is much better remedy than tape backup, it’s RAID technology. In fact, most shops run RAIDs anyway, to reduce the impact of long restoration times, and from experience, there are very little cases when you have to fall back to tape backup after equipment failures. All you need to do is choose a “right” RAID solution (not all RAID controllers are born equal), and manage it in a “right way” (i.e. actually notice when there is a failed element, and replace it quickly). I’d hazard to say, if you have a decent RAID storage system, you can stop bothering about equipment failures at all. And it won’t cost you a fortune.</p>
<p>The second class of errors, the “human”/“application” errors, is much worse, because although getting rid of them “almost completely” is possible (I, for one, certainly hope that the procedure for launching a nuclear attack is made relatively error-resistant!), it is not practical for most “normal” businesses to hire twice the staff and establish approval procedures for every keypress. So, there must be a way to go back in time and restore the “most recent known good” state of data. Normally, it means restoring from the last (or some previous, if you are extremely unlucky) generation of backup.</p>
<p>Now, there is a better way to achieve the same goal: it is to have data storage capable for “persistent <a href="http://en.wikipedia.org/wiki/Snapshot_%28computer_storage%29">snapshots</a>”. While (usually non-persistent) snapshots have been used for a long time, on high-end storage systems, in conjunction with regular tape backup, they where not considered as an alternative to tape backup. On the other hand, Apple’s <a href="http://en.wikipedia.org/wiki/Time_Machine_%28software%29">Time Machine</a> is specifically designed as an alternative to traditional backup, remedying for “second class” of errors, but it is not, in typical configuration, backed by anything that could protect from the errors of the “first class”.</p>
<p>So, I see the data storage system for today and tomorrow use as a decent RAID (e.g., RAID1 over TCP/IP via <a href="http://www.drbd.org/">DRBD</a> worked really well for me, and it even allows for geographically distributed configurations), and a filesystem (or volume manager) capable for reliable persistent snapshots on top of it. Throw in a policy manager that would create new and remove old unneeded snapshot generations, and a monitor that would alert the user in case of component failure, and you get a tape-less system that is as reliable as a system with a tape backup, and can recover from disasters much faster.</p>]]></summary>
</entry>

</feed>
