<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Petitesnouvelles&#039;s Blog</title>
	<atom:link href="http://petitesnouvelles.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://petitesnouvelles.wordpress.com</link>
	<description>automating everything in the wonderful *nix world</description>
	<lastBuildDate>Thu, 05 Jan 2012 09:34:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='petitesnouvelles.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/0097416d0ecaa5a4ea06c522110acf76?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Petitesnouvelles&#039;s Blog</title>
		<link>http://petitesnouvelles.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://petitesnouvelles.wordpress.com/osd.xml" title="Petitesnouvelles&#039;s Blog" />
	<atom:link rel='hub' href='http://petitesnouvelles.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Gprof2dot</title>
		<link>http://petitesnouvelles.wordpress.com/2009/12/06/gprof2dot/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/12/06/gprof2dot/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 03:17:01 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[elisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=166</guid>
		<description><![CDATA[Profiling I want to share with you a nice trick which, even if not fundamental, is still very useful. You can also use this to impress your girlfriend. Sometimes profiling is necessary to understand which part of our code are taking so long. Python offer different alternatives, I advice you to read the official python [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=166&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Profiling</h3>
<p>I want to share with you a nice trick which, even if not fundamental, is still very useful.<br />
You can also use this to impress your girlfriend.</p>
<p>Sometimes profiling is necessary to understand which part of our code are taking so long.<br />
Python offer different alternatives, I advice you to read the <a href="http://docs.python.org/library/profile.html"> official python documentation </a> to get an idea.</p>
<h3>Gprof2Dot</h3>
<p>Another very nice thing is <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot"> gprof2dot </a>.<br />
This little program takes into input profiling data in many different formats and converts it to a dot file, keeping all the valuable informations.</p>
<p>As you can see for example <a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png"> here </a>.<br />
You also need to have <a href="http://www.graphviz.org/Download.php"> graphviz </a> to be able to actually generate the final graph.</p>
<h3>Scripting and emacs integration</h3>
<p>Given that I want to automate it and I want to use it also from emacs I wrote a simple bash script:<br />
<pre class="brush: bash;">
#!/bin/bash
FNAME=$1
if [ ! -f $FNAME ]
then
    echo &amp;quot;file $FNAME not found, executing from $PWD&amp;quot;
    exit 1
fi
# discard filename
shift

# change those variables as you prefer
STATS=&amp;quot;output.pstats&amp;quot;
TYPE=png
OUT=output.$TYPE
OPEN=&amp;quot;open&amp;quot;

# $@ collect all the arguments for the python script
# it doens't contain the file name after the shift
python -m cProfile -o $STATS $FNAME $@
gprof2dot.py -f pstats $STATS | dot -T$TYPE -o $OUT
rm $STATS
$OPEN $OUT
</pre></p>
<p>You can find this script also in <a href="http://github.com/AndreaCrotti/Emacs-conf/blob/master/.emacs.d/scripts/gprofile.sh"> my emacs configuration </a>.</p>
<p>Now we&#8217;re almost done, just put this somewhere in the emacs <em>exec-path</em> and you&#8217;re ready to use it!<br />
Just press Meta-! on a python buffer and launch &#8220;gprofile.sh python_file.py [extra args..]&#8220;</p>
<p>To automate even more this little elisp functions does that for you:<br />
<pre class="brush: plain;">
(defun gprof ()
  (interactive)
  (shell-command (concat &amp;quot;gprofile.sh &amp;quot; buffer-file-name)))
</pre></p>
<p>But at the moment it doesn&#8217;t take arguments for the script (will fix it soon).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/166/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=166&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/12/06/gprof2dot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>elisp fun</title>
		<link>http://petitesnouvelles.wordpress.com/2009/12/02/elisp-fun/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/12/02/elisp-fun/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 13:37:58 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[elisp]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/2009/12/02/elisp-fun/</guid>
		<description><![CDATA[Problem As we all know programmers are lazy, repetition is the evil, we want to type as fast as possible. Using C-like languages you always need to put the comma in the end. Normally after the comma you also want to go to newline and indent, so why not put together those two things and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=155&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Problem</h3>
<p>As we all know programmers are lazy, repetition is the <em>evil</em>, we want to type as fast as possible.<br />
Using C-like languages you always need to put the comma in the end.</p>
<p>Normally after the comma you also want to go to newline and indent, so why not put together those two things and automate it?</p>
<p>If you also like <a href="http://yasnippet.googlecode.com/">yasnippet</a> then you&#8217;ll find this feature even nicer.<br />
I took from this feature <a href="http://www.macromates.com/"> textmate </a>, a wonderful text editor which comes with this setting by default.<br />
As we&#8217;ll see we don&#8217;t need many lines of elisp code to end up with a much more powerful and flexible version of this nice feature.</p>
<h3>Solution</h3>
<h4>newline-force</h4>
<p>We first define a first function <em>newline-force</em><br />
Here it is:</p>
<p><pre class="brush: plain;">
(defun newline-force()
  &quot;Goes to newline leaving untouched the rest of the line&quot;
  (interactive)
  (progn
    (end-of-line)
    (newline-and-indent)))
</pre></p>
<p>This function goes to end of line and calls the predefined function <em>newline-and-indent</em>, which goes to newline and indent according to mode<br />
In more detail:</p>
<ul>
<li> <em>interactive</em>: function is available for user</li>
<li> <em>progn</em>: executes a sequence of disjointed operations</li>
</ul>
<p><span id="more-155"></span></p>
<h3>newline-force-close</h3>
<p>The newline-force-close function before going to newline adds a closing char at the end.<br />
We have to consider some more cases:</p>
<ul>
<li> we are in the beginning of the buffer</li>
<li> we already have the closing char inserted</li>
</ul>
<p><pre class="brush: plain;">
(defun newline-force-close()
  (interactive)
  (end-of-line)
  (let ((closing-way (assoc major-mode newline-force-close-alist2))
        closing-char)
    ;; Setting the user defined or the constant if not found
    (if (not closing-way)
	(progn
	  (message &quot;closing char not defined for this mode, using default&quot;)
	  (setq closing-char default-closing-char))
      (setq closing-char (cdr closing-way)))
    (when (not (bobp))
      ;; if we're at beginning of buffer, the backward-char will beep
      ;; :( This works even in the case of narrowing (e.g. we don't
      ;; look outside of the narrowed area.
      (when (not (looking-at closing-char))
 	(insert closing-char))
      (newline-force))))
</pre></p>
<p>Using the variable <em>major mode</em> we do a lookup in the association list <em>newline-force-close-alist</em>.<br />
If nothing is found we use the default closing char.</p>
<p>Here below there are the two variables needed.<br />
When defining some default values which shouldn&#8217;t change usign <em>defconst</em> is better than setting the symbol with setq.<br />
Using <em>defconst</em>, <em>defvar</em>, <em>defun</em> or <em>defcustom</em> allows you to add a docstring to your symbols.</p>
<p>This is very useful and that&#8217;s why emacs is also called the &#8220;self documenting editor&#8221;.</p>
<p>Here below is the association list, which is simply it&#8217;s a list of <strong>conses</strong>.</p>
<p><pre class="brush: plain;">
(defconst default-closing-char &quot;;&quot;
  &quot;default closing char, change in newline-force-close-alist if needed&quot;)

(setq newline-force-close-alist
  '((python-mode . &quot;:&quot;)
   (html-mode . &quot; &lt;br&gt;&quot;)))
</pre></p>
<p>Now last step, we bind the two defined functions to a pair of key</p>
<p><pre class="brush: plain;">
(global-set-key (kbd &quot;M-RET&quot;) 'newline-force)
(global-set-key [M-S-return] 'newline-force-close)
</pre></p>
<p>In this way we bind globally the two functions o Meta-Return and Meta-Shift-Return.<br />
If you instead prefer to add it only for certain modes than you need to add hooks to your modes, and use <em>local-set-key</em>.</p>
<p>See also <a href="http://groups.google.com/group/comp.emacs/browse_thread/thread/dd41c46d06658d5d#">this discussion</a>, which is where this code comes from.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/155/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/155/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=155&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/12/02/elisp-fun/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Github behind a proxy</title>
		<link>http://petitesnouvelles.wordpress.com/2009/04/10/github-behind-a-proxy/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/04/10/github-behind-a-proxy/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 09:33:22 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=135</guid>
		<description><![CDATA[Suppose you have an account to github and you want to use it even when you are behind a very restrictive proxy. The problem arises &#8220;only&#8221; when you have to push new patches, given that you can clone/pull even using http out of the box. Luckily the github guys give us the access to another [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=135&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Suppose you have an account to github and you want to use it even when you are behind a very restrictive proxy.<br />
The problem arises &#8220;only&#8221; when you have to push new patches, given that you can clone/pull even using http out of the box.</p>
<p>Luckily the github guys give us the access to another server (<em>ssh.github.com</em>) which basically listen on the port 443 and forwards </p>
<p>The informations to set up your environment can be found here:</p>
<p><a href="http://blog.codeslower.com/2008/8/Using-PuTTY-and-SSL-to-securely-access-GitHub-repositories-via-SSH"> github over proxy </a></p>
<p>And here you find:<br />
<a href="http://www.mtu.net/~engstrom/ssh-proxy.php"> corkscrew </a></p>
<p>This for example is my configuration (on Macosx but on linux is the same):</p>
<p><em>SSH_CONFIG</em><br />
<pre class="brush: python;">
Host gitproxy
  User git
  HostName ssh.github.com
  Port 443
  ProxyCommand corkscrew &lt;proxy&gt; &lt;port&gt; %h %p
  IdentityFile /Users/andrea/.ssh/github
</pre></p>
<p>Now in your git repository you can simply add the new remote<br />
<pre class="brush: python;">
git remote add git@gitproxy:&lt;repository&gt;
</pre></p>
<p>Another nice way to bypass the proxy (thanks Christian) is to use the GIT_PROXY_COMMAND variable, in this way</p>
<p><pre class="brush: python;">
export GIT_PROXY_COMMAND=/usr/local/bin/proxy-cmd.sh

#!/bin/bash
(echo &quot;CONNECT $1:$2 HTTP/1.0&quot;; echo; cat ) | socket proxy.unitn.it 3128 | (read a; read a; cat )
</pre></p>
<p>And now git for every push/pull will execute that script and bypass the proxy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=135&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/04/10/github-behind-a-proxy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Auto ssh over a set of machines</title>
		<link>http://petitesnouvelles.wordpress.com/2009/03/19/auto-ssh-over-lab-of-linux-machines/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/03/19/auto-ssh-over-lab-of-linux-machines/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 16:40:24 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/2009/03/19/auto-ssh-over-lab-of-linux-machines/</guid>
		<description><![CDATA[I just found out that every pc in the lab have sshd running and waiting at port 22. Now I immediately thought some nice and nasty things like: running the same process everywhere do some funny jokes to the users connected etc etc Or simply get a shell with all the laboratory software you need [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=128&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I just found out that every pc in the lab have sshd running and waiting at port 22.<br />
Now I immediately thought some nice and nasty things like:</p>
<li> running the same process everywhere </li>
<li> do some funny jokes to the users connected </li>
<p>etc etc</p>
<p>Or simply get a shell with all the laboratory software you need automatically.</p>
<p>If you also have on those machines a listening xorg then you could also use X11 programs over the ssh, which works like a charm. (ssh -Yc &#8220;hostname&#8221; &#8220;command&#8221; for example)</p>
<p>The only two &#8220;problems&#8221; are:</p>
<li> the need to insert the password every time </li>
<li> the need to accept the fingerprint for each new pc </li>
<p>Let&#8217;s see how to solve them.</p>
<p>First we generate a new key:<br />
<pre class="brush: python;">ssh-keygen -t dsa -f $HOME/.ssh/unilab</pre></p>
<p>Then we upload the public key to one of the pc&#8217;s, as long as the home directory is mounted over the network (of course) it doesn&#8217;t matter which one.<br />
<pre class="brush: python;"> scp $HOME/.ssh/unilab.pub utente@host:.ssh/ </pre></p>
<p>Last thing you need to add to the authorized keys your public key (on whatever lab pc you&#8217;re logged in).<br />
<pre class="brush: python;"> cat $HOME/.ssh/unilab.pub &amp;gt;&amp;gt; $HOME/.ssh/authorized_keys </pre></p>
<p>Now we can set a really nice configuration in our $HOME/.ssh/config.</p>
<p>Here it is:<br />
<pre class="brush: python;">
Host a10?pc*
  User &lt;youruser&gt;
  IdentityFile &lt;your private key&gt;
  Port 22
  StrictHostKeyChecking no
</pre></p>
<p>And that&#8217;s it, if for example you now do<br />
<pre class="brush: python;"> ssh a105pc08 </pre><br />
ssh will find the matching on the regular expression and use those settings, letting you login automatically.</p>
<p>But we&#8217;re not over, how do we know where sshd is up and running?</p>
<p><span id="more-128"></span><br />
We&#8217;ll we can do a scan of a list of hosts given in input until we find an ssh up and running</p>
<p><pre class="brush: python;">
#!/usr/bin/env bash
# usage cluster.sh &lt;command&gt; 
# gives you the first possible shell launching the optional command

NC=&quot;/opt/local/bin/nc&quot;
FPING=&quot;/opt/local/sbin/fping&quot;

function get_first_shell {
	for host in $(lab5)
	do
    echo &quot;analyzing $host&quot;
    if $FPING -t50 $host &gt; /dev/null
      then 
  		if $NC -z -w 1 $host 22 &gt; /dev/null
  		then
  	    open_shell $host $1 &amp;&amp; break
  		fi
		fi
	done
}

function open_shell {
  # -t useful lo launch remote interpreters
	ssh -t $1 $2; return
}

function lab5 {
	for ((i=1; $i &lt; 40; i=$i+1))
	do
		echo &quot;a105pc$(printf '%02d' $i)&quot;
	done
}

get_first_shell $1
</pre></p>
<p>This is just an example, it&#8217;s enough to substitute the lab5 function with a static list or a generator of your hostnames/ip address you want to scan.<br />
The function get_first_shell first checks that the host is up with  fping  and then checks that the port 22 is open with  netcat , and that&#8217;s it!<br />
This is an example of execution:</p>
<p><pre class="brush: python;">
andreaMb:~ andrea$ get_first_shell 
analyzing a105pc01
analyzing a105pc02
analyzing a105pc03
analyzing a105pc04
analyzing a105pc05
analyzing a105pc06
analyzing a105pc07
analyzing a105pc08
Linux austudNONETWORK 2.6.24-23-generic #1 SMP Thu Nov 27 18:44:42 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
Last login: Thu Mar 19 12:22:31 2009 from 172.31.121.180
andrea.crotti@a105pc08:~$
</pre></p>
<p>Now we have the automatic access, <strong>GREAT</strong>!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/128/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=128&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/03/19/auto-ssh-over-lab-of-linux-machines/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Find that pc</title>
		<link>http://petitesnouvelles.wordpress.com/2009/01/27/find-that-pc/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/01/27/find-that-pc/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 10:15:48 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[dhcp]]></category>
		<category><![CDATA[sed]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/2009/01/27/find-that-pc/</guid>
		<description><![CDATA[Assume that you are in a big network where the ip addresses are given via dhcp. Assume also that you want to be able to communicate with the same pc which can change the ip address every time it reboots. One easy and &#8220;legal&#8221; way to always find is using netbios, a protocol that makes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=124&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Assume that you are in a big network where the ip addresses are given via dhcp.<br />
Assume also that you want to be able to communicate with the same pc which can change the ip address every time it reboots.</p>
<p>One easy and &#8220;legal&#8221; way to always find is using netbios, a protocol that makes a computer shout over the network it&#8217;s pairing Name -&gt; IP address.</p>
<p>For windows and macosx this works out of the box, for linux/bsd machines you can just set a minimal smb.conf like this.</p>
<p><pre class="brush: python;">
[global]
	workgroup = WORKGROUP
	server string = My Samba Server
	netbios name = koala
</pre></p>
<p>It&#8217;s useful to have the correct pairing right in /etc/hosts for every kind of command line program that doesn&#8217;t speak netbios.<br />
So we&#8217;ll use <em>nmblookup</em> and sed for the task.<br />
Just substitute the netbios name that you need here:<br />
<pre class="brush: python;">
export koala=$(nmblookup koala | sed -n 2p | cut -d ' ' -f 1)
# Now I can substitute the right ip in /etc/hosts
sed &quot;/koala/ s/.*/$koala\tkoala&quot; &lt; /etc/hosts &gt; /tmp/hosts
sudo mv /etc/hosts /etc/hosts.bak
sudo mv /tmp/hosts /etc/hosts
</pre></p>
<p>Maybe you also want to modify <em>sudoers</em> to use it without inserting a password each time.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/124/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=124&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/01/27/find-that-pc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Automating the interaction</title>
		<link>http://petitesnouvelles.wordpress.com/2009/01/22/automating-the-interaction/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/01/22/automating-the-interaction/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 20:53:31 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[ghc]]></category>
		<category><![CDATA[ghci]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[textmate]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=122</guid>
		<description><![CDATA[A pretty nice feature of shell scripting is &#8220;&#60;&#60;&#34; operator. It allows basically to launch interactive commands within a bash script. For example I wanted to add a small but very useful function to textmate, I want to be able to know all the possible informations about a whatever function or data type. The default [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=122&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A pretty nice feature of shell scripting is &#8220;&lt;&lt;&quot; operator.<br />
It allows basically to launch interactive commands within a bash script.</p>
<p>For example I wanted to add a small but very useful function to textmate, I want to be able to know all the possible informations about a whatever function or data type.</p>
<p>The default info function in the haskell bundle unfortunately is only able to retrieve informations about prelude functions or functions used with the full path.<br />
(eg <em> Data.List.lookup </em> and not simply <em> lookup </em>).</p>
<p>Using ghci I should load the file (which automatically loads also the needed libraries) and type :info.<br />
This is really easily done using &#8220;&lt;&lt;&quot;.</p>
<p>I added a command &#8220;info about&#8221; with the following code in my haskell bundle and now if the file is correct (it compiles) you are sure that you&#8217;ll get the informations about the function you&#8217;re looking for.</p>
<p><pre class="brush: python;">
GHCI &lt;&lt; EOF
:load $TM_FILEPATH
:info ${TM_SELECTED_TEXT:-$TM_CURRENT_WORD}
EOF
</pre></p>
<p>I also think that there should be a better way to communicate with ghci (and using System.Enviroment to get the arguments) but I didn&#8217;t find any, this solution even if not really elegant works pretty well.</p>
<p>This &#8220;approach&#8221; can be used also with many interpreters, sometimes I find it really useful.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/122/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=122&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/01/22/automating-the-interaction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Life behing a proxy</title>
		<link>http://petitesnouvelles.wordpress.com/2009/01/19/life-behing-a-proxy/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/01/19/life-behing-a-proxy/#comments</comments>
		<pubDate>Sun, 18 Jan 2009 23:56:30 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[ftp]]></category>
		<category><![CDATA[macosx]]></category>
		<category><![CDATA[macports]]></category>
		<category><![CDATA[openvpn]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[rsync]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/2009/01/19/life-behing-a-proxy/</guid>
		<description><![CDATA[Staying behind a proxy can be very annoying, with macosx it&#8217;s nice and easy to set a global proxy. Unfortunately command line programs don&#8217;t care about those settings, so we have to manually set them every time. With the script you&#8217;ll find below we set globally the proxy for ftp, http, rsync and subversion: To [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=119&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Staying behind a proxy can be very annoying, with macosx it&#8217;s nice and easy to set a global proxy.<br />
Unfortunately command line programs don&#8217;t care about those settings, so we have to manually set them every time.</p>
<p>With the script you&#8217;ll find below we set globally the proxy for ftp, http, rsync and subversion:</p>
<p><span id="more-119"></span><br />
<pre class="brush: python;">
# Set your own variables in PROXY, PROXY_PORT and USER
USER=&quot;user&quot;
PROXY=&quot;myproxy&quot;
PROXY_PORT=&quot;proxy_port&quot;
export RSYNC_PROXY=$PROXY:$PROXY_PORT
export ftp_proxy=$PROXY:$PROXY_PORT
export http_proxy=&quot;http://$PROXY:$PROXY_PORT&quot;
export ALL_PROXY=$http_proxy

USRHOME=&quot;/Users/$USER&quot;
SVN=&quot;$USRHOME/.subversion/servers&quot;
# checking if not already set, not totally safe
if ! grep $PROXY $SVN
  then
    cp $SVN &quot;$USRHOME/.subversion/servers.bak&quot;
    chown $USER $SVN.bak
    sed -e &quot;
    /\[global\]/ a\
    http-proxy-host = $PROXY\\
    http-proxy-port = $PROXY_PORT\
    &quot; &lt; $SVN.bak &gt; $SVN
fi
</pre></p>
<p>To use it just save it somewhere (I suggest <strong>$HOME/.[position]</strong>) and whenever you need it for example macports just type<br />
<pre class="brush: python;">
source $HOME/.[position]
</pre></p>
<p>For subversion I imagine that you also need to restore the situation when you&#8217;re not proxyed.<br />
A simple grep command like:<br />
<pre class="brush: python;">
grep -v '^http-proxy*' .subversion/servers
</pre><br />
will do the trick.</p>
<p>Another program you may need to run behind a proxy (at least I do) is <a href="http://openvpn.net/"> openvpn </a>.<br />
Openvpn it&#8217;s great and breaks through anything, but when proxed it needs a few changes to the default configuration.<br />
In a fairly simple configuration we need to add/modify:<br />
<pre class="brush: python;">
proto tcp-client   # doens't work with udp
port 443           # necessary only if for example only 80 and 443 are available
http-proxy &lt;proxy&gt; &lt;port&gt; &lt;file&gt; &lt;modality&gt;
</pre></p>
<p>From the openvpn 2.1 manual<br />
<em><br />
  &#8211;http-proxy server port [authfile|'auto'] [auth-method]<br />
Connect to remote host through an HTTP proxy at address server and port port. If HTTP Proxy-Authenticate is required, authfile is a file containing a username and password on 2 lines, or &#8220;stdin&#8221; to prompt from console.<br />
auth-method should be one of &#8220;none&#8221;, &#8220;basic&#8221;, or &#8220;ntlm&#8221;.<br />
The auto flag causes OpenVPN to automatically determine the auth-method and query stdin or the management interface for username/password credentials, if required. This flag exists on OpenVPN 2.1 or higher.<br />
</em></p>
<p>My idea with macosx was to get the global variables and automatic changing global configurations there are a couple of problems that I haven&#8217;t solved:</p>
<li> how to stick &#8220;actions&#8221; when I change network position </li>
<li> how to set variables for every shell even if they are not children of the caller </li>
<p>I would also really like to authenticate to the coova login page with mechanize or another automatic system but I still have troubles when I get to https connections.</p>
<p>So if you have any idea to improve automatism you&#8217;re welcome to comment, thanks and hope that this script actually helps someone.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/119/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=119&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/01/19/life-behing-a-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Multilanguage and multiparadigm navigator 3/n Python implementation</title>
		<link>http://petitesnouvelles.wordpress.com/2009/01/14/multilanguage-and-multiparadigm-navigator-3n-python-implementation/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/01/14/multilanguage-and-multiparadigm-navigator-3n-python-implementation/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 18:05:54 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=94</guid>
		<description><![CDATA[Now it starts the interesting part, we&#8217;ll actually go to see one language a time the real program. The program that given the input we&#8217;ve seen in the previous chapter gives us a kind of useful output. The program is divided in a few different parts: Parsing command line options Setting up data structures needed [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=94&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now it starts the interesting part, we&#8217;ll actually go to see one language a time the real program.<br />
The program that given the input we&#8217;ve seen in the previous chapter gives us a kind of useful output.</p>
<p>The program is divided in a few different parts:</p>
<li> Parsing command line options </li>
<li> Setting up data structures needed </li>
<li> Executing Floyd Warshall algorithm </li>
<li> Building the output and writing it to file </li>
<p></p>
<p>Optionally we can also graph the result using the library <a href="http://code.google.com/p/pydot/" title="pydot"> pydot </a> and passing the &#8220;-d&#8221; flag from the command line.</p>
<p><span id="more-94"></span><br />
The <a href="http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm" title="Floyd"> Floyd Warshall </a> algorithm is the core of the program, instead of calculating the shortest path from each city of the path we just calculate using dynamic programming techniques the shortest distances between all the nodes.</p>
<p>It maybe slower if we just want the shortest path between two cities but it adds no more computational complexity when the path length grows.</p>
<p><pre class="brush: python;">
def floyd_warshall(cities, dist):
    &quot;&quot;&quot;returns a dictionary containing the minumum distances between cities&quot;&quot;&quot;
    dim = len(cities)
    old = new = {}
    # first cycle to set the initial configuration
    for c1 in cities:
        for c2 in cities:
            old[(c1, c2)] = [dist[(c1, c2)], [c2]]
    # ranging over the distance between nodes
    for k in range(1, dim):
        for c1 in cities:
            for c2 in cities:
                diretto = old[(c1, c2)]
                before = old[(c1, cities[k-1])]
                after = old[(cities[k-1], c2)]
                if diretto[0] &lt;= (before[0] + after[0]):
                    new[(c1, c2)] = diretto
                else:
                    new[(c1, c2)] = [before[0] + after[0], before[1]+after[1]]
        old = new
    return new
</pre></p>
<p>We use two dictionaries to calculate at each step what is the shortest distance at k-th step (with <em>k</em> steps between <em>c1</em> and <em>c2</em>).<br />
We want to save both the distance and the intermediate cities.</p>
<p>The rest of the code is pretty simple to understand, a nice thing (I believe) can be found here:<br />
<pre class="brush: python;">
for t1, t2 in zip(path, path[1:]):
</pre></p>
<p>In general using zip over a list and a list without the first element allows get all the pairs in order:<br />
<pre class="brush: python;">
In [76]: k = range(4)

In [77]: for t1, t2 in zip(k, k[1:]):
   ....:     print t1, t2
   ....:     
   ....:     
0 1
1 2
2 3
</pre></p>
<p>So we can execute our navigator program for a fairly simple input and get:<br />
<pre class="brush: python;">
./nav.py -d
GRICIGNANO.CANISTRO.BELLINO.FORCE.CONSIGLIO.AFRAGOLA.CASTELPOTO.GRICIGNANO.CASTELPOTO.GORIANO.CASTELPOTO.AFRAGOLA.FORCE
57
</pre></p>
<p>In the same folder the program has generated two png files (if it was able to use the pydot module): <em>path.png</em> and <em>pathgraph.png</em>.<br />
The first one shows the full map with distances between cities.</p>
<p>Red node is the starting city, yellow end node and green nodes are intermediate cities (left nodes if we don&#8217;t pass trough them).<br />
 click on the image to see it larger<br />
<a href="http://petitesnouvelles.files.wordpress.com/2009/01/path.png"> <img src="http://petitesnouvelles.files.wordpress.com/2009/01/path3.png?w=320&#038;h=246" alt="Path" height="246" width="320"></a></p>
<p>In this other png we actually in what order we go trough the map, in form <em> order(distance)</em>.<br />
<img src="http://petitesnouvelles.files.wordpress.com/2009/01/pathgraph1.png?w=348&#038;h=843" alt="Pathgraph" height="843" width="348"></p>
<p>Here there is the full source code:<br />
<pre class="brush: python;">

#!/usr/bin/env python

from copy import deepcopy
from sys import maxint
from sys import argv
from getopt import getopt

def parse_stradario(stradario):
    &quot;&quot;&quot;parses the file containing the map&quot;&quot;&quot;
    toparse = open(stradario).readline().split('.')
    idx = 0
    ncities = int(toparse[idx])
    cities = toparse[1 : ncities + 1]
    idx = ncities + 1
    # main data structure used
    dst = {}
    for jdx in range(0, ncities * ncities, ncities):
        for kdx in range(ncities):
            val = int(toparse[idx + jdx + kdx])
            if val &lt; 0:
                val = maxint
            dst[(cities[jdx / ncities], cities[kdx])] = val
    return ncities, cities, dst

def parse_percorso(percorso):
    &amp;quot;&amp;quot;&amp;quot;parses the path&amp;quot;&amp;quot;&amp;quot;
    return file.readline(open(percorso,'r')).split('.')[:-1]

def floyd_warshall(cities, dist):
    &amp;quot;&amp;quot;&amp;quot;returns a dictionary containing the minumum distances between cities&amp;quot;&amp;quot;&amp;quot;
    dim = len(cities)
    old = new = {}
    # first cycle to set the initial configuration
    for c1 in cities:
        for c2 in cities:
            old[(c1, c2)] = [dist[(c1, c2)], [c2]]
    # ranging over the distance between nodes
    for k in range(1, dim):
        for c1 in cities:
            for c2 in cities:
                diretto = old[(c1, c2)]
                before = old[(c1, cities[k-1])]
                after = old[(cities[k-1], c2)]
                if diretto[0] &lt;= (before[0] + after[0]):
                    new[(c1, c2)] = diretto
                else:
                    new[(c1, c2)] = [before[0] + after[0], before[1]+after[1]]
        old = new
    return new
    
def draw(cities, dist, path):
    &amp;quot;&amp;quot;&amp;quot;draws the graphs&amp;quot;&amp;quot;&amp;quot;
    try:
        import pydot
    except Exception.ImportError:
        print &amp;quot;pydot not present, install it if you want to graph&amp;quot;
        return
    graph = pydot.Dot(graph_type='graph')
    nodes = []
    for c in cities:
        n = pydot.Node(c, label=c, color='black')
        if c == path[0]:
            n.set_color('red')
        elif c == path[-1]:
            n.set_color('yellow')
        elif c in path[1 : len(path)-1]:
            n.set_color('green')
        nodes.append(n)
        graph.add_node(n)
    for i in range(len(cities)):
        for j in range(i + 1, len(cities)):
            d = dist[(cities[i], cities[j])]
            if d &lt; maxint:
                e = pydot.Edge(nodes[i], nodes[j], weight=str(d), label=str(d))
                graph.add_edge(e)
    
    pathGraph = pydot.Dot(graph_type='digraph')
    # very nice way to enumerate couples of a list
    i = 1
    for t1, t2 in zip(path, path[1:]):
        e = graph.get_edge(t1, t2)
        w = 0
        # I could have more than one edge from get_edge
        if isinstance(e, list):
            w = e[0].get_weight()
        else:
            w = e.get_weight()
        e1 = pydot.Edge(pydot.Node(t1, label=t1), pydot.Node(t2, label=t2), label=str(i)+&amp;quot;(&amp;quot; + w + &amp;quot;)&amp;quot;)
        pathGraph.add_edge(e1)
        i += 1
    pathGraph.write_png('pathgraph.png')
    graph.write_png('path.png')

def usage():
    &amp;quot;&amp;quot;&amp;quot;docstring for usage&amp;quot;&amp;quot;&amp;quot;
    print &amp;quot;&amp;quot;&amp;quot;
    ./nav.py [-s stradario] [-p path] [-d]
    nav.py gets as input (optional) a map and a path chosen and outputs the shortest path,
    optionally with option [-d] it also creates two nice graphs with pydot and open them.
    &amp;quot;&amp;quot;&amp;quot;

def main():
    &amp;quot;&amp;quot;&amp;quot;Main function&amp;quot;&amp;quot;&amp;quot;
    strad = &amp;quot;stradario.txt&amp;quot;
    path = &amp;quot;percorso.txt&amp;quot;
    isdraw = False
    
    opts, args = getopt(argv[1:], &amp;quot;s:p:d&amp;quot;)
    for o,a in opts:
        if o in '-s':
            strad = a
        if o in '-p':
            path = a
        if o in '-d':
            isdraw = True

    n, cities, dist = parse_stradario(strad)
    min_dist = floyd_warshall(cities, dist)
    percorso = parse_percorso(path)
    final_dist = 0
    tappe = [percorso[0]]
    for i in range(len(percorso)-1):
        dst = min_dist[(percorso[i],percorso[i+1])]
        final_dist += dst[0]
        tappe += dst[1]
    print '.'.join(tappe)
    print final_dist
    if isdraw:
        draw(cities, dist, tappe)

if __name__ == '__main__':
    main()
</pre></p>
<p>I see that there are problems with the comments (every quote is translated into &#8220;&amp;quot&#8221; even if I put the source code in the  tag).<br />
I have this problem only with this python file, if you have an idea of the reason of that behavior please tell me.</p>
<p>As usual if you have any critique or doubt (or you find some bugs, sure they are plenty) you&#8217;re welcome to notice it.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/94/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=94&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/01/14/multilanguage-and-multiparadigm-navigator-3n-python-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>

		<media:content url="http://petitesnouvelles.files.wordpress.com/2009/01/path3.png" medium="image">
			<media:title type="html">Path</media:title>
		</media:content>

		<media:content url="http://petitesnouvelles.files.wordpress.com/2009/01/pathgraph1.png" medium="image">
			<media:title type="html">Pathgraph</media:title>
		</media:content>
	</item>
		<item>
		<title>Multilanguage and multiparadigm navigator 2/n Input generator</title>
		<link>http://petitesnouvelles.wordpress.com/2009/01/06/multilanguage-and-multiparadigm-navigator-2n/</link>
		<comments>http://petitesnouvelles.wordpress.com/2009/01/06/multilanguage-and-multiparadigm-navigator-2n/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 21:24:43 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=77</guid>
		<description><![CDATA[In this second post we&#8217;ll see how to implement correct and configurable input generator for our problem. This script is used to generate two simple output files in the form: Mapfile: [Number of cities] [List of cities] [Distance table] PathFile: [List of cities] both separated by dots. For example the map file could be: 5.CASALBELTRAME.FONTANILE.GASPERINA.INVERSO.MEANA.0.4.-1.-1.-1.4.0.8.6.9.-1.8.0.-1.-1.-1.6.-1.0.-1.-1.9.-1.-1.0. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=77&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this second post we&#8217;ll see how to implement correct and configurable input generator for our problem.</p>
<p>This script is used to generate two simple output files in the form:</p>
<li> Mapfile: [Number of cities] [List of cities] [Distance table]
<li> PathFile: [List of cities]
<p>both separated by dots.</p>
<p>For example the map file could be:</p>
<p> 5.CASALBELTRAME.FONTANILE.GASPERINA.INVERSO.MEANA.0.4.-1.-1.-1.4.0.8.6.9.-1.8.0.-1.-1.-1.6.-1.0.-1.-1.9.-1.-1.0.</p>
<p>And the path file:</p>
<p> INVERSO.CASALBELTRAME.MEANA.GASPERINA.INVERSO. </p>
<p>
The source code here below can also be downloaded together with a list of cities (necessary to make the randomization).</p>
<p><span id="more-77"></span><br />
This is the part of code that choose randomly a list of cities<br />
<pre class="brush: python;">
  rand_c = []
  jump_max = len(cities) / n_cit
  # FIXME: any smarter way to add many cities randomically picked from a list?
  start = randrange(jump_max)
  rand_c.append(cities[start].strip())
  for _ in range(n_cit - 1):
      start += randrange(jump_max)
      rand_c.append(cities[start].strip())
  return rand_c
</pre><br />
<br />
It takes a random jump value (not too large to make sure we don&#8217;t go &#8220;too far&#8221; and fetches the k-th city.</p>
<p>Another nice function (I think) is gen_table:<br />
<pre class="brush: python;">
  for i in range(n_cit):
      # setting to 0 we make sure the diagonal is filled of 0
      res[i] = [0] * n_cit
      for j in range(i):
          res[i][j] = res[j][i] = gen_distance()
</pre></p>
<p>In this part of the code we create a symmetric matrix only analyzing the lower triangle, with the diagonal already set as 0.<br />
The symmetric matrix is needed as long the distances between cities are of course symmetric.</p>
<p>The probability of having or not a connection between cities is given by the <em> grade </em> variable, as we see here:<br />
<pre class="brush: python;">
  def gen_distance():
      &quot;&quot;&quot;generates a random distance if threshold reached
      Otherwise no connection =&gt; -1&quot;&quot;&quot;
      if randrange(0, 11) &lt;= conn_grade:
          return randrange(DST_MIN, DST_MAX)
      else:
          return -1
</pre></p>
<p>Below you find the whole source, other possible settings are:</p>
<li> Number of cities
<li> Length of the path
<li> Output files
<p><pre class="brush: python;">
#!/usr/bin/env python

# This script generates the input file for the real program navigator,
# given a connection degree, the number of cities and the length
# of the path to calculate

import getopt
from random import randrange, choice
from sys import exit, argv, stdout

MAP_FILE = 'stradario.txt'
PATH_FILE = 'percorso.txt'
BADARGS = 3
DST_MIN = 1
DST_MAX = 10

def gen_cities(n_cit, fname='cities.txt'):
    &quot;&quot;&quot;Returns n cities picked casually from file fname&quot;&quot;&quot;
    cities = open(fname).readlines()
    # check if less cities than possible
    if n_cit &gt; len(cities):
        raise Exception(&quot;not enough cities&quot;)
    else:
        rand_c = []
        jump_max = len(cities) / n_cit
        # FIXME: any smarter way to add many cities randomically picked from a list?
        start = randrange(jump_max)
        rand_c.append(cities[start].strip())
        for _ in range(n_cit - 1):
            start += randrange(jump_max)
            rand_c.append(cities[start].strip())
        return rand_c


def gen_table(n_cit, conn_grade):
    &quot;&quot;&quot;Generates the table of distances between cities,
    it basically works on the lower triangular matrix
    automatically setting the upper part
    &quot;&quot;&quot;
    from operator import add
    def gen_distance():
        &quot;&quot;&quot;generates a random distance if threshold reached
        Otherwise no connection =&gt; -1&quot;&quot;&quot;
        if randrange(0, 11) &lt;= conn_grade:
            return randrange(DST_MIN, DST_MAX)
        else:
            return -1
    res = [None] * n_cit
    for i in range(n_cit):
        # setting to 0 we make sure the diagonal is filled of 0
        res[i] = [0] * n_cit
        for j in range(i):
            res[i][j] = res[j][i] = gen_distance()
    # FIXME heavy use of lambdas
    flat = reduce(lambda x, y: add(x, y), res)
    return '.'.join(map(lambda x: str(x), flat)) + '.'


def gen_map(cities, n_cit, conn_grade):
    &quot;&quot;&quot;creates the random map file&quot;&quot;&quot;
    st = '.'.join([str(n_cit), '.'.join(cities), gen_table(n_cit, conn_grade)])
    return st


def random_path(cities, num):
    &quot;&quot;&quot;creates a random path of length num using the array cities&quot;&quot;&quot;
    if len(cities) == 1:
        print &quot;no path possible&quot;
        return cities[0]
    i = 0
    path = []
    while i &lt; num:
        # FIXME if num &gt;&gt; len(cities) very inefficient
        new = choice(cities)
        # we just generate another instance if we get the same value
        if path and new == path[-1]:
            continue
        path.append(new)
        i += 1
    return path

def gen_path(cities, lenpath):
    &quot;&quot;&quot;writes the path obtained&quot;&quot;&quot;
    return '.'.join(random_path(cities, lenpath)) + '.'


def generate(n_cit, lenpath, grade, output):
    &quot;&quot;&quot;Generations of input and writing on the output files&quot;&quot;&quot;
    cities = gen_cities(n_cit)
    mappa, path = gen_map(cities, n_cit, grade), gen_path(cities, lenpath)
    output[0].write(mappa)
    output[1].write(path)
    

def usage():
    &quot;&quot;&quot;docstring for usage&quot;&quot;&quot;
    print &quot;&quot;&quot; ./gen_input.py [-n n_cities] [-r lenpath] [-g connection_grade] [stradario] [percorso] -o
        If -o is given it will print output to standard output
        All the parameters have already a default value, which is
        n_cities   =&gt; 10
        lenpath     =&gt; 10
        grade       =&gt; 5
        stradario   =&gt; &quot;stradario.txt&quot;
        percorso    =&gt; &quot;percorso.txt&quot;&quot;&quot;
    exit(BADARGS)

if __name__ == '__main__':
    opts, args = getopt.getopt(argv[1:], 'ohr:n:g:')
    # default value
    n_cities = npath = 10
    grade = 5                   # middle level of connection grade
    for o, a in opts:
        if o in ('-h'):
            usage()
        if o in ('-r'):
            npath = int(a)
        if o == '-n':
            n_cities = int(a)
        if o == '-g':
            grade = int(a)
            if grade &lt; 0 or grade &gt; 10:
                usage()
        if o == '-o':
            args = [stdout, stdout]
    if not args:
        args = [open(MAP_FILE, &quot;w&quot;), open(PATH_FILE, &quot;w&quot;)]
    if len(args) == 1:
        usage()
    generate(n_cities, npath, grade, args)
</pre></p>
<p>You will also need a cities text file, I just realized that I cannot upload zip or txt files, so for now I will paste some lines of the file I&#8217;m using, just paste it everything on a file and call it &#8216;cities.txt&#8217;.</p>
<p><pre class="brush: python;">
VILLAPUTZU
VILLAR
VILLARBASSE
VILLARBOIT
VILLAREGGIA
VILLARICCA
VILLAROMAGNANO
VILLAROSA
VILLASALTO
VILLASANTA
VILLASIMIUS
VILLASOR
VILLASPECIOSA
VILLASTELLONE
VILLATA
VILLAURBANA
VILLAVALLELONGA
VILLAVERLA
VILLENEUVE
VILLESSE
VILLETTA
VILLETTE
VILLIMPENTA
VILLONGO
VILLORBA
VILMINORE
VIMERCATE
VIMODRONE
VINADIO
VINCHIATURO
VINCHIO
VINCI
VINOVO
VINZAGLIO
VIOLA
VIONE
VIPITENO
VIRGILIO
VIRLE
VISANO
VISCHE
VISCIANO
VISCO
VISONE
VISSO
VISTARINO
VISTRORIO
VITA
VITERBO
VITICUSO
VITO
VITORCHIANO
VITTORIA
VITTORIO
VITTORITO
VITTUONE
VITULANO
VITULAZIO
VIU
VIVARO
VIVERONE
VIZZINI
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=77&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2009/01/06/multilanguage-and-multiparadigm-navigator-2n/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
		<item>
		<title>Get the k-th digit out of a number</title>
		<link>http://petitesnouvelles.wordpress.com/2008/12/29/get-the-k-th-digit-out-of-a-number/</link>
		<comments>http://petitesnouvelles.wordpress.com/2008/12/29/get-the-k-th-digit-out-of-a-number/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 10:27:19 +0000</pubDate>
		<dc:creator>petitesnouvelles</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://petitesnouvelles.wordpress.com/?p=55</guid>
		<description><![CDATA[One really common problem is to get the k-th digit out of a number. For example given the number 10210 we want to know what it the second digit. We&#8217;ll see how we can solve elegantly this problem in python. The simplest (and fastest) way is to trasform the number in string and list the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=55&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One really common problem is to get the k-th digit out of a number.<br />
For example given the number</p>
<p><strong>10210</strong></p>
<p>we want to know what it the second digit.</p>
<p>We&#8217;ll see how we can solve elegantly this problem in python.</p>
<p><span id="more-55"></span><br />
The simplest (and fastest) way is to trasform the number in string and list the chars obtained.</p>
<p><pre class="brush: python;">
&gt;&gt;&gt; n = 123123
&gt;&gt;&gt; map(int, list(str(n)))
[1, 2, 3, 1, 2, 3]
</pre></p>
<p>This is pretty nice but we may want a numerical way to get the digits, thanks to Carlo (on an italian python group) we can just use</p>
<p><pre class="brush: python;">
&gt;&gt;&gt; n=987654321 
&gt;&gt;&gt; list(reversed([d for n, d in iter(lambda: divmod(n, 10), (0,0))])) 

    [9, 8, 7, 6, 5, 4, 3, 2, 1] 
</pre></p>
<p>This is the one-liner version of the classic algorithm used to change a number base.<br />
The most important function is iter which takes a callable and a sentinel, continues to iterate the lambda function until it gets <strong> (0,0) </strong>.<br />
After we build a list with the list comprehension construct and reverse it.<br />
The first <em> list </em> returns a list object given the iterator constructed by reversed.</p>
<p>It actually works for any bases &lt;= 10, we can redefine as:</p>
<p><pre class="brush: python;">
&gt;&gt;&gt; f = lambda n, base: list(reversed([d for n, d in iter(lambda: divmod(n, base), (0,0))]))
&gt;&gt;&gt; f(10,2)
[1, 0, 1, 0]
</pre></p>
<p>We can also get back our original number in a similar way:<br />
<pre class="brush: python;">
&gt;&gt;&gt; n = 1231231; l = [1,2,3,1,2,3,1]
&gt;&gt;&gt; pows = list(reversed([int(pow(10, x)) for x in range(len(l))]))
&gt;&gt;&gt; sum([pows[i]* l[i] for i in range(len(l))]) == n
True
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/petitesnouvelles.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/petitesnouvelles.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/petitesnouvelles.wordpress.com/55/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=petitesnouvelles.wordpress.com&amp;blog=5220601&amp;post=55&amp;subd=petitesnouvelles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://petitesnouvelles.wordpress.com/2008/12/29/get-the-k-th-digit-out-of-a-number/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/733df2bec21a6aa4eaaa38ff8dac96b6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">petitesnouvelles</media:title>
		</media:content>
	</item>
	</channel>
</rss>
