<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Flying memes</title>
	<atom:link href="http://sandropaganotti.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sandropaganotti.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sun, 25 Jul 2010 12:45:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>An iPad plugin theme for wordpress: working alpha</title>
		<link>http://sandropaganotti.com/2010/07/25/an-ipad-plugin-theme-for-wordpress-working-alpha/</link>
		<comments>http://sandropaganotti.com/2010/07/25/an-ipad-plugin-theme-for-wordpress-working-alpha/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 12:45:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Annunci]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[Sencha]]></category>
		<category><![CDATA[Theme]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[WpTouch]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=425</guid>
		<description><![CDATA[I&#8217;ve started deploying an iPad wordpress theme/plugin based on wptouch and powered by Sencha. Today I&#8217;ve reached the first working alpha and so I&#8217;ve decided to use it against this blog. You can try out this theme by surfing here with an iPad or a simulator; two screenshots are also available after the jump. I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started deploying an iPad wordpress theme/plugin based on <a href="http://wordpress.org/extend/plugins/wptouch/">wptouch</a> and powered by <a href="http://www.sencha.com/">Sencha</a>. Today I&#8217;ve reached the first working alpha and so I&#8217;ve decided to use it against this blog. You can try out this theme by surfing here with an iPad or a simulator; two screenshots are also available after the jump.</p>
<p><span id="more-425"></span></p>
<p><a href="http://sandropaganotti.com/wp-content/uploads/2010/07/ishot-2241.png"><img class="alignnone size-full wp-image-430" title="ishot-224" src="http://sandropaganotti.com/wp-content/uploads/2010/07/ishot-2241.png" alt="" width="600" height="465" /></a></p>
<p><a href="http://sandropaganotti.com/wp-content/uploads/2010/07/Screen-shot-2010-07-25-at-14.27.471.png"><img class="alignnone size-full wp-image-429" title="Screen shot 2010-07-25 at 14.27.47" src="http://sandropaganotti.com/wp-content/uploads/2010/07/Screen-shot-2010-07-25-at-14.27.471.png" alt="" width="462" height="599" /></a></p>
<p>I&#8217;ve planned to release a first version of this plugin as soon as it include some basic features, such as permalink navigation and pages support.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/07/25/an-ipad-plugin-theme-for-wordpress-working-alpha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>We Love Shadows! A CSS3 and Javascript based light source</title>
		<link>http://sandropaganotti.com/2010/06/19/we-love-shadows-a-css3-and-javascript-based-light-source/</link>
		<comments>http://sandropaganotti.com/2010/06/19/we-love-shadows-a-css3-and-javascript-based-light-source/#comments</comments>
		<pubDate>Sat, 19 Jun 2010 13:31:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Interfaccie]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=405</guid>
		<description><![CDATA[CSS3 has gradients and CSS3 has shadows, so why don&#8217;t try to use both to simulate a light source ? That is the basic idea behind this project. I&#8217;ve set-up a small demo which let you use the mouse to direct a light source over a text and observe its shadow change according to light [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dev.w3.org/csswg/css3-images/" target="_blank">CSS3 has gradients</a> and <a href="http://www.w3.org/TR/css3-text/#text-shadow" target="_blank">CSS3 has shadows</a>, so why don&#8217;t try to use both to simulate a light source ? That is the basic idea behind this project. <a href="http://sandropaganotti.com/wp-content/goodies/demos/we-love-shadows/we-love-shadows.html" target="_blank">I&#8217;ve set-up a small demo</a> which let you use the mouse to direct a light source over a text and observe its shadow change according to light position.</p>
<p><span id="more-405"></span> To simulate the light behavior I used a CSS3 gradient on the body background and a text-shadow property on the text. Both of these css3 attributes are then dynamically changed upon the user&#8217;s mouse move.</p>
<p>Here&#8217;s the snippet of the JQuery-flavored javascript I used:</p>
<pre><code class="javascript">$(document).ready(function() {
    $('body').mousemove(function(event) {
        $('#instructions').hide();

        // compute the center of the page and the distance between the center and the mouse
        // coordinates
        cx = Math.ceil($('body').width()  / 2);
        cy = Math.ceil($('body').height() / 2);
        dx = event.pageX - cx;
        dy = event.pageY - cy;

        // introducing a little parallax for the biggest light cone
        x0 = Math.ceil(cx - (dx * 0.2));
        y0 = Math.ceil(cy - (dy * 0.2));
        x1 = event.pageX;
        y1 = event.pageY;
        r0 = 300;
        r1 = 10;

        // another parallax for the text shadow
        sx = -dx * 0.03;
        sy = -dy * 0.03;

        // blur the shadow depending upon its distance
        b  =  (Math.abs(sx) + Math.abs(sy)) * 0.2;

        // simulate the light
        $('body').css('background-image', "-webkit-gradient(radial, " + x0 +" " + y0 +", "+ r0 +", "+ x1 +" "+ y1 +", "+ r1 +", from(#575757), to(#FFFFFF))");

        // simulate the shadow
        $('h1').css('text-shadow', "#444 "+ sx +"px "+ sy + "px " + b + "px");
    });
});
</code></pre>
<p>Here&#8217;s an image took from the demo, the whole page source code is available on <a href="http://github.com/sandropaganotti" target="_blank">my github account</a> as a <a href="http://gist.github.com/444897" target="_blank">gist</a>:</p>
<p><a href="http://sandropaganotti.com/wp-content/goodies/demos/we-love-shadows/we-love-shadows.html"><img title="WeLoveShadows" src="http://sandropaganotti.com/wp-content/uploads/2010/06/Untitled.jpg" alt="" width="625" height="277" /></a></p>
<p>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/06/19/we-love-shadows-a-css3-and-javascript-based-light-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I&#8217;ve just checked in at WC2010 Johannesburg Stadium from home</title>
		<link>http://sandropaganotti.com/2010/06/12/foursquare-easy-hacking/</link>
		<comments>http://sandropaganotti.com/2010/06/12/foursquare-easy-hacking/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 23:05:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Algoritmi]]></category>
		<category><![CDATA[foursquare]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=393</guid>
		<description><![CDATA[Thanks to Uncle Pear suggestion I realized that you can easily check-in in every Foursquare venue simply invoking its id using the API, to try this behavior I checked in at Johannesburg  WC2010 stadium from my home in Italy. Here&#8217;s the simple snippet of code you can use (from a linux shell): curl -u sandro.paganotti@gmail.com:my_password [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to <a href="http://unclepear.com/" target="_blank">Uncle Pear</a> suggestion I realized that you can easily check-in in every Foursquare venue simply invoking its id using the API, to try this behavior <a href="http://foursquare.com/user/-1098756" target="_blank">I checked in at Johannesburg  WC2010 stadium</a> from my home in Italy.</p>
<p><span id="more-393"></span> Here&#8217;s the simple snippet of code you can use (from a linux shell):</p>
<pre><code>curl -u sandro.paganotti@gmail.com:my_password -d "vid=4762107" http://api.foursquare.com/v1/checkin
</code></pre>
<p><a href="http://groups.google.com/group/foursquare-api/web/api-documentation" target="_blank">Foursquare api</a> are really easy to use and lets you invoke up to 200 times each method each hour, so a quite simple exercise can be write a simple program that automatically check-in a selected account in a given array of locations:</p>
<pre><code class="ruby">
require 'rubygems'
require 'restclient'
require 'nokogiri'

counter = -1
debug   = true

travel = [
            # minutes to wait, venue to check-in
            [5 ,4762107],
            [10,2335319]
         ]

RestClient.add_before_execution_proc do |req, params|
    req.basic_auth 'sandro.paganotti@gmail.com', 'my_password'
end

loop do
    time, venue_id = travel[counter = ((counter + 1) % travel.size)]
    puts "sleeping #{time} minutes.." if debug
    sleep time * 60
    response = RestClient.post "http://api.foursquare.com/v1/checkin", :vid=&gt;venue_id
    puts  ['checkin','message'].inject(Nokogiri::XML(response.body)) { |s,r| s.send(:at, r) }.inner_text
end
</code></pre>
<p>By invoking this code an infinite loop will check-in the provided account into each of the given venues waiting a configurable amount of time between each of them.</p>
<p>Here&#8217;s the result:</p>
<pre><code>sandropaganotti$ ruby venue.rb
sleeping 5 minutes..
OK! We've got you @ WC2010 Soccer City Stadium. This is your 2nd checkin here!
sleeping 10 minutes..
OK! We've got you @ Service Station Cafe. This is your 1st checkin here!
sleeping 5 minutes..
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/06/12/foursquare-easy-hacking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euruko 2010 and some CSS3 experiments</title>
		<link>http://sandropaganotti.com/2010/06/06/euruko-2010-and-some-css3-experiments/</link>
		<comments>http://sandropaganotti.com/2010/06/06/euruko-2010-and-some-css3-experiments/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 13:34:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Annunci]]></category>
		<category><![CDATA[Approfondimenti]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[Euruko 2010]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=386</guid>
		<description><![CDATA[update 14/07/2010: rubyinside.com featured my speaker showcase ! Here&#8217;s the post ! update 19/06/2010: my speakers showcase gets a dedicated post at euruko2010 official blog from Ela. Thanks guys ! Euruko 2010 is over. It was a great week-end spent among cool people having fun and talking about Ruby. As Matz said &#8220;we have a [...]]]></description>
			<content:encoded><![CDATA[<p><strong>update 14/07/2010: </strong><a href="http://rubyinside.com">rubyinside.com</a> featured my speaker showcase ! <a href="http://www.rubyinside.com/euruko-2010-presentations-3538.html">Here&#8217;s the post </a>!</p>
<p><strong>update 19/06/2010: </strong>my <a href="http://euruko2010.heroku.com" target="_blank">speakers showcase</a> gets a dedicated post at <a href="http://euruko2010.org" target="_blank">euruko2010 official blog</a> from <a href="http://twitter.com/elamadej">Ela</a>. Thanks guys !</p>
<p><a href="http://euruko2010.org">Euruko 2010</a> is over. It was a great week-end spent among cool people having fun and talking about Ruby. As Matz said &#8220;we have a nice community&#8221;, and that&#8217;s absolutely true. To honor this conference (and to test some CSS3 features ^_^ ) <a href="http://euruko2010.heroku.com" target="_blank">I&#8217;ve developed a page</a> showcasing the speakers and their talks. For each of them you may find a short summary and some resources (slide, etc..).</p>
<p><span id="more-386"></span>Working with CSS3 highlight some browser performances problem I was unaware before, for example I tried to have a scrolling background under a shadowed box, <a href="http://euruko2010.heroku.com/?bgon=true" target="_blank">you can try this in your browser and notice how it is slow</a>. However if we turn the shadows off the scrolling become smooth again (<a href="http://euruko2010.heroku.com/?bgon=true&amp;shadow_off=true" target="_blank">try this</a>).</p>
<p>Ok, nothing left to say, hope you&#8217;ll enjoy the showcase:</p>
<p style="text-align: center;"><a href="http://euruko2010.heroku.com" target="_blank"><img class="aligncenter size-full wp-image-387" style="border: 1px solid black;" title="ishot-179" src="http://sandropaganotti.com/wp-content/uploads/2010/06/ishot-179.png" alt="" width="529" height="570" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/06/06/euruko-2010-and-some-css3-experiments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>whymca 2010: so good!</title>
		<link>http://sandropaganotti.com/2010/05/23/whymca-2010-so-good/</link>
		<comments>http://sandropaganotti.com/2010/05/23/whymca-2010-so-good/#comments</comments>
		<pubDate>Sun, 23 May 2010 21:54:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Annunci]]></category>
		<category><![CDATA[whymca10]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=384</guid>
		<description><![CDATA[Just a small post to thanks everyone who took part to whymca 2010 conference. I specially want to thanks people who attend my and Marco&#8216;s talk &#8216;HTML5 come strumento di sviluppo mobile&#8217;. Finally many kudos to all the organizers who managed to set-up this amazing conference.]]></description>
			<content:encoded><![CDATA[<p>Just a small post to thanks everyone who took part to <a href="http://www.whymca.org/" target="_blank">whymca 2010</a> conference. I specially want to thanks people who attend my and <a href="http://mavimo.org/" target="_blank">Marco</a>&#8216;s talk <a href="http://www.slideshare.net/sandropaganotti/html5-come-strumento-di-sviluppo-mobile">&#8216;HTML5 come strumento di sviluppo mobile&#8217;</a>. Finally many kudos to <a href="http://www.whymca.org/page/chi-siamo" target="_blank">all the organizers</a> who managed to set-up this amazing conference.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/05/23/whymca-2010-so-good/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A semantic experiment for separate good from bad.</title>
		<link>http://sandropaganotti.com/2010/05/04/a-semantic-experiment-for-separate-good-from-bad/</link>
		<comments>http://sandropaganotti.com/2010/05/04/a-semantic-experiment-for-separate-good-from-bad/#comments</comments>
		<pubDate>Tue, 04 May 2010 11:37:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Algoritmi]]></category>
		<category><![CDATA[Semantic Relations]]></category>
		<category><![CDATA[wordnet]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=379</guid>
		<description><![CDATA[Yesterday was sunday and I came up with a fascinating idea: what happens if I use wordnet to measure the distance between two words ? By assigning weights to all the relation types and by navigate this relations graph I thought to be able to measure the distance between a word and the others in [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday was sunday and I came up with a fascinating idea: what happens if I use <a href="http://github.com/roja/words">wordnet</a> to measure the distance between two words ? By assigning  weights to all the relation types and by navigate this relations graph I  thought to be able to measure the distance between a word and the others  in terms of the minimum sum of weights of the edges between each pair made of the chosen word and another.</p>
<p><span id="more-379"></span><br />
So I tried to assign weights using the relation type as discriminator, to make an example take the word &#8216;sword&#8217; and its relations:</p>
<pre><code>
related-term        relation type           assigned weight
weapon:             hypernym                5
backsword:          hyponym                 2
blade:              part_meronym            3
broadsword:         hyponym                 2
cavalry sword:      hyponym                 2
cutlas:             hyponym                 2
Excalibur:          instance_hyponym        2
falchion:           hyponym                 2
fencing sword:      hyponym                 2
foible:             part_meronym            3
forte:              part_meronym            3
haft:               part_meronym            3
hilt:               part_meronym            3
rapier:             hyponym                 2
point:              part_meronym            3
</code></pre>
<p>The weight I choose for each of the relation types tried to follow the statement<br />
&#8216;The more the words are related the less greater the number is&#8217;; so weapon is less<br />
related to sword than broadsword because the first express a concept broader than sword<br />
(also a nuclear bomb is a weapon); the second instead detail the word &#8216;sword&#8217; and<br />
make true the statement &#8216;A broadsword is always a sword&#8217; so it&#8217;s more related to the<br />
chosen word.</p>
<p>By following this general rule I associated a weight to each of the most common  relation types and wrote down a few lines of code in order to compute weights by navigate the relation graph:</p>
<pre>
<code class="ruby">
def compute_distances(weights = :default, max_depth_allowed = 6)

  # retrieve the list of the weights associated to each relation type
  # (its just an hash {:relation_type => weight})
  weights = CONFIG_FILE['distance']["#{weights}"]
  data = Words::Wordnet.new

  # get a list of sysnsets as a starting point (eg: red, crimson)
  synsets_to_analyze = self.synsets.map{|s| [s.synset_id,0,0]}
  synsets_to_store   = []

  # process the first element of the list
  # until the sysets_to_analyze stack is empty
  while(sys = synsets_to_analyze.shift) do
    sys_id,dis,dep = *sys; next if dep >= max_depth_allowed
    sys = Words::Synset.new(sys_id,data.wordnet_connection,nil) rescue next;

    # save the current sysnset words into an output array
    sys.words.each {|w|  synsets_to_store.unshift([sys_id,w,dis])}

    # put each of the sysnset related to this into the stack unless they
    # are already present
    sys.relations.each do |r|
      synsets_to_analyze.unshift(
        [r.destination.synset_id, dis + weights["#{r.relation_type}"],dep + 1]
      ) if r.is_semantic? and
           !synsets_to_store.find{|s| s.first == r.destination.synset_id}
    end
  end

  # now in sysnsets_to_store you have an array of the words each of them
  # with the weight that separe it from the starting synsets.
 # (now I store them on a db, but is just because the context is the same as the Abacus gem)
  synsets_to_store.each do |s|
    a_id = ArticleKey.find_by_the_key(s[1]).id rescue next
    self.distances.find_or_create_by_article_key_id( a_id, :distance => s[2])
  end

end
</code>
</pre>
<p>Here some of the results for &#8216;sword&#8217; with depth = 3:</p>
<pre><code>
sword:                           0
brand:                           0
steel:                           0
broadsword:                      2
rapier:                          2
tuck:                            2
backsword:                       2
fencing sword:                   2
falchion:                        2
Excalibur:                       2
cutlas:                          2
sabre:                           2
cavalry sword:                   2
saber:                           2
cutlass:                         2
foible:                          3
blade:                           3
hilt:                            3
forte:                           3
tip:                             3
peak:                            3
point:                           3
helve:                           3
haft:                            3
claymore:                        4
scimitar:                        4
saber:                           4
sabre:                           4
foil:                            4
epee:                            4
arm:                             5
basket hilt:                     5
head:                            5
weapon system:                   5
knife blade:                     5
weapon:                          5
widow's peak:                    5
cusp:                            5
razorblade:                      5
cutting edge:                    6
pommel:                          6
knob:                            6
knife edge:                      6
fire ship:                       7
shaft:                           7
slasher:                         7
missile:                         7
Greek fire:                      7
missile:                         7
weapon of mass destruction:      7
light arm:                       7
WMD:                             7
gun:                             7
flamethrower:                    7
pike:                            7
brass knucks:                    7
knucks:                          7
brass knuckles:                  7
knuckles:                        7
W:                               7
tomahawk:                        7
hatchet:                         7
lance:                           7
knuckle duster:                  7
bow and arrow:                   7
projectile:                      7
sling:                           7
bow:                             7
stun baton:                      7
spear:                           7
stun gun:                        7
convexity:                       8
cutting implement:               8
convex shape:                    8
portion:                         8
part:                            8
handle:                          8
grip:                            8
hold:                            8
handgrip:                        8
reap hook:                       9
knife:                           9
sticker:                         9
dagger:                          9
axe:                             9
file:                            9
awl:                             9
lawn mower:                      9
mower:                           9
scissors:                        9
ax:                              9
sickle:                          9
cone shape:                      9
conoid:                          9
cone:                            9
reaping hook:                    9
pencil:                          9
arrowhead:                       9
knife:                           9
pair of scissors:                9
spatula:                         9
spatula:                         9
alpenstock:                      9
instrument:                      10
weapons system:                  11
implements of war:               11
arms:                            11
munition:                        11
weaponry:                        11
</code></pre>
<p>Now, as you may notice, there still a lot of tuning to do; for example it is pretty strange that &#8216;weapon of mass destruction&#8217; is more semantically related to &#8216;sword&#8217; than &#8216;dagger&#8217; <img src='http://sandropaganotti.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<p>Anyway I&#8217;m pretty pleased of the results of this small experiment thus I&#8217;m still far from my initial idea: calculate the weight of each word of the dictionary in relation to &#8216;good&#8217; and &#8216;bad&#8217; and use these weights to estimate the &#8216;mood&#8217; of some common trends in twitter.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/05/04/a-semantic-experiment-for-separate-good-from-bad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game of Life, introducing gray</title>
		<link>http://sandropaganotti.com/2010/04/02/game-of-life-introducing-gray/</link>
		<comments>http://sandropaganotti.com/2010/04/02/game-of-life-introducing-gray/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 22:13:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Algoritmi]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[game of life]]></category>
		<category><![CDATA[Processing]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=368</guid>
		<description><![CDATA[During the last hour I modified my previous version of Game Of life trying to reproduce the same behavior using an analogic discriminator. Instead of counting the number of neighbours I elaborate their medium color and use this value to decide the next rgb combination of the cell. In the following snippet the two versions [...]]]></description>
			<content:encoded><![CDATA[<p>During the last hour I modified my previous version of Game Of life trying to reproduce the same behavior using an analogic discriminator. Instead of counting the number of neighbours I elaborate their medium color and use this value to decide the next rgb combination of the cell. </p>
<p><span id="more-368"></span>In the following snippet the two versions (classic and analogic) are compared:</p>
<pre><code class="javascript">
//  Classic version:
  void compute(){
    int black_neighbours = 0;
    for(int z=0; z < neighbours.length; z++)
      if(neighbours[z].rgb == black)
        black_neighbours ++;  

    switch(black_neighbours){
      case 0:
      case 1:
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
        to_color(white);
        break;
      case 2:
        to_color(rgb);
        break;
      case 3:
        to_color(black);
        break;
    }
  } 

// Analogic version
  void compute(){
    int[] medium_color = new int[] {0,0,0};
    for(int z=0; z < neighbours.length; z++)
      for(int c=0; c < 3; c++)
        medium_color[c] = medium_color[c] + neighbours[z].rgb[c];

    int medium_tone = 0;
    for(int c=0; c < 3; c++){
      medium_color[c] = medium_color[c] / neighbours.length;
      medium_tone = medium_tone + medium_color[c];
    }  

    medium_tone = medium_tone / 3;

    if (medium_tone > 191 || medium_tone < 128 ){
      to_color(white);
    }else if(medium_tone > 159 ){
      to_color(rgb);
    }else{
      to_color(black);
    }
  }
</code></pre>
<p>Next I went a step further using &#8216;medium color&#8217; when the classic rules asked insted to keep the previous cell color. This lead to a general acceleration to white because the medium neighbours color is always more bright than pure black, to balance this behavior I expanded the range of medium_tones which results in black. Here&#8217;s the tuned code:</p>
<pre><code class="javascript">
  void compute(){
    int[] medium_color = new int[] {0,0,0};
    for(int z=0; z < neighbours.length; z++)
      for(int c=0; c < 3; c++)
        medium_color[c] = medium_color[c] + neighbours[z].rgb[c];

    int medium_tone = 0;
    for(int c=0; c < 3; c++){
      medium_color[c] = medium_color[c] / neighbours.length;
      medium_tone = medium_tone + medium_color[c];
    }  

    medium_tone = medium_tone / 3;

    if (medium_tone > 191 || medium_tone < 80 ){
      to_color(white);
    }else if(medium_tone > 159 ){
      to_color(medium_color);
    }else{
      to_color(black);
    }
  }
</code></pre>
<p>Now <a href="http://www.youtube.com/watch?v=QheZEcI5bv4">a short video</a> of this new behavior:</p>
<p><object width="640" height="505"><param name="movie" value="http://www.youtube.com/v/QheZEcI5bv4&#038;hl=it_IT&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/QheZEcI5bv4&#038;hl=it_IT&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="505"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/04/02/game-of-life-introducing-gray/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A processing.org Game of Life</title>
		<link>http://sandropaganotti.com/2010/03/20/a-processing-org-game-of-life/</link>
		<comments>http://sandropaganotti.com/2010/03/20/a-processing-org-game-of-life/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 17:13:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Algoritmi]]></category>
		<category><![CDATA[game of life]]></category>
		<category><![CDATA[Jhon Conway]]></category>
		<category><![CDATA[Processing]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=325</guid>
		<description><![CDATA[Everybody knows the popular Game of Life created by Jhon Conway and becamed famous after been published by Martin Gardner on Scientific American in 1970. It is essentially a cellular automation algorithm with a very few simple rules that determinate how to grow a pool of one-pixel-shaped organisms layed upon a 2D matrix. Here&#8217;s the [...]]]></description>
			<content:encoded><![CDATA[<p>Everybody knows the popular <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Game of Life</a> created by <a href="http://en.wikipedia.org/wiki/John_Horton_Conway" target="_blank">Jhon Conway</a> and becamed famous after been published by <a href="http://en.wikipedia.org/wiki/Martin_Gardner" target="_blank">Martin Gardner</a> on <a href="http://ddi.cs.uni-potsdam.de/HyFISCH/Produzieren/lis_projekt/proj_gamelife/ConwayScientificAmerican.htm" target="_blank">Scientific American</a> in 1970. It is essentially a cellular automation algorithm with a very few simple rules that determinate how to grow a pool of one-pixel-shaped organisms layed upon a 2D matrix.</p>
<p><span id="more-325"></span>Here&#8217;s the rules:</p>
<ul>
<li>if the organism has more than 3 or fewer than 2 neighbours it dies;</li>
<li>if the organism has 2 or 3 neighbours it survives;</li>
<li>if a white cell in the matrix is sorrounded by exactly 3 neighbours it became a living organism.</li>
</ul>
<p>I&#8217;ve implemented this Game Of Life using Processing language and trying to push all of the game logic within the organism class in order to really simulate a cellular behavior, here&#8217;s the class:</p>
<pre><code class="javascript">class Spot{
  int[]   rgb, rgb_next;
  int     x,y;
  Spot[]  neighbours;

  Spot(int gx, int gy, int[] c){
    rgb      = c;
    rgb_next = new int[3];
    x       = gx;
    y       = gy;
  }

  void set_neighbors(Spot[][] grid){
    int xp = (x+1 == grid.length ? 0 : x+1);
    int xm = (x-1 == -1 ? grid.length - 1 : x-1);
    int yp = (y+1 == grid[0].length ? 0 : y+1);
    int ym = (y-1 == -1 ? grid[0].length - 1 : y-1);

    neighbours = new Spot[] {  grid[xm][ym], grid[xm][y ], grid[xm][yp],
                               grid[x ][ym],               grid[x ][yp],
                               grid[xp][ym], grid[xp][y ], grid[xp][yp]
                            };
  }

  void compute(){
    int black_neighbours = 0;
    for(int z=0; z &lt; neighbours.length; z++)
      if(neighbours[z].rgb == black)
        black_neighbours ++;  

    switch(black_neighbours){
      case 0:
      case 1:
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
        to_color(white);
        break;
      case 2:
        to_color(rgb);
        break;
      case 3:
        to_color(black);
        break;
    }
  } 

  void advance(){
    rgb = rgb_next;
    rgb_next = new int[3];
  }

  void draw(int bw,int bh){
     fill(rgb[0],rgb[1],rgb[2]);
     rect(x*bw,y*bh,bw,bh);
  }

  void to_color(int[] c){ rgb_next = c; }
}
</code></pre>
<p>There are three methods that worth a look:</p>
<ul>
<li><strong>set_neighbors</strong>:<br />
which determinates the sourronding neighbors (as the method name states) by creating an array of pointer to the closest organisms using the matrix passed as parameter as a reference. The first four lines are needed in order to eliminate the boundaries by linking each edge of the matrix to the opposite one.</li>
<li><strong>compute</strong>:<br />
which implements the real logic of the Game, it is divided into two steps, the first part calculates the number of alive neighbors sorrounding the organism and the second one applies the rules stated above.</li>
<li><strong>advance</strong>:<br />
due the fact that all of the organisms need to be processed before each of them can switch to the new state, the Spot class record the result of the &#8216;compute&#8217; method inside a different variable and then, when advance is invoked, it moves this result to the &#8216;live&#8217; variable.</li>
</ul>
<p>Here&#8217;s a short video of my script in action, the source code is, as usually, <a href="http://github.com/sandropaganotti/processing-game-of-life" target="_blank">available on my github account</a>:</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="660" height="405" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/LcHvyVpdnEk&amp;hl=it_IT&amp;fs=1&amp;rel=0&amp;border=1" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="660" height="405" src="http://www.youtube.com/v/LcHvyVpdnEk&amp;hl=it_IT&amp;fs=1&amp;rel=0&amp;border=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/03/20/a-processing-org-game-of-life/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Language switch</title>
		<link>http://sandropaganotti.com/2010/03/03/language-switch/</link>
		<comments>http://sandropaganotti.com/2010/03/03/language-switch/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 22:40:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Annunci]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=321</guid>
		<description><![CDATA[After a lot of reasonings I come to the decision to switch the language of this blog from italian to english, this change is going to cost me more time every time I decide to post something but it will also work as a training center for my foreign language skills. Plus it is probable [...]]]></description>
			<content:encoded><![CDATA[<p>After a lot of reasonings I come to the decision to switch the language of this blog from italian to english, this change is going to cost me more time every time I decide to post something but it will also work as a training center for my foreign language skills. Plus it is probable that most (if not all) of my current followers will keep reading and understand english posts while new non-italian readers may be attracted due to this change.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/03/03/language-switch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Abacus, Pierre Hérigone e la mnemotecnica</title>
		<link>http://sandropaganotti.com/2010/02/28/abacus-pierre-herigone-e-la-mnemotecnica/</link>
		<comments>http://sandropaganotti.com/2010/02/28/abacus-pierre-herigone-e-la-mnemotecnica/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 16:31:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Librerie]]></category>
		<category><![CDATA[abacus]]></category>
		<category><![CDATA[Hérigone]]></category>
		<category><![CDATA[mnemotecnica]]></category>

		<guid isPermaLink="false">http://sandropaganotti.com/?p=306</guid>
		<description><![CDATA[Ho recentemente acquistato un libro che mi stà regalando una serie di spunti per interessanti approfondimenti e delle simpatiche occasioni per scrivere due righe di codice. Il libro in questione si chiama &#8220;Enigmi e giochi matematici&#8221; di Martin Gardner e raccoglie gli articoli che lo stesso Martin pubblicò negli anni sulla rivista Scientific American. Il [...]]]></description>
			<content:encoded><![CDATA[<p>Ho recentemente acquistato un libro che mi stà regalando una serie di spunti per interessanti approfondimenti e delle simpatiche occasioni per scrivere due righe di codice. Il libro in questione si chiama &#8220;<a href="http://www.ibs.it/code/9788817127479/gardner-martin/enigmi-giochi-matematici.html" target="_blank">Enigmi e giochi matematici</a>&#8221; di <a href="http://it.wikipedia.org/wiki/Martin_Gardner" target="_blank">Martin Gardner</a> e raccoglie gli articoli che lo stesso Martin pubblicò negli anni sulla rivista Scientific American.</p>
<p><span id="more-306"></span></p>
<p>Il capitolo numero 11 tratta di mnemotecnica, la disciplina che studia il modo di memorizzare lunghe sequenze di numeri, e tratta del metodo di <a href="http://en.wikipedia.org/wiki/Herigone%27s_mnemonic_system" target="_blank">Pierre Hérigone</a>, che può essere riassunto nel seguente modo:</p>
<ol>
<li>Associa le cifre del numero che vuoi memorizzare a delle consonanti secondo <a href="http://it.wikipedia.org/wiki/Mnemotecnica#La_conversione_fonetica" target="_blank">una tabella nota</a>; ad esempio la temperatura di ebollizione del mercurio, 357°C, diverrebbe mlk;</li>
<li>Trova una parola che contenga quelle consonanti in quell&#8217;ordine (senza altre &#8216;consonanti di disturbo in mezzo&#8217;); ad esempio per mlk andrebbe benissimo milk, mentre non andrebbe bene multik;</li>
<li>Associa la parola appena trovata ad una frase che in qualche modo leghi con il significato originario della cifra, possibilmente in modo che la frase risultante contenga uno stimolo visuale; ad esempio si può immaginare un allevatore stupito dal fatto che le sue mucche producano mercurio invece che latte.</li>
<li>Se la cifra dovesse essere molto lunga utilizza una sequenza di più parole seguendo lo schema appena descritto.</li>
</ol>
<p>Nel tempo libero stò cercando di trasporre questi quattro semplici passaggi all&#8217;interno di una gemma: <a href="http://rubygems.org/gems/abacus" target="_blank">abacus</a>, della quale ho rilasciato giusto oggi la versione 0.0.1; vediamo come si usa:</p>
<pre><code class="ruby">&gt;&gt; require 'abacus'
=&gt; true
&gt;&gt; include Abacus
=&gt; Object
&gt;&gt; number = HerigoneNumber.find_by_number(357)
=&gt; #&lt;Abacus::HerigoneNumber id: 19081, system: "default", number: 357&gt;
&gt;&gt; number.article_keys.map{|article_key| article_key.the_key}
=&gt; ["hemlock", "milk", "milky"]
</code></pre>
<p>Per poter funzionare Abacus utilizza un database sqllite che crea all&#8217;interno della cartella home dell&#8217;utente (il percorso in realtà è configurabile, ma per questi dettagli vi rimando <a href="http://github.com/sandropaganotti/Abacus/blob/master/README.markdown" target="_blank">alle note di installazione su github</a>) e nel quale struttura il/i dizionari di riferimento.</p>
<p>Abacus implementa un parser (molto base ad oggi) <a href="http://xdxf.sourceforge.net/" target="_blank">XDXF</a>, un formato open per la memorizzazione di dizionari: esistono già parecchie opere convertite più o meno bene in questo formato che possono essere <a href="http://xdxf.revdanica.com/down/" target="_blank">scaricate gratuitamente</a>, io ad esempio ho utilizzato <a href="http://downloads.sourceforge.net/xdxf/comn_sdict05_eng_eng_main.tar.bz2" target="_blank">questo dizionario base di inglese</a>:</p>
<pre><code># da shell:
sudo gem install abacus
wget http://downloads.sourceforge.net/xdxf/comn_sdict05_eng_eng_main.tar.bz2
tar -xjvf comn_sdict05_eng_eng_main.tar.bz2
abacus db:create
abacus db:xdxf:import  eng_eng_main/dict.xdxf
abacus db:herigone:generate
</code></pre>
<p>La sfida più interessante di questo piccolo progetto è stata mantenere delle performances adeguate durante la sessione di traduzione numero -&gt; parola, per fare questo in fase di import (con il comando db:herigone:generate) la gemma traduce ogni lemma del dizionario nel suo corrispettivo numerico rendendo la fase di ricerca una semplice SELECT su di un campo indicizzato.</p>
<p>In futuro vorrei estendere questo piccolo progetto aggiungendo due funzionalità di aggregazione semantica: in caso di sequenze di cifre lunghe mi piacerebbe infatti includere un generatore di linguaggio naturale con l&#8217;obiettivo creare una frase che almento nell&#8217;apparenza manifesti una certa correttezza (sarebbe bellissimo tradurre le prima 1000 cifre del PI in uno strampalato poema no?). Sarebbe inoltre interessante utilizzare <a href="http://wordnet.princeton.edu/" target="_blank">wordnet</a> per ridurre la variabilità semantica delle singole parole trovate a quanto di più vicino ad una parola che serva da &#8216;rappresentante logico&#8217; per la cifra in ingresso (ad esempio per 357 il rappresentante logico sarebbe &#8216;mercurio&#8217;).</p>
<p>Nel frattempo, per chiunque fosse interessato, i sorgenti della gemma sono disponibili <a href="http://github.com/sandropaganotti/Abacus" target="_blank">sul mio account di GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sandropaganotti.com/2010/02/28/abacus-pierre-herigone-e-la-mnemotecnica/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
