<?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>Ruslan&#039;s Blog</title>
	<atom:link href="http://ruslanspivak.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ruslanspivak.com</link>
	<description>The harder you work the luckier you get</description>
	<lastBuildDate>Fri, 29 Jun 2012 04:41:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Need for Speed &#8211; SENDFILE System Call</title>
		<link>http://ruslanspivak.com/2012/06/28/need-for-speed-sendfile-system-call/</link>
		<comments>http://ruslanspivak.com/2012/06/28/need-for-speed-sendfile-system-call/#comments</comments>
		<pubDate>Fri, 29 Jun 2012 04:41:25 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1933</guid>
		<description><![CDATA[A very common operation of Web servers these days is transferring files to clients. They do that by reading the files&#8217; contents from a disk and writing it back to the clients&#8217; sockets. The copying of the file on Linux/UNIX, for example, could be done in a loop using read/write system calls: On the surface [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>A very common operation of Web servers these days is transferring files to clients. They do that by reading the files&#8217; contents from a disk and writing it back to the clients&#8217; sockets.</p>
<p>The copying of the file on Linux/UNIX, for example, could be done in a loop using <em>read/write</em> system calls:</p>
<pre class="brush: python; title: ; notranslate">
import os
...
while True:
    data = os.read(filefd, 4096)
    if not data:
        break
    os.write(socketfd, data)
</pre>
<p>On the surface this looks perfectly fine, but for transferring large files, when pre-processing of the file contents isn&#8217;t necessary, this is pretty inefficient.</p>
<p>The reason is that the <em>read</em> and <em>write</em> system calls involve copying data from kernel space to user space and vice versa and all that happens in a loop:<br />
<a href="http://ruslanspivak.com/wp-content/uploads/2012/06/sendfile1.jpg"><img src="http://ruslanspivak.com/wp-content/uploads/2012/06/sendfile1.jpg" alt="" title="sendfile1" width="636" height="464" class="aligncenter size-full wp-image-1960" /></a></p>
<p>That&#8217;s where the <a href="http://www.kernel.org/doc/man-pages/online/pages/man2/sendfile.2.html">sendfile</a> system call comes in handy. It provides a nice optimization for this particular use case by doing all the copying from the file descriptor to the socket descriptor completely in the kernel space:<br />
<a href="http://ruslanspivak.com/wp-content/uploads/2012/06/sendfile2.jpg"><img src="http://ruslanspivak.com/wp-content/uploads/2012/06/sendfile2.jpg" alt="read/write" title="sendfile2" width="640" height="468" class="aligncenter size-full wp-image-1957" /></a></p>
<p>Python 3.3 provides <a href="http://docs.python.org/dev/library/os.html#os.sendfile">os.sendfile</a> as part of the standard library. Check out <a href="https://github.com/rspivak/csdesign">more details</a> on the <a href="https://github.com/rspivak/csdesign">GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/06/28/need-for-speed-sendfile-system-call/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Self-Pipe Trick</title>
		<link>http://ruslanspivak.com/2012/06/24/self-pipe-trick/</link>
		<comments>http://ruslanspivak.com/2012/06/24/self-pipe-trick/#comments</comments>
		<pubDate>Sun, 24 Jun 2012 21:44:17 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1903</guid>
		<description><![CDATA[Imagine that your server process needs to simultaneously wait for I/O on multiple descriptors and also needs to wait for the delivery of a signal. The problem is that you can&#8217;t safely mix select() with signals because there is a chance of race condition. Consider the following code excerpt: The problem here is that if [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Imagine that your server process needs to simultaneously wait for I/O on multiple descriptors and also needs to wait for the delivery of a signal.<br />
The problem is that you can&#8217;t safely mix <em>select()</em> with signals because there is a chance of race condition.</p>
<p>Consider the following code excerpt:</p>
<pre class="brush: python; title: ; notranslate">
GOT_SIGNAL = False

def handler(signum, frame):
    global GOT_SIGNAL
    GOT_SIGNAL = True

...

signal.signal(signal.SIGUSR1, handler)

# What if the signal arrives at this point?

try:
    reads, writes, excs = select.select(rlist, wlist, elist)
except select.error as e:
    code, msg = e.args
    if code == errno.EINTR:
        if GOT_SIGNAL:
            print 'Got signal'
    else:
        raise
</pre>
<p>The problem here is that if the <em>SIGUSR1</em> is delivered after setting the signal handler but before call to <em>select</em> then the <em>select</em> call <strong>will block</strong> and we won&#8217;t execute our application logic in response to the event thus effectively <em>&#8220;missing&#8221;</em> the signal (our application logic in this case is printing the message: <em>Got signal</em>).</p>
<p>That&#8217;s an example of possible nasty racing. Let&#8217;s simulate that with <a href="https://github.com/rspivak/csdesign/blob/master/selsigrace.py">selsigrace.py</a></p>
<p>Start the program</p>
<pre class="brush: bash; title: ; notranslate">
$ python selsigrace.py
PID: 32324
Sleep for 10 secs
</pre>
<p>and send the <em>USR1</em> signal to the PID(it&#8217;s different on every run) within the 10 second interval while the process is still sleeping:</p>
<pre class="brush: bash; title: ; notranslate">
$ kill -USR1 32324
</pre>
<p>You should see the program produce additional line of output &#8216;Wake up and block in &#8220;select&#8221;&#8216; and <strong>block without exiting</strong>, no message &#8220;Got signal&#8221;:</p>
<pre class="brush: bash; title: ; notranslate">
$ python selsigrace.py
PID: 32324
Sleep for 10 secs
Wake up and block in &quot;select&quot;
</pre>
<p>If you send yet another <em>USR1</em> signal at this point then the <em>select</em> will be interrupted and the program will terminate with the message:</p>
<pre class="brush: bash; title: ; notranslate">
$ kill -USR1 32324
</pre>
<pre class="brush: bash; title: ; notranslate">
$ python selsigrace.py
PID: 32324
Sleep for 10 secs
Wake up and block in &quot;select&quot;
Got signal
</pre>
<p><a href="http://cr.yp.to/docs/selfpipe.html">Self-Pipe Trick</a> is used to avoid race conditions when waiting for signals and calling <em>select</em> on a set of descriptors.</p>
<p>The following steps describe how to implement it:</p>
<ol>
<li>Create a pipe and change its read and write ends to be nonblocking</li>
<li>Add the read end of the pipe to the read list of descriptors given to <em>select</em></li>
<li>Install a signal handler for the signal we&#8217;re concerned with. When the signal arrives the signal handler writes a byte of data to the pipe. Because the write end of the pipe is nonblocking we prevent the situation when signals flood the process, the pipe becomes full and the process blocks itself in the signal handler.</li>
<li>When <em>select</em> successfully returns check if the read end of the pipe is in the <em>readables</em> list and if it is then our signal has arrived.</li>
<li>When the signal arrives read <strong>all</strong> bytes that are in the pipe and execute any actions that have to be done in response to the signal delivery.</li>
</ol>
<p>You can check out the implementation on <a href="https://github.com/rspivak/csdesign">GitHub</a> and try it.</p>
<p>Start the <a href="https://github.com/rspivak/csdesign/blob/master/selfpipe.py">selfpipe.py</a> and send a <em>USR1</em> signal to it. You should see it output a message <em>Got signal</em> and exit.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/06/24/self-pipe-trick/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>SIGPIPE 101</title>
		<link>http://ruslanspivak.com/2012/06/08/sigpipe-101/</link>
		<comments>http://ruslanspivak.com/2012/06/08/sigpipe-101/#comments</comments>
		<pubDate>Fri, 08 Jun 2012 05:40:44 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1865</guid>
		<description><![CDATA[Have you ever seen a socket.error: [Errno 32] Broken pipe message when running a Python Web server and wondered what that means? The rule is that when a process tries to write to a socket that has already received an RST packet, the SIGPIPE signal is sent to that process which causes the Broken pipe [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Have you ever seen a <strong>socket.error: [Errno 32] Broken pipe</strong> message when running a Python Web server and wondered what that means?</p>
<p>The rule is that when a process tries to write to a socket that has already received an <em>RST</em> packet, the <em>SIGPIPE</em> signal is sent to that process which causes the <em>Broken pipe socket.error</em> exception.</p>
<p>Here are two scenarios that you can try that cause SIGPIPE signal to be fired.</p>
<p><strong>1.</strong> Server may send an RST packet to a client to abort the socket connection but the client ignores the packet and continues to write to the socket.</p>
<p>To test that behavior install <a href="https://github.com/rspivak/cynic">Cynic</a>, run it</p>
<pre class="brush: bash; title: ; notranslate">
$ cynic
INFO     [2012-06-08 05:06:37,040] server: Starting 'HTTPHtmlResponse'   on port 2000
INFO     [2012-06-08 05:06:37,040] server: Starting 'HTTPJsonResponse'   on port 2001
INFO     [2012-06-08 05:06:37,040] server: Starting 'HTTPNoBodyResponse' on port 2002
INFO     [2012-06-08 05:06:37,040] server: Starting 'HTTPSlowResponse'   on port 2003
INFO     [2012-06-08 05:06:37,040] server: Starting 'RSTResponse'        on port 2020
INFO     [2012-06-08 05:06:37,040] server: Starting 'RandomDataResponse' on port 2021
INFO     [2012-06-08 05:06:37,040] server: Starting 'NoResponse'         on port 2022
INFO     [2012-06-08 05:06:37,041] server: Starting 'LogRecordHandler'   on port /tmp/_cynic.sock
</pre>
<p>and then run the <em>client1.py</em>:</p>
<pre class="brush: python; title: ; notranslate">
import socket

# connect to Cynic's RSTResponse service on port 2020
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('', 2020))

# first read gets an RST packet
try:
    s.recv(1024)
except socket.error as e:
    print e
    print

# write after getting the RST causes SIGPIPE signal
# to be sent to this process which causes a socket.error
# exception
s.send('hello')
</pre>
<p>and see what happens:</p>
<pre class="brush: bash; title: ; notranslate">
$ python ./client1.py
[Errno 104] Connection reset by peer

Traceback (most recent call last):
  File &quot;./client1.py&quot;, line 17, in
    s.send('hello')
socket.error: [Errno 32] Broken pipe
</pre>
<p><strong>2.</strong> Server can send an RST to the client&#8217;s SYN request to indicate that there is no process wating for connections on the host at the specified port, but the client tries to write to the socket anyway.</p>
<p>To test it run the <em>client2.py</em>:</p>
<pre class="brush: python; title: ; notranslate">
import socket

# connect to the port that nobody is listening on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# gets us an RST packet
try:
    s.connect(('', 30301))
except socket.error as e:
    print e
    print

# write after getting RST causes SIGPIPE signal
# to be sent to this process which causes an exception
s.send('hello')
</pre>
<p>Here is the output:</p>
<pre class="brush: bash; title: ; notranslate">
$ python ./client2.py
[Errno 111] Connection refused

Traceback (most recent call last):
  File &quot;./sigpipe2.py&quot;, line 15, in
    s.send('hello')
socket.error: [Errno 32] Broken pipe
</pre>
<p>I hope that clarifies a SIGPIPE&#8217;s nature a little bit.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/06/08/sigpipe-101/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Examples of Concurrent Server Design in Python</title>
		<link>http://ruslanspivak.com/2012/06/06/simple-examples-of-concurrent-server-design-in-python/</link>
		<comments>http://ruslanspivak.com/2012/06/06/simple-examples-of-concurrent-server-design-in-python/#comments</comments>
		<pubDate>Wed, 06 Jun 2012 06:45:19 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1847</guid>
		<description><![CDATA[I&#8217;ve created a repo on GitHub called csdesign &#8211; https://github.com/rspivak/csdesign  &#8211; where I put several simple examples of concurrent TCP servers in Python. Currently it contains two of those: TCP Concurrent Server, One Child per Client (fork) TCP Concurrent Server, I/O Multiplexing (select) It&#8217;s an ongoing effort and if it&#8217;s something that you&#8217;re interested in [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve created a repo on GitHub called <strong>csdesign</strong> &#8211; <a href="https://github.com/rspivak/csdesign">https://github.com/rspivak/csdesign</a>  &#8211; where I put several simple examples of concurrent TCP servers in Python.</p>
<p>Currently it contains two of those:</p>
<ol>
<li>TCP Concurrent Server, One Child per Client (fork)</li>
<li>TCP Concurrent Server, I/O Multiplexing (select)</li>
</ol>
<p>It&#8217;s an ongoing effort and if it&#8217;s something that you&#8217;re interested in just follow the project on <a href="https://github.com/rspivak/csdesign">GitHub</a> or its progress on <a href="https://twitter.com/#!/alienoid">Twitter</a>.</p>
<p>Here is the Roadmap:</p>
<ul>
<li>TCP Concurrent Server, One Thread per Client</li>
<li>TCP Concurrent Server, I/O Multiplexing (poll)</li>
<li>TCP Concurrent Server, I/O Multiplexing (epoll)</li>
<li>TCP Preforked Server</li>
<li>TCP Prethreaded Server</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/06/06/simple-examples-of-concurrent-server-design-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cynic &#8211; Test Harness to Make Your System Under Test Cynical</title>
		<link>http://ruslanspivak.com/2012/06/03/cynic-test-harness-to-make-your-system-under-test-cynical/</link>
		<comments>http://ruslanspivak.com/2012/06/03/cynic-test-harness-to-make-your-system-under-test-cynical/#comments</comments>
		<pubDate>Mon, 04 Jun 2012 04:43:52 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1830</guid>
		<description><![CDATA[These days almost any application has several integration points like database, payment gateway, or some Web service that it consumes over HTTP. All communication with the remote systems happens over the network and both networks and those systems often go wonky. If we do not test the behavior of our system when the remote end [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>These days almost any application has several integration points like database, payment gateway, or some Web service that it consumes over HTTP.</p>
<p>All communication with the remote systems happens over the network and both networks and those systems often go wonky.</p>
<p>If we do not test the behavior of <strong>our</strong> system when the remote end operates out of spec and goes haywire the only place for testing becomes in production which is, as we all know, for some systems is less than acceptable.</p>
<p>Because the calls to the remote systems use network, the socket connection can have different failure scenarios, for example:</p>
<ul>
<li>The remote end resets the connection by sending a TCP RST packet</li>
<li>The connection may be established, but the response is never sent back and the connection is not closed (If you don&#8217;t use socket timeouts in your app you may be in trouble at some point).</li>
<li>The remote end can send garbage data as the response</li>
<li>The service can send HTML over HTTP instead of the expected JSON response</li>
<li>The HTTP service can send one byte of the response data every 30 seconds</li>
<li>The remote HTTP service sends only headers and no body</li>
<li>The service can send megabytes of data instead of expected kilobytes</li>
<li>Etc.</li>
</ul>
<p>It would be good to be able to test the behavior of our application when some of those conditions happen.</p>
<p><a href="https://github.com/rspivak/cynic"><strong>Cynic</strong></a> tries to help with that testing. Basically it&#8217;s a test harness (test double) that can be used to simulate crafty and devious remote systems right from your command line.</p>
<p><a href="https://github.com/rspivak/cynic">Cynic</a> will try hard to cause injury to your system.</p>
<p><em>It&#8217;s goal is to make your system under test cynical.</em></p>
<h2>Installation</h2>
<pre>$ [sudo] pip install cynic</pre>
<p>Or the bleeding edge version from the git master branch:</p>
<pre>$ [sudo] pip install git+https://github.com/rspivak/cynic.git#egg=cynic</pre>
<h2><a name="quick-intro" href="https://github.com/rspivak/cynic#quick-intro"></a>Quick intro</h2>
<p>Start Cynic which in turn will start multiple services on different ports:</p>
<pre>$ cynic
INFO     [2012-06-03 23:44:35,603] server: Starting 'HTTPHtmlResponse'   on port 2000
INFO     [2012-06-03 23:44:35,603] server: Starting 'HTTPJsonResponse'   on port 2001
INFO     [2012-06-03 23:44:35,604] server: Starting 'HTTPNoBodyResponse' on port 2002
INFO     [2012-06-03 23:44:35,604] server: Starting 'HTTPSlowResponse'   on port 2003
INFO     [2012-06-03 23:44:35,604] server: Starting 'RSTResponse'        on port 2020
INFO     [2012-06-03 23:44:35,604] server: Starting 'RandomDataResponse' on port 2021
INFO     [2012-06-03 23:44:35,604] server: Starting 'NoResponse'         on port 2022
INFO     [2012-06-03 23:44:35,604] server: Starting 'LogRecordHandler'   on port /tmp/_cynic.sock</pre>
<h3><a name="test-different-services" href="https://github.com/rspivak/cynic#test-different-services"></a>Test different services</h3>
<ol>
<li>Connect to the service on port 2020 and get a TCP RST packet right away which causes &#8216;Connection reset by peer&#8217; message on the command line</li>
</ol>
<blockquote>
<pre>$ curl http://localhost:2020
curl: (56) Recv failure: Connection reset by peer</pre>
</blockquote>
<ol start="2">
<li>Connect to the service on port 2021 and get back 7 bytes of random data</li>
</ol>
<blockquote>
<pre>$ telnet localhost 2021
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
#6
Connection closed by foreign host.</pre>
</blockquote>
<ol start="3">
<li>Connect to the service on port 2001 to get the HTTP JSON response</li>
</ol>
<blockquote>
<pre>$ curl http://localhost:2001
{"message": "Hello, World!"}</pre>
</blockquote>
<p>So you got the basic idea. Point your application&#8217;s integration points to the Cynic&#8217;s services and see how your app reacts.</p>
<p>For more information check the project&#8217;s GitHub page at <a href="https://github.com/rspivak/cynic">https://github.com/rspivak/cynic</a></p>
<p><strong>UPDATE [2012-06-04]</strong> Added <a href="https://vimeo.com/43375697">screencast</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/06/03/cynic-test-harness-to-make-your-system-under-test-cynical/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Logsna &#8211; a sane log output format</title>
		<link>http://ruslanspivak.com/2012/05/20/logsna-a-sane-log-output-format/</link>
		<comments>http://ruslanspivak.com/2012/05/20/logsna-a-sane-log-output-format/#comments</comments>
		<pubDate>Mon, 21 May 2012 04:03:04 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1793</guid>
		<description><![CDATA[Good old log files are still the most reliable, versatile, and useful sources of information. When they are also human-readable and easy to use with standard Unix tools like tail and grep they are even more useful. We all know that especially in time of stress when things with a system are going south having [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Good old log files are still the most reliable, versatile, and useful sources of information.<br />
When they are also human-readable and easy to use with standard Unix tools like <strong><em>tail</em></strong> and <strong><em>grep</em></strong> they are even more useful.</p>
<p>We all know that especially in time of stress when things with a system are going south having a quick and easy way to grep for useful information is critical. The purpose of a small Python utility <a href="https://github.com/rspivak/logsna">Logsna</a> is to provide a sane log output format that makes some grepping a bit easier.</p>
<p><a href="https://github.com/rspivak/logsna">Logsna</a> offers a custom formatter class <em>logsna.Formatter</em> that can be used in a logging config file, for example:</p>
<pre class="brush: python; title: ; notranslate">
# sanefmt.py
import logging
import logging.config
from StringIO import StringIO

CONFIG = &quot;&quot;&quot;\
[loggers]
keys=root

[handlers]
keys=console

[handler_console]
class=logging.StreamHandler
args=(sys.stderr,)
formatter=sane

[formatters]
keys=sane

[logger_root]
level=DEBUG
handlers=console

# Our custom formatter class
[formatter_sane]
class=logsna.Formatter
&quot;&quot;&quot;

config = StringIO(CONFIG)
logging.config.fileConfig(config)

log = logging.getLogger('mylogger.component1')

log.debug('debug message')
log.info('info message')
log.warning('warning message')
log.critical('critical message')
try:
    1 / 0
except:
    log.exception('Houston we have a problem')
</pre>
<h4>The Log Format</h4>
<p>Here is an output from the above program:</p>
<pre class="brush: bash; title: ; notranslate">
DEBUG    [2012-05-21 01:59:23,686] mylogger.component1: debug message
INFO     [2012-05-21 01:59:23,686] mylogger.component1: info message
WARNING  [2012-05-21 01:59:23,686] mylogger.component1: warning message
CRITICAL [2012-05-21 01:59:23,686] mylogger.component1: critical message
ERROR    [2012-05-21 01:59:23,686] mylogger.component1: Houston we have a problem
! Traceback (most recent call last):
!   File &quot;/home/alienoid/python/sanefmt.py&quot;, line 67, in
!     1 / 0
! ZeroDivisionError: integer division or modulo by zero
</pre>
<h4>The Log Format Notes</h4>
<p>- All timestamps are in <strong>ISO8601</strong> and <strong>UTC</strong> format</p>
<p>- To grep for messages of a specific level</p>
<pre class="brush: python; title: ; notranslate">
$ tail -f sanefmt.log | grep '^INFO'
</pre>
<p>- To grep for messages from a particular logger</p>
<pre class="brush: bash; title: ; notranslate">
$ tail -f sanefmt.log | grep 'component1:'
</pre>
<p>- To pull out full exception tracebacks with a corresponding log message</p>
<pre class="brush: bash; title: ; notranslate">
$ tail -f sanefmt.log | grep -B 1 '^\!'
</pre>
<h4>Installation</h4>
<pre class="brush: bash; title: ; notranslate">
$ [sudo] pip install logsna
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/05/20/logsna-a-sane-log-output-format/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>BASH Nonstandard Redirection</title>
		<link>http://ruslanspivak.com/2012/04/16/bash-nonstandard-redirection/</link>
		<comments>http://ruslanspivak.com/2012/04/16/bash-nonstandard-redirection/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 02:35:46 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1770</guid>
		<description><![CDATA[I&#8217;ve recently discovered a neat BASH specific syntax for stream redirection so I thought I&#8217;d share it on the off chance you find it useful too. Let&#8217;s see how standard error (STDERR) can be redirected to standard output (STDOUT), which in turn is redirected to a file, using standard syntax: The order is important: And [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve recently discovered a neat BASH specific syntax for stream redirection so I thought I&#8217;d share it on the off chance you find it useful too.</p>
<p>Let&#8217;s see how standard error (STDERR) can be redirected to standard output (STDOUT), which in turn is redirected to a file, using standard syntax:</p>
<pre class="brush: bash; title: ; notranslate">
$ printf &quot;%s\n%\n&quot; Hello world &gt; FILE 2&gt;&amp;1
$ cat FILE
Hello
bash: printf: `\': invalid format character
</pre>
<p>The order is important:</p>
<pre class="brush: bash; title: ; notranslate">
$ printf &quot;%s\n%\n&quot; Hello world 2&gt;&amp;1 &gt; FILE
bash: printf: `\': invalid format character
$ cat FILE
Hello
</pre>
<p>And here is a BASH nonstandard syntax for redirection of STDERR and STDOUT to the same place &#8211; <strong>&#038;> FILE</strong></p>
<pre class="brush: bash; title: ; notranslate">
$ printf &quot;%s\n%\n&quot; Hello world &amp;&gt; FILE
$ cat FILE
Hello
bash: printf: `\': invalid format character
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/04/16/bash-nonstandard-redirection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SlimIt &#8211; multiline string support</title>
		<link>http://ruslanspivak.com/2012/04/09/slimit-multiline-string-support/</link>
		<comments>http://ruslanspivak.com/2012/04/09/slimit-multiline-string-support/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 02:58:12 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[minifier]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1747</guid>
		<description><![CDATA[I made some changes to the lexer and now SlimiIt can handle JavaScript string literals that span multiple lines. In JavaScript, as in Python, continuation lines can be used with a backslash as the last character on the line indicating that the next line is a continuation of the line. Here is a simple example:]]></description>
			<content:encoded><![CDATA[<p></p><p>I made some changes to the lexer and now <a href="https://github.com/rspivak/slimit">SlimiIt</a> can handle JavaScript string literals that span multiple lines.<br />
In JavaScript, as in Python, continuation lines can be used with a backslash as the last character on the line indicating that the next line is a continuation of the line.</p>
<p>Here is a simple example:</p>
<pre class="brush: bash; title: ; notranslate">
$ cat test.js
var s = &quot;hello \
    \
    world\
    &quot;;
$
$ cat test.js | slimit -m -t
var a=&quot;hello         world    &quot;;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/04/09/slimit-multiline-string-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What’s New in SlimIt 0.6.1</title>
		<link>http://ruslanspivak.com/2012/03/15/whats-new-in-slimit-0-6-1/</link>
		<comments>http://ruslanspivak.com/2012/03/15/whats-new-in-slimit-0-6-1/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 03:59:40 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1722</guid>
		<description><![CDATA[While the new version of SlimIt is mostly a bugfix release: - Problem with &#8220;+&#8221;, &#8220;++&#8221; and whitespace - Problem with for loop with ? operator in initializer position there is also one new feature: -t / &#8211;mangle-toplevel command-line option. It allows you to turn on global scope name mangling which is now off by [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>While the new version of <a href="https://github.com/rspivak/slimit">SlimIt</a> is mostly a bugfix release:<br />
- <a href="https://github.com/rspivak/slimit/issues/26">Problem with &#8220;+&#8221;, &#8220;++&#8221; and whitespace</a><br />
- <a href="https://github.com/rspivak/slimit/issues/25">Problem with for loop with ? operator in initializer position</a></p>
<p>there is also one new feature: <strong>-t / &#8211;mangle-toplevel</strong> command-line option.<br />
It allows you to turn on global scope name mangling which is now off by default.<br />
Let&#8217;s see it in action.</p>
<pre class="brush: bash; title: ; notranslate">
$ cat test.js
function foo(first, second){
  alert(first, second);
}

foo();
</pre>
<p>Global scope mangling is off by default:</p>
<pre class="brush: bash; title: ; notranslate">
$ slimit -m test.js
function foo(a,b){alert(a,b);}foo();
</pre>
<p>With global scope name mangling on:</p>
<pre class="brush: bash; title: ; notranslate">
$ slimit -m --mangle-toplevel test.js
function a(a,b){alert(a,b);}a();
</pre>
<p>In Python code pass <strong>mangle_toplevel=True</strong> argument to minify function:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from slimit import minify
&gt;&gt;&gt; text = &quot;&quot;&quot;\
... function foo(first, second){
...   alert(first, second);
... }
...
... foo();
... &quot;&quot;&quot;
&gt;&gt;&gt; minify(text, mangle=True, mangle_toplevel=True)
'function a(a,b){alert(a,b);}a();'
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/03/15/whats-new-in-slimit-0-6-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s New in Crammit 0.3</title>
		<link>http://ruslanspivak.com/2012/03/12/whats-new-in-crammit-0-3/</link>
		<comments>http://ruslanspivak.com/2012/03/12/whats-new-in-crammit-0-3/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 05:06:47 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[crammit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1713</guid>
		<description><![CDATA[Crammit 0.3 is out. Two main features in this release: - Python 2.6 support (thanks to Didip Kerabat for contributing code) - files option in assetsinfo.yaml that lists all processed files for a bundle After running it on the command line the output information from assetsinfo.yaml may look like]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="https://github.com/rspivak/crammit">Crammit 0.3</a> is out.</p>
<p>Two main features in this release:<br />
- Python 2.6 support (thanks to <a href="https://github.com/didip">Didip Kerabat</a> for contributing code)<br />
- <strong>files</strong> option in <em>assetsinfo.yaml</em> that lists all processed files for a bundle</p>
<p>After running it on the command line</p>
<pre class="brush: bash; title: ; notranslate">
$ crammit -c assets.yaml
</pre>
<p>the output information from <em>assetsinfo.yaml</em> may look like</p>
<pre class="brush: plain; title: ; notranslate">
css:
  base:
    files:
    - /home/rspivak/static/css/test1.css
    - /home/rspivak/static/css/test2.css
    fingerprint: 71fe4cba05a1a51023c6af4c4abf9c47ab21e357
    output:
      gz: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.min.css.gz
      min: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.min.css
      raw: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.css
    size:
      gz: 108
      min: 235
      raw: 277
javascript:
  common:
    files:
    - /home/rspivak/static/js/application.js
    - /home/rspivak/static/js/vendor/vendor1.js
    - /home/rspivak/static/js/vendor/vendor2.js
    fingerprint: 6493b619c73c49ce1f4dfe2c31d41902e98acaee
    output:
      gz: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.min.js.gz
      min: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.min.js
      raw: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.js
    size:
      gz: 56
      min: 41
      raw: 50
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/03/12/whats-new-in-crammit-0-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Class-based Views in Pyramid</title>
		<link>http://ruslanspivak.com/2012/03/02/class-based-views-in-pyramid/</link>
		<comments>http://ruslanspivak.com/2012/03/02/class-based-views-in-pyramid/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 05:00:03 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[pyramid]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1376</guid>
		<description><![CDATA[It&#8217;s very easy to add a class-based view to your Pyramid application. There are basically just two things that you have to do with your typical Python class: make sure that your __init__ method accepts and stores request object for further reference (request is not passed to your other class methods) add a @view_config decorator [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>It&#8217;s very easy to add a class-based view to your Pyramid application.</p>
<p>There are basically just two things that you have to do with your typical Python class:</p>
<ol>
<li>make sure that your __init__ method accepts and stores <strong>request</strong> object for further reference (request is not passed to your other class methods)</li>
<li>add a @view_config decorator to a method that you want to be called when your view is rendered</li>
</ol>
<p>Here is a simple example of a login class-based view:</p>
<pre class="brush: python; title: ; notranslate">
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPForbidden

class LoginView(object):
    def __init__(self, request):
        self.request = request

    def get_login_url(self):
        login_url = self.request.route_url('login')
        return login_url

    @view_config(context=HTTPForbidden, renderer='login.mak')
    @view_config(route_name='login', renderer='login.mak')
    def login(self):
        login_url = self.get_login_url()
        # more code goes here
        return dict(url=login_url)
</pre>
<p>As you can see it really is that simple.</p>
<p>You&#8217;ve probably noticed that I had to repeat renderer=&#8217;login.mak&#8217; part twice and it&#8217;s kind of annoying. But as luck would have it as of version 1.3a2 Pyramid comes with a new decorator @view_defaults and our class can be re-written with it like this:</p>
<pre class="brush: python; title: ; notranslate">
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPForbidden

@view_defaults(renderer='login.mak')
class LoginView(object):
    def __init__(self, request):
        self.request = request

    def get_login_url(self):
        login_url = self.request.route_url('login')
        return login_url

    @view_config(context=HTTPForbidden)
    @view_config(route_name='login')
    def login(self):
        login_url = self.get_login_url()
        # more code goes here
        return dict(url=login_url)
</pre>
<p>I like that much more than the old version. For more information on the @view_defaults decorator see here: <a href="http://readthedocs.org/docs/pyramid/en/latest/whatsnew-1.3.html#view-defaults-decorator">@view_defaults decorator</a></p>
<p>And the last thing I&#8217;d like to mention is a handy <strong>view</strong> variable that is available for you in your templates. You can use it to call helper methods from your class-based view like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;span&gt;Login URL: ${view.get_login_url()}&lt;/span&gt;
</pre>
<h4>UPDATE Mar 2, 2012</h4>
<p>If you don&#8217;t want to use the <em>view_config</em> decorator and want to register your class-based view&#8217;s method via an <strong>add_view</strong> call of your Configurator object this is how to do it.</p>
<pre class="brush: python; title: ; notranslate">
# __init__.py
from pyramid.config import Configurator

from mypackage.views import LoginView

def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.add_route('login', '/login')
    config.add_view(LoginView, attr='login', route_name='login')
    ...
</pre>
<p>You pass your view class (it can also be a Python dotted name) to the <em>add_view</em> method  and use an <strong>attr</strong> argument to specify what method on that class should be used as a view.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/03/02/class-based-views-in-pyramid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pyramid Inside &#8211; p* scripts</title>
		<link>http://ruslanspivak.com/2012/02/19/pyramid-inside-p-scripts/</link>
		<comments>http://ruslanspivak.com/2012/02/19/pyramid-inside-p-scripts/#comments</comments>
		<pubDate>Sun, 19 Feb 2012 15:51:31 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[pyramid]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1518</guid>
		<description><![CDATA[Pyramid 1.3 introduced different p* scripts that replaced the paster commands with Pyramid-specific analogues. Here is a summary table that lists all currently available scripts with their brief descriptions. pcreate create a Pyramid application using one of the pre-defined scaffolds pserve run the application proutes display all application routes pviews display matching views for a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/whatsnew-1.3.html">Pyramid 1.3</a> introduced different <strong>p* scripts</strong> that replaced the <em>paster</em> commands with Pyramid-specific analogues. Here is a summary table that lists all currently available scripts with their brief descriptions.</p>
<table class="wborder">
<tr>
<td><strong>pcreate</strong></td>
<td>create a Pyramid application using one of the pre-defined scaffolds</td>
</tr>
<tr>
<td><strong>pserve</strong></td>
<td>run the application</td>
</tr>
<tr>
<td><strong>proutes</strong></td>
<td>display all application routes</td>
</tr>
<tr>
<td><strong>pviews</strong></td>
<td>display matching views for a given URL</td>
</tr>
<tr>
<td><strong>prequest</strong></td>
<td>send a request to the application without starting a server</td>
</tr>
<tr>
<td><strong>pshell</strong></td>
<td>play in the interactive shell with the app</td>
</tr>
<tr>
<td><strong>ptweens</strong></td>
<td>display &#8220;tweens&#8221;</td>
</tr>
</table>
<p>The best way to get to know what those commands do is to try them out. But before we see our <strong>p* scripts</strong> in action make sure to install the latest Pyramid 1.3 and <strong>activate</strong> your virtual environment. The steps to do that might look like this:</p>
<pre class="brush: bash; title: ; notranslate">
$ virtualenv --no-site-packages test
$ cd test
$ source bin/activate
$ pip install pyramid
</pre>
<p>OK, buckle up and let&#8217;s get it started.</p>
<h4>Create application</h4>
<p>Let&#8217;s create a simple project called <em>myproject</em> with <strong>pcreate</strong> command</p>
<pre class="brush: bash; title: ; notranslate">
$ pcreate -s starter myproject
...
Welcome to Pyramid.  Sorry for the convenience.
</pre>
<h4>Run it</h4>
<p>In order to run our application we need to install it for development first.</p>
<pre class="brush: bash; title: ; notranslate">
$ cd myproject
$ python setup.py develop
</pre>
<p>And now we can run it with <strong>pserve</strong> script</p>
<pre class="brush: bash; title: ; notranslate">
$ pserve development.ini
Starting server in PID 17410.
serving on http://0.0.0.0:6543
</pre>
<h4>Display all application routes</h4>
<pre class="brush: bash; title: ; notranslate">
$ proutes development.ini | grep -v debug
Name        Pattern             View
----        -------             ----
__static/   /static/*subpath    &lt;function &lt;pyramid.static  ...&gt;
home        /                   &lt;function my_view at 0x996b09c&gt;
</pre>
<h4>Display matching views for a given URL</h4>
<pre class="brush: bash; title: ; notranslate">
$ pviews development.ini /

URL = /

    context: &lt;pyramid.traversal.DefaultRootFactory instance at ...&gt;
    view name: 

    Route:
    ------
    route name: home
    route pattern: /
    route path: /
    subpath: 

        View:
        -----
        myproject.views.my_view
</pre>
<h4>Send a request to our application without starting a server</h4>
<p>Let&#8217;s make a GET request and show response headers</p>
<pre class="brush: bash; title: ; notranslate">
$ prequest -d development.ini /
200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 3390
&lt;!DOCTYPE html PUBLIC ...&gt;
...
</pre>
<p>And now a POST request to a non-existent URL</p>
<pre class="brush: bash; title: ; notranslate">
$ echo 'body text' | prequest -mPOST -d development.ini /dummy
404 Not Found
Content-Type: text/html; charset=UTF-8
Content-Length: 158
&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;404 Not Found&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;404 Not Found&lt;/h1&gt;
  The resource could not be found.&lt;br/&gt;&lt;br/&gt;
/dummy

 &lt;/body&gt;
&lt;/html&gt;
</pre>
<h4>Play in the interactive shell</h4>
<pre class="brush: bash; title: ; notranslate">
$ pshell development.ini
Python 2.7.1 (r271:86832, Apr 12 2011, 16:16:18)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)] on linux2
Type &quot;help&quot; for more information.

Environment:
  app          The WSGI application.
  registry     Active Pyramid registry.
  request      Active request object.
  root         Root of the default resource tree.
  root_factory Default root factory used to create `root`.

&gt;&gt;&gt; from myproject.views import my_view
&gt;&gt;&gt; from pyramid.request import Request
&gt;&gt;&gt; r = Request.blank('/')
&gt;&gt;&gt; my_view(r)
{'project': 'myproject'}
</pre>
<p>If we install IPython it will be used instead of the default Python shell.</p>
<h4>Display &#8220;tweens&#8221; (middleware)</h4>
<pre class="brush: bash; title: ; notranslate">
$ ptweens development.ini
...

Implicit Tween Chain

Position    Name
--------    ----
-           INGRESS
0           pyramid_debugtoolbar.toolbar_tween_factory
1           pyramid.tweens.excview_tween_factory
-           MAIN
</pre>
<p>If you&#8217;ve read this far and want to dig deeper into those commands check out an excellent official documentation page: <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/commandline.html">Command-Line Pyramid</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/02/19/pyramid-inside-p-scripts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Crammit &#8211; Yet Another Asset Packaging Library</title>
		<link>http://ruslanspivak.com/2012/02/12/crammit-yet-another-asset-packaging-library/</link>
		<comments>http://ruslanspivak.com/2012/02/12/crammit-yet-another-asset-packaging-library/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 07:34:56 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1481</guid>
		<description><![CDATA[Crammit is really simple. It&#8217;s a small tool that uses YAML for configuration and other libraries to do the heavy lifting. Here is a config file assets.yaml: Let&#8217;s put it through its paces: In addition to generated asset bundles it outputs an information file that sums up all what&#8217;s been done. Check it out here [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="https://github.com/rspivak/crammit">Crammit</a> is really simple. It&#8217;s a small tool that uses YAML for configuration and other libraries to do the heavy lifting.</p>
<p>Here is a config file <strong>assets.yaml</strong>:</p>
<pre class="brush: plain; title: ; notranslate">
output: assets    # directory path relative to  current directory
fingerprint: true # add sha1 hash to the output file name

javascript:
  # 'common' is a bundle name
  # output file will have prefix 'common'
  common:
    - static/js/application.js
    - static/js/vendor/*.js
  utils:
    # paths are relative to the current directory
    - static/js/utils.js

css:
  base:
    # you can use Unix shell-style wildcards in file names
    - static/css/*.css
</pre>
<p>Let&#8217;s put it through its paces:</p>
<pre class="brush: bash; title: ; notranslate">
$ crammit -c assets.yaml
</pre>
<p>In addition to generated asset bundles it outputs an information file that sums up all what&#8217;s been done.</p>
<pre class="brush: plain; title: ; notranslate">
css:
  base:
    fingerprint: 71fe4cba05a1a51023c6af4c4abf9c47ab21e357
    output:
      gz: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.min.css.gz
      min: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.min.css
      raw: base-71fe4cba05a1a51023c6af4c4abf9c47ab21e357.css
    size:
      gz: 108
      min: 235
      raw: 277
javascript:
  common:
    fingerprint: 6493b619c73c49ce1f4dfe2c31d41902e98acaee
    output:
      gz: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.min.js.gz
      min: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.min.js
      raw: common-6493b619c73c49ce1f4dfe2c31d41902e98acaee.js
    size:
      gz: 56
      min: 41
      raw: 50
  utils:
    fingerprint: c3ef63280b954d99e8b13fc11ea3031caee77f1a
    output:
      gz: utils-c3ef63280b954d99e8b13fc11ea3031caee77f1a.min.js.gz
      min: utils-c3ef63280b954d99e8b13fc11ea3031caee77f1a.min.js
      raw: utils-c3ef63280b954d99e8b13fc11ea3031caee77f1a.js
    size:
      gz: 42
      min: 22
      raw: 24
</pre>
<p>Check it out <a href="https://github.com/rspivak/crammit">here</a> for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/02/12/crammit-yet-another-asset-packaging-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pyramid is Awesome for Beginners</title>
		<link>http://ruslanspivak.com/2012/02/05/pyramid-is-awesome-for-beginners/</link>
		<comments>http://ruslanspivak.com/2012/02/05/pyramid-is-awesome-for-beginners/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 19:20:42 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[pyramid]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1438</guid>
		<description><![CDATA[I know some people think that Pyramid is a complex framework and that aspiring Python web developers should start with something else and maybe come back to Pyramid later. But I truly believe that even if you&#8217;re a total beginner Pyramid can serve you really well and once you grow more experienced, you&#8217;ll appreciate the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I know some people think that <a href="http://docs.pylonsproject.org/en/latest/docs/pyramid.html">Pyramid</a> is a complex framework and that aspiring Python web developers should start with something else and maybe come back to Pyramid later.</p>
<p>But I truly believe that even if you&#8217;re a total beginner Pyramid can serve you really well and once you grow more experienced, you&#8217;ll appreciate the power that you get with the Pyramid framework.</p>
<p>Take a look at this &#8220;hello world&#8221; application in <code>hello.py</code>:</p>
<pre class="brush: python; title: ; notranslate">
from wsgiref.simple_server import make_server
from pyramid.config import Configurator

def hello(request):
   return 'Hello %(name)s!' % request.matchdict

if __name__ == '__main__':
    config = Configurator()
    config.add_route('main', '/hello/{name}')
    config.add_view(hello, route_name='main', renderer='string')
    server = make_server('', 8080, config.make_wsgi_app())
    server.serve_forever()
</pre>
<p>It wasn&#8217;t that difficult.</p>
<p>And this is how to install and run it:</p>
<pre class="brush: bash; title: ; notranslate">
$ pip install pyramid
$ python hello.py
</pre>
<p>Then in your browser type <code>http://localhost:8080/hello/fred</code> and see the result. Easy peasy.</p>
<p>So what are you waiting for? <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Grab it <a href="http://pypi.python.org/pypi/pyramid">here</a> and give it a try!</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/02/05/pyramid-is-awesome-for-beginners/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>SlimIt vs YUI Compressor</title>
		<link>http://ruslanspivak.com/2012/01/15/slimit-vs-yui-compressor/</link>
		<comments>http://ruslanspivak.com/2012/01/15/slimit-vs-yui-compressor/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 02:46:47 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[minifier]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1338</guid>
		<description><![CDATA[Let&#8217;s compare compression of SlimIt and YUI Compressor using jQuery source file. File SlimIt SlimIt+gzip YUI YUI+gzip jquery-1.7.1.js 97241 33330 104684 36164 As you can see SlimIt performs better and it&#8217;s pure Python. Do you still use YUI Compressor in your Python project? Give SlimIt a try. If you have any questions or encountered any [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Let&#8217;s compare compression of <a href="https://github.com/rspivak/slimit">SlimIt</a> and <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a> using jQuery source file.</p>
<table class="wborder">
<tbody>
<tr>
<th>File</th>
<th>SlimIt</th>
<th>SlimIt+gzip</th>
<th>YUI</th>
<th>YUI+gzip</th>
</tr>
<tr>
<td>jquery-1.7.1.js</td>
<td>97241</td>
<td>33330</td>
<td>104684</td>
<td>36164</td>
</tr>
</tbody>
</table>
<p>As you can see <a href="https://github.com/rspivak/slimit">SlimIt</a> performs better and it&#8217;s pure Python.<br />
Do you still use YUI Compressor in your Python project? Give <a href="https://github.com/rspivak/slimit">SlimIt</a> a try.<br />
If you have any questions or encountered any issue here is the place to discuss it: <a href="https://github.com/rspivak/slimit/issues">GitHub Issues</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/01/15/slimit-vs-yui-compressor/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>New Home for My Blog</title>
		<link>http://ruslanspivak.com/2012/01/02/new-home-for-my-blog/</link>
		<comments>http://ruslanspivak.com/2012/01/02/new-home-for-my-blog/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 17:20:05 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[uncategorized]]></category>

		<guid isPermaLink="false">http://li124-144.members.linode.com/?p=12</guid>
		<description><![CDATA[First of all Happy New Year! I moved my blog to a new hosting provider and as you can see the blog is somewhat empty. Sorry for the inconveniences. I&#8217;ll be reviewing my old content and populating my new blog with it over time.]]></description>
			<content:encoded><![CDATA[<p></p><p>First of all Happy New Year!</p>
<p>I moved my blog to a new hosting provider and as you can see the blog is somewhat empty.<br />
Sorry for the inconveniences. I&#8217;ll be reviewing my old content and populating my new blog with it over time.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2012/01/02/new-home-for-my-blog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colorized HTTP codes with httpcode 0.5</title>
		<link>http://ruslanspivak.com/2011/12/30/colorized-http-codes-with-httpcode-0-5/</link>
		<comments>http://ruslanspivak.com/2011/12/30/colorized-http-codes-with-httpcode-0-5/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 07:56:38 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1334</guid>
		<description><![CDATA[New release of httpcode is out. Grab it here. This release adds colorization of HTTP codes:]]></description>
			<content:encoded><![CDATA[<p></p><p>New release of httpcode is out. Grab it <a href="https://github.com/rspivak/httpcode">here</a>.</p>
<p>This release adds colorization of HTTP codes:<br />
<a href="http://ruslanspivak.files.wordpress.com/2011/12/httpcode.png"><img src="http://ruslanspivak.files.wordpress.com/2011/12/httpcode.png" alt="" title="httpcode" width="534" height="153" class="alignleft size-full wp-image-1336" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/30/colorized-http-codes-with-httpcode-0-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SlimIt knows how to minify object access</title>
		<link>http://ruslanspivak.com/2011/12/27/slimit-knows-how-to-minify-object-access/</link>
		<comments>http://ruslanspivak.com/2011/12/27/slimit-knows-how-to-minify-object-access/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 04:00:21 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1325</guid>
		<description><![CDATA[SlimIt got a new feature &#8211; object access minification. Let&#8217;s give it a try: But if the object attribute is not a legitimate identifier minification does nothing: This is not a part of an official release yet, but you can clone it and install from GitHub. Let me know if you have any issues with [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="https://github.com/rspivak/slimit">SlimIt</a> got a new feature &#8211; <a href="https://github.com/rspivak/slimit/commit/d76d004b6c44a1a7d28719a6bf4db221b3dfc089">object access minification</a>.</p>
<p>Let&#8217;s give it a try:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from slimit import minify
&gt;&gt;&gt; minify('foo[&quot;bar&quot;];') == 'foo.bar;'
True
</pre>
<p>But if the object attribute is not a legitimate identifier minification does nothing:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; minify('foo[&quot;bar bar&quot;];')
'foo[&quot;bar bar&quot;];'
</pre>
<p>This is not a part of an official release yet, but you can clone it and install from <a href="https://github.com/rspivak/slimit">GitHub</a>.<br />
Let me know if you have any <a href="https://github.com/rspivak/slimit/issues">issues</a> with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/27/slimit-knows-how-to-minify-object-access/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>httpcode 0.4 is out &#8211; filtering codes with regex</title>
		<link>http://ruslanspivak.com/2011/12/27/httpcode-0-4-is-out-filtering-codes-with-regex/</link>
		<comments>http://ruslanspivak.com/2011/12/27/httpcode-0-4-is-out-filtering-codes-with-regex/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 19:58:22 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1313</guid>
		<description><![CDATA[A quick announcement &#8211; httcode 0.4 is out. Grab it while it&#8217;s hot! Thanks to Mark Striemer in this release you can filter codes with regex and use &#8216;x&#8216; to denote any digit. Filter codes with a regex Use an &#8216;x&#8217; for any digit Grab it here]]></description>
			<content:encoded><![CDATA[<p></p><p>A quick announcement &#8211; <a href="https://github.com/rspivak/httpcode">httcode 0.4 is out</a>. Grab it while it&#8217;s hot! <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Thanks to <a href="https://github.com/rspivak/httpcode/pull/6">Mark Striemer</a> in this release you can filter codes with regex and use &#8216;<strong>x</strong>&#8216; to denote any digit.</p>
<h5>Filter codes with a regex</h5>
<pre class="brush: bash; title: ; notranslate">
$ hc 30[12]
Status code 301
Message: Moved Permanently
Code explanation: Object moved permanently -- see URI list

Status code 302
Message: Found
Code explanation: Object moved temporarily -- see URI list
</pre>
<h5>Use an &#8216;x&#8217; for any digit</h5>
<pre class="brush: bash; title: ; notranslate">
$ hc 1xx
Status code 100
Message: Continue
Code explanation: Request received, please continue

Status code 101
Message: Switching Protocols
Code explanation: Switching to new protocol; obey Upgrade header
</pre>
<p>Grab it <a href="https://github.com/rspivak/httpcode">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/27/httpcode-0-4-is-out-filtering-codes-with-regex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>httpcode.el – explain HTTP status code in minibuffer</title>
		<link>http://ruslanspivak.com/2011/12/24/httpcode-el-explain-http-status-code-in-minibuffer/</link>
		<comments>http://ruslanspivak.com/2011/12/24/httpcode-el-explain-http-status-code-in-minibuffer/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 04:49:56 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1308</guid>
		<description><![CDATA[In addition to command line version here comes Emacs package to explain HTTP status codes in minibuffer httpcode.el]]></description>
			<content:encoded><![CDATA[<p></p><p>In addition to <a href="http://ruslanspivak.com/2011/12/21/httpcode-explain-http-status-code-on-the-command-line/">command line version</a> here comes Emacs package to explain HTTP status codes in minibuffer <a href="http://github.com/rspivak/httpcode.el">httpcode.el</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/24/httpcode-el-explain-http-status-code-in-minibuffer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>httpcode &#8211; explain HTTP status code on the command line</title>
		<link>http://ruslanspivak.com/2011/12/21/httpcode-explain-http-status-code-on-the-command-line/</link>
		<comments>http://ruslanspivak.com/2011/12/21/httpcode-explain-http-status-code-on-the-command-line/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 03:00:26 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1283</guid>
		<description><![CDATA[Now and then I find myself looking at RFC or Wikipedia page to find the meaning of different HTTP status codes, like 100, 405, 410, etc. It takes some time to click on the link, wait for the page to load and to find the code I need. That&#8217;s a pretty slow workflow so I [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Now and then I find myself looking at RFC or Wikipedia page to find the meaning of different <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes">HTTP status codes</a>, like <strong>100</strong>, <strong>405</strong>, <strong>410</strong>, etc. It takes some time to click on the link, wait for the page to load and to find the code I need.</p>
<p>That&#8217;s a pretty slow workflow so I wrote real quick a <a href="http://github.com/rspivak/httpcode">little utility called httpcode</a> that explains the meaning of an HTTP status code on the command line. Who needs a browser anyways <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Try it.</p>
<h3>Installation</h3>
<pre class="brush: bash; title: ; notranslate">
$ [sudo] pip install httpcode
</pre>
<h3>Examples</h3>
<h5>Explain 405 status code</h5>
<pre class="brush: bash; title: ; notranslate">
$ hc 405
Status code 405
Message: Method Not Allowed
Code explanation: Specified method is invalid for this resource.
</pre>
<h5>List all codes</h5>
<pre class="brush: bash; title: ; notranslate">
$ hc
Status code 100
Message: Continue
Code explanation: Request received, please continue

Status code 101
Message: Switching Protocols
Code explanation: Switching to new protocol; obey Upgrade header

Status code 200
Message: OK
Code explanation: Request fulfilled, document follows

...
</pre>
<h5>Show help</h5>
<pre class="brush: bash; title: ; notranslate">
$ hc -h
Usage: hc 1

Without parameters lists all available
HTTP status codes and their description

Options:
  -h, --help  show this help message and exit
</pre>
<p>Check out the documentation <a href="http://httpcode.readthedocs.org/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/21/httpcode-explain-http-status-code-on-the-command-line/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SlimIt on Read the Docs</title>
		<link>http://ruslanspivak.com/2011/12/20/slimit-on-read-the-docs/</link>
		<comments>http://ruslanspivak.com/2011/12/20/slimit-on-read-the-docs/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 04:01:14 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1263</guid>
		<description><![CDATA[Quick update: 1. SlimIt is now available on Read the Docs 2. pip is now the only tool mentioned in installation documentation, no more easy_install. I also got a GitHub cake for that from Kenneth Reitz]]></description>
			<content:encoded><![CDATA[<p></p><p>Quick update:</p>
<p>1. <a href="http://github.com/rspivak/slimit">SlimIt</a> is now available on <a href="http://readthedocs.org/projects/slimit/">Read the Docs</a></p>
<p>2. <a href="http://pypi.python.org/pypi/pip">pip</a> is now the only tool mentioned in installation documentation, no more <del>easy_install</del>. I also got a <a href="http://github.com/rspivak/slimit/commit/1ef7f40b966fe1acd6ac462859931279df1b5594">GitHub cake</a> for that from <a href="http://github.com/kennethreitz">Kenneth Reitz</a> <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/20/slimit-on-read-the-docs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a custom node visitor with SlimIt</title>
		<link>http://ruslanspivak.com/2011/12/17/writing-a-custom-node-visitor-with-slimit/</link>
		<comments>http://ruslanspivak.com/2011/12/17/writing-a-custom-node-visitor-with-slimit/#comments</comments>
		<pubDate>Sat, 17 Dec 2011 05:05:49 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1224</guid>
		<description><![CDATA[I&#8217;ve added a base node visitor class ASTVisitor to SlimIt to reduce some boilerplate code required for writing a custom node visitor. The class itself is pretty simple and contains just two methods: a visit method that you want to call to process all node&#8217;s children and a generic_visit method that acts as a fallback [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve added a base node visitor class <a href="https://github.com/rspivak/slimit/blob/master/src/slimit/visitors/nodevisitor.py">ASTVisitor</a> to <a href="https://github.com/rspivak/slimit">SlimIt</a> to reduce some boilerplate code required for writing a custom node visitor.</p>
<p>The class itself is pretty simple and contains just two methods:</p>
<ul>
<li>a <em>visit</em> method that you want to call to process all node&#8217;s children and</li>
<li>a <em>generic_visit</em> method that acts as a fallback when your visitor doesn&#8217;t know how to visit a particular node</li>
</ul>
<p>Let&#8217;s say that you want to parse a JavaScript object literal. In order to do that your visitor has to inherit from <a href="https://github.com/rspivak/slimit/blob/master/src/slimit/visitors/nodevisitor.py">ASTVisitor</a> and add a <em>visit_Object</em> method. One thing to note here is a signature of the method: <code>def visit_NodeType(self, node)</code> where <em>NodeType</em> is the type of a node you want to visit. For a full list of available node types check out <code>ast.py</code> module on <a href="https://github.com/rspivak/slimit/blob/master/src/slimit/ast.py">GitHub</a></p>
<p>With that said the code to visit an object literal with our own node visitor now would look like this:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from slimit.parser import Parser
&gt;&gt;&gt; from slimit.visitors.nodevisitor import ASTVisitor
&gt;&gt;&gt;
&gt;&gt;&gt; text = &quot;&quot;&quot;
... var x = {
...     &quot;key1&quot;: &quot;value1&quot;,
...     &quot;key2&quot;: &quot;value2&quot;
... };
... &quot;&quot;&quot;
&gt;&gt;&gt;
&gt;&gt;&gt; class MyVisitor(ASTVisitor):
...     def visit_Object(self, node):
...         &quot;&quot;&quot;Visit object literal.&quot;&quot;&quot;
...         for prop in node:
...             left, right = prop.left, prop.right
...             print 'Property key=%s, value=%s' % (left.value, right.value)
...             # visit all children in turn
...             self.visit(prop)
...
&gt;&gt;&gt;
&gt;&gt;&gt; parser = Parser()
&gt;&gt;&gt; tree = parser.parse(text)
&gt;&gt;&gt; visitor = MyVisitor()
&gt;&gt;&gt; visitor.visit(tree)
Property key=&quot;key1&quot;, value=&quot;value1&quot;
Property key=&quot;key2&quot;, value=&quot;value2&quot;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/17/writing-a-custom-node-visitor-with-slimit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SFTP server with Python and Paramiko in under a minute</title>
		<link>http://ruslanspivak.com/2011/12/12/sftp-server-with-python-and-paramiko-in-under-a-minute/</link>
		<comments>http://ruslanspivak.com/2011/12/12/sftp-server-with-python-and-paramiko-in-under-a-minute/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 05:35:57 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1204</guid>
		<description><![CDATA[I needed a simple server that could be used as a stub for testing Python SFTP clients so I whipped out one over the weekend. It&#8217;s a simple single-threaded server so it&#8217;s not for production use but give it a try anyways, you might find it useful too. Installation: Running the server: Connecting with a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I needed a simple server that could be used as a stub for testing Python SFTP clients so I whipped out one over the weekend.<br />
It&#8217;s a simple single-threaded server so it&#8217;s not for production use but give it a try anyways, you might find it useful too.</p>
<p>Installation:</p>
<pre class="brush: bash; title: ; notranslate">
$ [sudo] pip install sftpserver
</pre>
<p>Running the server:</p>
<pre class="brush: bash; title: ; notranslate">

    $ sftpserver
    Usage: sftpserver [options]
    -k/--keyfile should be specified

    Options:
      -h, --help            show this help message and exit
      --host=HOST           listen on HOST [default: localhost]
      -p PORT, --port=PORT  listen on PORT [default: 3373]
      -l LEVEL, --level=LEVEL
                            Debug level: WARNING, INFO, DEBUG [default: INFO]
      -k FILE, --keyfile=FILE
                            Path to private key, for example /tmp/test_rsa.key

    $ sftpserver -k /tmp/test_rsa.key -l DEBUG
</pre>
<p>Connecting with a Python client to our server:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import paramiko
&gt;&gt;&gt; pkey = paramiko.RSAKey.from_private_key_file('/tmp/test_rsa.key')
&gt;&gt;&gt; transport = paramiko.Transport(('localhost', 3373))
&gt;&gt;&gt; transport.connect(username='admin', password='admin', pkey=pkey)
&gt;&gt;&gt; sftp = paramiko.SFTPClient.from_transport(transport)
&gt;&gt;&gt; sftp.listdir('.')
['loop.py', 'stub_sftp.py']
</pre>
<p>The server code itself is pretty minimal, check it out on <a href="https://github.com/rspivak/sftpserver">GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/12/sftp-server-with-python-and-paramiko-in-under-a-minute/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Parsing JavaScript object literals with SlimIt</title>
		<link>http://ruslanspivak.com/2011/12/09/parsing-javascript-object-literals-with-slimit/</link>
		<comments>http://ruslanspivak.com/2011/12/09/parsing-javascript-object-literals-with-slimit/#comments</comments>
		<pubDate>Sat, 10 Dec 2011 04:48:42 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1194</guid>
		<description><![CDATA[I got a question about how to get to the values of object literal properties with SlimIt. Here is one way to do it with a custom node visitor:]]></description>
			<content:encoded><![CDATA[<p></p><p>I got a question about how to get to the values of object literal properties with <a href="http://slimit.org/">SlimIt</a>.<br />
Here is one way to do it with a custom node visitor:</p>
<pre class="brush: python; title: ; notranslate">
# parseobj.py
from slimit.parser import Parser

text = &quot;&quot;&quot;
var x = {
    &quot;key1&quot;: &quot;value1&quot;,
    &quot;key2&quot;: &quot;value2&quot;
};
&quot;&quot;&quot;

class MyVisitor(object):
    def visit(self, node):
        method = 'visit_%s' % node.__class__.__name__
        return getattr(self, method, self.generic_visit)(node)

    def generic_visit(self, node):
        for child in node:
            self.visit(child)

    def visit_Object(self, node):
        &quot;&quot;&quot;Visit object literal.&quot;&quot;&quot;
        for prop in node:
            left, right = prop.left, prop.right
            print 'Property value: %s' % right.value
            # visit all children in turn
            self.visit(prop)

parser = Parser()
tree = parser.parse(text)
visitor = MyVisitor()
visitor.visit(tree)

$ python parseobj.py
Property value: &quot;value1&quot;
Property value: &quot;value2&quot;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/09/parsing-javascript-object-literals-with-slimit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parsing fixed length file records with Python</title>
		<link>http://ruslanspivak.com/2011/12/08/parsing-fixed-length-file-records-with-python/</link>
		<comments>http://ruslanspivak.com/2011/12/08/parsing-fixed-length-file-records-with-python/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 03:55:34 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1180</guid>
		<description><![CDATA[I&#8217;ve recently had to deal with parsing fixed-length file records and found struct.unpack and namedtuple to be a pretty useful and concise combination for the task:]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve recently had to deal with parsing fixed-length file records and found <a href="http://docs.python.org/library/struct.html#module-struct">struct.unpack</a> and <a href="http://docs.python.org/library/collections.html#collections.namedtuple">namedtuple</a> to be a pretty useful and concise combination for the task:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from struct import unpack
&gt;&gt;&gt; from collections import namedtuple
&gt;&gt;&gt; line = '    23C   17000'
&gt;&gt;&gt; Transaction = namedtuple('Transaction', 'code status amount')
&gt;&gt;&gt; format = '&lt;6sc8s' # code: 6bytes, status: 1byte, amount: 8bytes
&gt;&gt;&gt; txn = Transaction._make(unpack(format, line))
&gt;&gt;&gt; txn
Transaction(code='    23', status='C', amount='   17000')
&gt;&gt;&gt; txn.code, txn.status, txn.amount
('    23', 'C', '   17000')
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/12/08/parsing-fixed-length-file-records-with-python/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to convert Python UTC datetime object to UNIX timestamp</title>
		<link>http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/</link>
		<comments>http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/#comments</comments>
		<pubDate>Thu, 21 Jul 2011 04:04:53 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1153</guid>
		<description><![CDATA[I seem to get this question every half a year and every time I have difficulties remembering how to do it. So here is the snippet that I use to convert datetime to timestamp: Let&#8217;s verify it: Looks fine, but I can&#8217;t for the life of me understand why the function timegm is part of [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I seem to get this question every half a year and every time I have difficulties remembering how to do it.</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; d = datetime.utcnow()
&gt;&gt;&gt; d
datetime.datetime(2011, 7, 21, 3, 13, 22, 259901)
</pre>
<p>So here is the snippet that I use to convert datetime to timestamp:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import calendar
&gt;&gt;&gt; calendar.timegm(d.utctimetuple())
1311218002
</pre>
<p>Let&#8217;s verify it:</p>
<pre class="brush: bash; title: ; notranslate">
$ date -ud @1311218002
Thu Jul 21 03:13:22 UTC 2011
</pre>
<p>Looks fine, but I can&#8217;t for the life of me understand why the function <em>timegm</em> is part of the <em>calendar</em> module.</p>
<p>From Python official documentation:</p>
<dl>
<dt><tt>calendar.</tt><tt>timegm</tt><big>(</big><em>tuple</em><big>)</big></dt>
<dd>An unrelated but handy function that takes a time tuple such as returned by the <tt>gmtime()</tt> function in the <a title="Time access and conversions." href="http://docs.python.org/library/time.html#module-time"><tt>time</tt></a> module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, <a title="time.gmtime" href="http://docs.python.org/library/time.html#time.gmtime"><tt>time.gmtime()</tt></a> and <a title="calendar.timegm" href="http://docs.python.org/library/calendar.html#calendar.timegm"><tt>timegm()</tt></a> are each others’ inverse.</dd>
</dl>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Nice logging feature in Erlang</title>
		<link>http://ruslanspivak.com/2011/06/22/nice-logging-feature-in-erlang/</link>
		<comments>http://ruslanspivak.com/2011/06/22/nice-logging-feature-in-erlang/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 03:50:17 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1128</guid>
		<description><![CDATA[Have you ever had, at least once, an exception when logging an exception because you&#8217;d screwed up the number of logging arguments? Something akin to the following: Here is what you get in Erlang: That&#8217;s right &#8211; you get &#8216;ok&#8217; and a report. That allows you to get critical information even if there is a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Have you ever had, at least once, an exception when logging an exception because you&#8217;d screwed up the number of logging arguments?</p>
<p>Something akin to the following:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import logging
&gt;&gt;&gt; msg1, msg2 = 'Look', 'leap!'
&gt;&gt;&gt; try:
...     1 / 0
... except Exception:
...     # crash and burn - no msg2. where is my unit test?!!!
...     logging.exception('%s before you %s', msg1)
...
Traceback (most recent call last):
  ...
TypeError: not enough arguments for format string
</pre>
<p>Here is what you get in Erlang:</p>
<pre class="brush: erlang; title: ; notranslate">
1&gt; error_logger:info_msg(&quot;~s before you ~s~n&quot;, [&quot;Look&quot;]).
ok

=INFO REPORT==== 22-Jun-2011::23:09:49 ===
ERROR: &quot;~s before you ~s~n&quot; - [&quot;Look&quot;]
2&gt;
</pre>
<p>That&#8217;s right &#8211; you get <strong>&#8216;ok&#8217;</strong> and a report. That allows you to get critical information even if there is a problem with your log message arguments without blowing your whole system. I like that, makes the system more fault-tolerant.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/06/22/nice-logging-feature-in-erlang/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The Bunch Pattern</title>
		<link>http://ruslanspivak.com/2011/06/12/the-bunch-pattern/</link>
		<comments>http://ruslanspivak.com/2011/06/12/the-bunch-pattern/#comments</comments>
		<pubDate>Sun, 12 Jun 2011 23:41:00 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1119</guid>
		<description><![CDATA[It&#8217;s good to know a name for such a useful pattern, so here we go &#8211; The Bunch Pattern.]]></description>
			<content:encoded><![CDATA[<p></p><p>It&#8217;s good to know a name for such a useful pattern, so here we go &#8211; <a href="http://books.google.com/books?id=9_AXCmGDiz8C&amp;lpg=PA9&amp;pg=PA34#v=onepage&amp;q&amp;f=false">The Bunch Pattern</a>.</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; class Bunch(dict):
...     def __init__(self, *args, **kw):
...         super(Bunch, self).__init__(*args, **kw)
...         self.__dict__ = self
...
&gt;&gt;&gt; bunch = Bunch(name='Bunch', category='pattern')
&gt;&gt;&gt; bunch.name
'Bunch'
&gt;&gt;&gt; bunch['name']
'Bunch'
&gt;&gt;&gt; 'pattern' in bunch
False
&gt;&gt;&gt; bunch.pattern = True
&gt;&gt;&gt; 'pattern' in bunch
True
&gt;&gt;&gt; bunch
{'category': 'pattern', 'pattern': True, 'name': 'Bunch'}
&gt;&gt;&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/06/12/the-bunch-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Power set generation &#8211; a joy of Python</title>
		<link>http://ruslanspivak.com/2011/06/09/power-set-generation-a-joy-of-python/</link>
		<comments>http://ruslanspivak.com/2011/06/09/power-set-generation-a-joy-of-python/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 01:12:43 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1062</guid>
		<description><![CDATA[When I worked on name mangling in SlimIt I needed a function that would generate subsets of a character string in lexicographic order. For example, if I had a character sequence &#8216;abc&#8217; I would expect to call my function and get items in the following order: &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;ab&#8217;, &#8216;ac&#8217;, &#8216;bc&#8217;, &#8216;abc&#8217;. The produced [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When I worked on name mangling in <a href="http://slimit.org/">SlimIt</a> I needed a function that would  generate subsets of a character string in lexicographic order.<br />
 For example, if I had a character sequence <em>&#8216;abc&#8217;</em> I would expect to call my function and get items in the following order: <em>&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;ab&#8217;, &#8216;ac&#8217;, &#8216;bc&#8217;, &#8216;abc&#8217;</em>. The produced sequence is called a <a href="http://en.wikipedia.org/wiki/Power_set">power set</a> and <a href="http://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK4/NODE152.HTM">binary counting</a> is a well known algorithm for generating such power sets . </p>
<p>The idea is that we represent our character sequence as a binary string of <strong><em>n</em></strong> bits, then start counting from zero to <em>2**n &#8211; 1</em> and if a bit <strong><em> k</em></strong> is set to <strong>1</strong> then we would put <strong><em>k</em>-th</strong> element from the character sequence into an output set.<br />
Let&#8217;s say we have a sequence &#8216;abc&#8217;, then counting to <em>2**3 &#8211; 1</em> would produce binary numbers 000, 001, 010, 011, 100, &#8230;, which correspond to &#8221;, &#8216;c&#8217;, &#8216;b&#8217;, &#8216;bc&#8217;, &#8216;a&#8217;, &#8230;, in the character sequence.</p>
<p>Code for binary counting looks like this (credit for original implementation goes to <a href="http://mail.python.org/pipermail/tutor/2004-March/028588.html">Tim Peters</a>):</p>
<pre class="brush: python; title: ; notranslate">
def powerset(s):
    &quot;&quot;&quot;powerset('abc') -&gt; a b ab c ac bc abc&quot;&quot;&quot;
    pairs = [(2**index, char) for index, char in enumerate(s)]
    for index in xrange(1, 2**len(s)):
        yield ''.join(char for mask, char in pairs if mask &amp; index)
</pre>
<p>And while it generates all necessary subsets they are not in lexicographic order.</p>
<p>So I decided to look at <em>itertools</em> module and check closer some properties of the <em>combinations</em> function available there and see if it could fit for my purposes and &#8211; wouldn&#8217;t you know it? &#8211; at the very  bottom of the module&#8217;s documentation page I found a <a href="http://docs.python.org/library/itertools.html#recipes">powerset recipe</a> that did just what I needed using <em>combinations</em> function.<br />
Here is a little bit adapted version of it:</p>
<pre class="brush: python; title: ; notranslate">
import itertools

def powerset(s):
    &quot;&quot;&quot;powerset('abc') -&gt; a b c ab ac bc abc&quot;&quot;&quot;
    for chars in itertools.chain.from_iterable(
        itertools.combinations(s, r) for r in range(1, len(s)+1)
        ):
        yield ''.join(chars)
</pre>
<p>I&#8217;ve been using Python for a long time now and still continue to bump into elegant solutions in Python standard library and that&#8217;s what I call the joy of Python <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/06/09/power-set-generation-a-joy-of-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Name mangling in SlimIt 0.5</title>
		<link>http://ruslanspivak.com/2011/06/06/name-mangling-in-slimit-0-5/</link>
		<comments>http://ruslanspivak.com/2011/06/06/name-mangling-in-slimit-0-5/#comments</comments>
		<pubDate>Mon, 06 Jun 2011 05:08:47 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1047</guid>
		<description><![CDATA[SlimIt 0.5 is out. This release includes name mangling that can be turned on with -m or &#8211;mangle flag from the command line. To give you a taste of what it&#8217;s like here is a simple example: After name mangling: And here is a new jQuery 1.6.1 minification benchmark for jsmin, rJSmin, and SlimIt (the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://slimit.org/">SlimIt 0.5</a> is out. This release includes name mangling that can be turned on with <em>-m</em> or <em>&#8211;mangle</em> flag from the command line.</p>
<p>To give you a taste of what it&#8217;s like here is a simple example:</p>
<pre class="brush: jscript; title: ; notranslate">
function test() {
  var long_name = 'long name', log = 5;
  console.log(long_name);
  foo = function(arg1, arg2) {
    var arg2 = 'new arg2';
    console.log(long_name + arg1 + arg2);
  };
}
</pre>
<p>After name mangling:</p>
<pre class="brush: jscript; title: ; notranslate">
function a() {
  var a = 'long name', b = 5;
  console.log(a);
  foo = function(b, c) {
    var c = 'new arg2';
    console.log(a + b + c);
  };
}
</pre>
<p>And here is a new <a href="http://code.jquery.com/jquery-1.6.1.js">jQuery 1.6.1</a> minification benchmark for <a href="http://pypi.python.org/pypi/jsmin/2.0.2">jsmin</a>, <a href="http://opensource.perlig.de/rjsmin/">rJSmin</a>, and <a href="http://slimit.org/">SlimIt</a> (the lower the better):</p>
<table>
<thead>
<tr>
<th>jQuery 1.6.1 (bytes)</th>
<th>jsmin</th>
<th>rJSmin</th>
<th>SlimIt</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>234,995</strong></td>
<td><strong>134,819</strong></td>
<td><strong>134,215</strong></td>
<td><strong>94,290</strong></td>
</tr>
</tbody>
</table>
<p>Please, file any bug reports at <a href="https://github.com/rspivak/slimit">GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/06/06/name-mangling-in-slimit-0-5/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>SlimIt 0.4 released: block braces removal</title>
		<link>http://ruslanspivak.com/2011/05/12/slimit-0-4-released-block-braces-removal/</link>
		<comments>http://ruslanspivak.com/2011/05/12/slimit-0-4-released-block-braces-removal/#comments</comments>
		<pubDate>Fri, 13 May 2011 04:51:37 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=1017</guid>
		<description><![CDATA[SlimIt 0.4 is released and it features block braces removal during minification process. If a block statement contains only one source element then curly braces around that statement are removed by SlimIt: after minification will become: And will become There is one case where braces removal gets tricky. Take a look at the following JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://slimit.org/">SlimIt 0.4</a> is released and it features block braces removal during minification process.</p>
<p>If a block statement contains only one source element then curly braces around that statement are removed by <a href="http://slimit.org/">SlimIt</a>:</p>
<pre class="brush: jscript; title: ; notranslate">
with (obj) {
    a = b;
}
</pre>
<p>after minification will become:</p>
<pre class="brush: jscript; title: ; notranslate">
with(obj)a=b;
</pre>
<p>And</p>
<pre class="brush: jscript; title: ; notranslate">
if (true) {
    x = 1;
} else {
    x = 0;
}
</pre>
<p>will become </p>
<pre class="brush: jscript; title: ; notranslate">
if(true)x=1;else x=0;
</pre>
<p>There is one case where braces removal gets tricky. Take a look at the following JavaScript code:</p>
<pre class="brush: jscript; title: ; notranslate">
if ( obj ) {
    for ( n in obj ) {
        if ( v === false) {
            break;
        }
    }
} else {
    for ( ; i &lt; l; ) {
        if ( nv === false ) {
            break;
        }
    }
}
</pre>
<p>If we blindly remove all block braces result will be the following (output is indented and formatted to illustrate the point):</p>
<pre class="brush: jscript; title: ; notranslate">
if (obj)
    for (n in obj)
        if (v === false)
            break;
else
    for (; i &lt; l; )
        if (nv === false)
            break;
</pre>
<p>but it will be interpreted by a JavaScript parser as</p>
<pre class="brush: jscript; title: ; notranslate">
if (obj)
    for (n in obj)
        if (v === false)
            break;
        else
            for (; i &lt; l; )
                if (nv === false)
                    break;
</pre>
<p>because <em><strong>else</strong></em> part will be associated with the closest <em><strong>if</strong></em> and that&#8217;s not what was described by the original pre-miniified source code. Because of that the <a href="http://slimit.org/">minifier</a> will convert such construct to the following form to avoid ambiguity but still performing minification where possible (indented for illustration purpose):</p>
<pre class="brush: jscript; title: ; notranslate">
if (obj) {
    for (n in obj)
        if (v === false)
            break;
} else
    for (; i &lt; l; )
        if (nv === false)
            break;
</pre>
<p>And this is how it&#8217;ll look like in minified form:</p>
<pre class="brush: jscript; title: ; notranslate">
if(obj){for(n in obj)if(v===false)break;}else for(;i&lt;l;)if(nv===false)break;')
</pre>
<p>
Here are some new numbers for <a href="http://pypi.python.org/pypi/jsmin/2.0.2">jsmin</a>, <a href="http://opensource.perlig.de/rjsmin/">rJSmin</a>, and <a href="http://slimit.org/">SlimIt</a> minification of <a href="http://code.jquery.com/jquery-1.6.1.js">jQuery 1.6.1</a>:</p>
<table>
<thead>
<tr>
<th>jQuery 1.6.1 (bytes)</th>
<th>jsmin</th>
<th>rJSmin</th>
<th>SlimIt</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>234,995</strong></td>
<td><strong>134,819</strong></td>
<td><strong>134,215</strong></td>
<td><strong>132,336</strong></td>
</tr>
</tbody>
</table>
<p><em>P.S:</em> After minification by <a href="http://slimit.org/">SlimIt</a> I ran a test suite that comes with jQuery against the minified version and got the same results as with<a href="http://code.jquery.com/jquery-1.6.1.min.js"> official minified version</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/05/12/slimit-0-4-released-block-braces-removal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SlimIt &#8211; a little benchmark</title>
		<link>http://ruslanspivak.com/2011/05/09/slimit-a-little-benchmark/</link>
		<comments>http://ruslanspivak.com/2011/05/09/slimit-a-little-benchmark/#comments</comments>
		<pubDate>Tue, 10 May 2011 02:46:07 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=985</guid>
		<description><![CDATA[SlimIt is in its infancy yet but it can already minify some stuff out. Here is a comparison of jsmin and SlimIt minification of jQuery 1.6: jQuery 1.6 (bytes) jsmin (bytes) SlimIt (bytes) 232,651 133,502 132,538 As you can see SlimIt on this source file performs better reducing jquery-1.6.js by additional 964 bytes. I have [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://packages.python.org/slimit/">SlimIt</a> is in its infancy yet but it can already minify some stuff out.</p>
<p>Here is a comparison of <a href="http://pypi.python.org/pypi/jsmin/2.0.2">jsmin</a> and <a href="http://slimit.org/">SlimIt</a> minification of <a href="http://code.jquery.com/jquery-1.6.js">jQuery 1.6</a>:</p>
<table>
<thead>
<tr>
<th>jQuery 1.6 (bytes)</th>
<th>jsmin (bytes)</th>
<th>SlimIt (bytes)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>232,651</strong></td>
<td><strong>133,502</strong></td>
<td><strong>132,538</strong></td>
</tr>
</tbody>
</table>
<p>As you can see <a href="http://slimit.org/">SlimIt</a> on this source file performs better reducing <em>jquery-1.6.js</em> by additional <strong>964</strong> bytes.</p>
<p>I have to note though that <a href="http://slimit.org/">SlimIt</a> is currently slower than <a href="http://pypi.python.org/pypi/jsmin/2.0.2">jsmin</a> and there are two contributing factors:<br />
1. SlimIt is a complete source-to-source compiler where you have a parser. a lexer and the parser constructs an AST and then minified code is generated by an AST tree walker.<br />
2. Minifier/tree walker uses <strong>+=</strong> operator when concatenating strings and it hurts performance on large strings and multiple concatenations.<br />
Standard solution is to use <strong><em>list.append()</em></strong> and <strong><em>&#8221;.join()</em></strong> methods because they are faster, but I didn&#8217;t bother with the speed for now (that will be the target of next releases) &#8211; as they say <em>&#8220;Make it work first, then make it faster&#8221;</em>.</p>
<p>Due to the nature of the <a href="http://slimit.org/">minifier</a> (<em>source-to-source compiler</em>) there are many ways how to improve minification considerably, so stay tuned &#8211; next releases will give even more bang for the buck.</p>
<p><strong>UPDATE</strong>: Looks like <a href="http://slimit.org">http://slimit.org</a> doesn&#8217;t work reliably for everyone so here is a direct link to documentation where you&#8217;ll find all necessary information with further links: <a href="http://packages.python.org/slimit/">http://packages.python.org/slimit</a> Meanwhile I&#8217;ll be looking for a place to host the package&#8217;s documentation reliably with <em>slimit.org</em> domain.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/05/09/slimit-a-little-benchmark/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SlimIt 0.3.2 is released. Go minify some JavaScript.</title>
		<link>http://ruslanspivak.com/2011/05/09/slimit-0-3-2-is-released-go-minify-some-javascript/</link>
		<comments>http://ruslanspivak.com/2011/05/09/slimit-0-3-2-is-released-go-minify-some-javascript/#comments</comments>
		<pubDate>Mon, 09 May 2011 08:16:22 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=978</guid>
		<description><![CDATA[New release is out and SlimIt 0.3.2 (http://slimit.org) can now minify JavaScript code. Let&#8217;s do it from the command line: And using library API: If you find any issues, please, submit them at GitHub. Happy minifying]]></description>
			<content:encoded><![CDATA[<p></p><p>New release is out and <a href="http://packages.python.org/slimit/">SlimIt 0.3.2</a> (<a href="http://slimit.org">http://slimit.org</a>) can now minify JavaScript code.</p>
<p>Let&#8217;s do it from the command line:</p>
<pre class="brush: bash; title: ; notranslate">
$ slimit -h
Usage: slimit [input file]

If no input file is provided STDIN is used by default.
Minified JavaScript code is printed to STDOUT.

$ cat test.js
var a = function( obj ) {
        for ( var name in obj ) {
                return false;
        }
        return true;
};
$
$ slimit &lt; test.js
var a=function(obj){for(var name in obj){return false;}return true;};
</pre>
<p>And using library API:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from slimit import minify
&gt;&gt;&gt; text = &quot;&quot;&quot;
... var a = function( obj ) {
...         for ( var name in obj ) {
...                 return false;
...         }
...         return true;
... };
... &quot;&quot;&quot;
&gt;&gt;&gt; print minify(text)
var a=function(obj){for(var name in obj){return false;}return true;};
</pre>
<p>If you find any issues, please, submit them at <a href="https://github.com/rspivak/slimit">GitHub</a>.</p>
<p>Happy minifying <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/05/09/slimit-0-3-2-is-released-go-minify-some-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SlimIt 0.2 is out with a JavaScript parser, pretty printer and a node visitor</title>
		<link>http://ruslanspivak.com/2011/05/07/slimit-0-2-is-out-with-a-javascript-parser-pretty-printer-and-a-node-visitor/</link>
		<comments>http://ruslanspivak.com/2011/05/07/slimit-0-2-is-out-with-a-javascript-parser-pretty-printer-and-a-node-visitor/#comments</comments>
		<pubDate>Sun, 08 May 2011 01:12:44 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=956</guid>
		<description><![CDATA[SlimIt 0.2 (should be also accessible via http://slimit.org) got a JavaScript parser, pretty printer and a node visitor. Let&#8217;s iterate over, modify a JavaScript AST and pretty print it: SlimIt comes with a bunch of tests and I also used it to parse and pretty print jQuery 1.5.2 which I then tested in a browser [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://packages.python.org/slimit/">SlimIt 0.2</a> (should be also accessible via <a href="http://slimit.org">http://slimit.org</a>) got a JavaScript parser, pretty printer and a node visitor.</p>
<p>Let&#8217;s iterate over, modify a JavaScript AST and pretty print it:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from slimit.parser import Parser
&gt;&gt;&gt; from slimit.visitors import nodevisitor
&gt;&gt;&gt; from slimit import ast
&gt;&gt;&gt;
&gt;&gt;&gt; parser = Parser()
&gt;&gt;&gt; tree = parser.parse('for(var i=0; i&lt;10; i++) {var x=5+i;}')
&gt;&gt;&gt; for node in nodevisitor.visit(tree):
...     if isinstance(node, ast.Identifier) and node.value == 'i':
...         node.value = 'hello'
...
&gt;&gt;&gt; print tree.to_ecma() # print awesome javascript <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
for (var hello = 0; hello &lt; 10; hello++) {
  var x = 5 + hello;
}
&gt;&gt;&gt;
</pre>
<p><a href="http://packages.python.org/slimit/">SlimIt</a> comes with a bunch of tests and I also used it to parse and pretty print <a href="http://code.jquery.com/jquery-1.5.2.js"> jQuery 1.5.2</a> which I then tested in a browser and it worked fine. But, you know, software is not perfect <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  If you find any issues, please, submit them at <a href="https://github.com/rspivak/slimit">GitHub</a>.</p>
<p>Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/05/07/slimit-0-2-is-out-with-a-javascript-parser-pretty-printer-and-a-node-visitor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SlimIt &#8211; a JavaScript minifier-to-be is released</title>
		<link>http://ruslanspivak.com/2011/05/02/slimit-a-javascript-minifier-to-be-is-released/</link>
		<comments>http://ruslanspivak.com/2011/05/02/slimit-a-javascript-minifier-to-be-is-released/#comments</comments>
		<pubDate>Tue, 03 May 2011 03:44:58 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[slimit]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=929</guid>
		<description><![CDATA[SlimIt 0.1 is out. This release contains only a JavaScript lexer and doesn&#8217;t minify anything yet. Why to release when it doesn&#8217;t minify yet? The foundation of the source-to-source compiler is a working lexer, so I decided to release it early on the off chance interested people would test it and report any issues with [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://slimit.org">SlimIt</a> 0.1 is out. This release contains only a JavaScript lexer and doesn&#8217;t minify anything yet.</p>
<p>Why to release when it doesn&#8217;t minify yet?</p>
<p>The foundation of the source-to-source compiler is a working lexer, so I decided to release it early on the off chance interested people would test it and report any issues with it while I work on parser and translator parts and some might even find the lexer useful on its own.</p>
<p>To install <a href="http://slimit.org/"><em>SlimIt</em></a> just run:</p>
<pre>$ sudo pip install slimit</pre>
<p>Then you can use it in your programs like this:</p>
<pre>&gt;&gt;&gt; from slimit.lexer import Lexer
&gt;&gt;&gt; lexer = Lexer()
&gt;&gt;&gt; lexer.input('a = 1;')
&gt;&gt;&gt; for token in lexer:
...     print token
...
LexToken(ID,'a',1,0)
LexToken(EQ,'=',1,2)
LexToken(NUMBER,'1',1,4)
LexToken(SEMI,';',1,5)</pre>
<p>For more information and examples visit <a href="http://slimit.org">http://slimit.org</a></p>
<p>Here are two new things I learned about JavaScript when working on this release:</p>
<p>1. Identifiers can contain unicode escape sequences but not all of them are allowed (for allowed unicode categories check out section 7.6 of <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMA-262 specification</a>).</p>
<p>This one is valid:</p>
<pre> var u03c0_tail = 7;</pre>
<p>But this one is not:</p>
<pre> var u0036_tail = 3;</pre>
<p>Per specification (section 7.6 of <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMA-262</a>):</p>
<pre>"A UnicodeEscapeSequence cannot be used to put a character into an IdentifierName that would
 otherwise be illegal. In other words, if a  UnicodeEscapeSequence sequence were replaced by its
 UnicodeEscapeSequence's CV, the result must still be valid IdentifierName that has the exact
 same sequence of characters as the original IdentifierName."</pre>
<p>That rule basically explains why <strong>u0036_tail</strong> is not a legal identifier. It happens because character value (CV) of <strong>u0036</strong> is <em>DIGIT SIX</em> and <strong>6_tail</strong> is not a valid identifier because an identifier can&#8217;t start with a digit.</p>
<p>2. Ambiguity at a lexical level between <strong>/</strong>, <strong>/=</strong> and <em>regex literal</em>.<br />
This case has to be handled separately in the code by keeping track of a previous token, bummer.</p>
<p>Here are two examples from <a href="http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions">Mozilla site</a> that demonstrate the problem at hand:</p>
<pre>for (var x = a in foo &amp;&amp; "&lt;/x&gt;" || mot ? z:<span style="color:#ff0000;">/x:3;x&lt;5;y&lt;/g/i</span>) {xyz(x++);}
for (var x = a in foo &amp;&amp; "&lt;/x&gt;" || mot ? <span style="color:#ff0000;">z/x</span>:3;x&lt;5;y&lt;<span style="color:#ff0000;">/g/i</span>) {xyz(x++);}</pre>
<p>In the first example <strong>/x:3;x&lt;5;y&lt;/g/i</strong> is a <em>regex literal</em>, in the second it&#8217;s <strong>/g/i</strong> because <strong>z/x</strong> is interpreted as <em>division</em>.</p>
<p>I&#8217;d like to thank <a href="http://nedbatchelder.com/blog/201104/a_javascript_lexer_in_python_and_the_saga_behind_it.html">Ned Batchelder</a> for releasing code of <em>jslex</em>. I used many test cases and some regex matchers from that project.</p>
<p><strong>UPDATE</strong>: Some people experienced problems when accessing <a href="http://slimit.org">http://slimit.org</a> &#8211; redirection didn&#8217;t work properly. Check out <a href="http://packages.python.org/slimit/">this page</a> if you had that issue.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/05/02/slimit-a-javascript-minifier-to-be-is-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to indent a block of text in Emacs</title>
		<link>http://ruslanspivak.com/2011/04/28/how-to-indent-a-block-of-text-in-emacs/</link>
		<comments>http://ruslanspivak.com/2011/04/28/how-to-indent-a-block-of-text-in-emacs/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 22:05:18 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=911</guid>
		<description><![CDATA[Sometimes I need to indent a block of text in Emacs regardless of current major mode. A key binding that fits the bill is C-x TAB which runs the command indent-rigidly. If used with prefix argument C-u it will indent by specified number of spaces, so pressing C-u 8 C-x TAB after marking a block [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes I need to indent a block of text in Emacs regardless of current major mode. A key binding that fits the bill is <em><strong>C-x TAB</strong></em> which runs the command <em><strong>indent-rigidly</strong></em>.</p>
<p>If used with prefix argument <em><strong>C-u</strong></em> it will indent by specified number of spaces, so pressing <em><strong>C-u 8 C-x TAB</strong></em> after marking a block of text will indent that block by <em>8</em> spaces and <em><strong>C-u -8 C-x TAB</strong></em> will remove <em>8</em> spaces of indentation.<em><strong></strong></em><strong><em> </em></strong>There is a nice shortcut: <em><strong>C-u C-x TAB</strong></em> will indent a block of text by <em>4</em> spaces.</p>
<p>When in <a href="https://code.launchpad.net/python-mode">Python mode</a> marking a region and pressing <em><strong>C-c &gt;</strong></em> to shift lines in region to the right and <em><strong>C-c &lt;</strong></em> to shift lines in region to the left works perfectly well too.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/04/28/how-to-indent-a-block-of-text-in-emacs/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Simple HTTP server from the command line</title>
		<link>http://ruslanspivak.com/2011/03/30/simple-http-server-from-the-command-line/</link>
		<comments>http://ruslanspivak.com/2011/03/30/simple-http-server-from-the-command-line/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 01:45:17 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=900</guid>
		<description><![CDATA[I&#8217;ve been using this small Python gem for couple years now and it really comes in handy when you need a quick web server running without setting up nginx or apache or what have you. Just open up a terminal and type:﻿ $ python -m SimpleHTTPServer Serving HTTP on 0.0.0.0 port 8000 ... Now check [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been using this small Python gem for couple years now and it really comes in handy when you need a quick web server running without setting up nginx or apache or what have you.</p>
<p>Just open up a terminal and type:﻿</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...</pre>
<p>Now check it in your browser: http://localhost:8000/</p>
<p>You can also change port the server is listening on:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ python -m SimpleHTTPServer 7070
Serving HTTP on 0.0.0.0 port 7070 ...</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/03/30/simple-http-server-from-the-command-line/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Register-Based Virtual Machine for TinyPie</title>
		<link>http://ruslanspivak.com/2011/02/08/register-based-virtual-machine-for-tinypie/</link>
		<comments>http://ruslanspivak.com/2011/02/08/register-based-virtual-machine-for-tinypie/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 05:23:43 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[compilers]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=847</guid>
		<description><![CDATA[After finishing up initial work for the TinyPie interpreter and AST visualizer I&#8217;m well on my way to TinyPie compiler. For simplicity reasons and to better understand different parts involved I decided to go with Register-Based Bytecode Interpreter / Virtual Machine , like the one used by Lua and Dalvik, instead of directly generating binary [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>After finishing up initial work for the <a href="http://github.com/rspivak/tinypie">TinyPie</a> <a href="http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/">interpreter</a> and <a href="http://ruslanspivak.com/2011/01/23/ast-visualizer-for-tinypie/">AST visualizer</a> I&#8217;m well on my way to TinyPie compiler.</p>
<p>For simplicity reasons and to better understand different parts involved I decided to go with <a href="http://en.wikipedia.org/wiki/Virtual_machine">Register-Based Bytecode Interpreter / Virtual Machine</a> , like the one used by<a href="http://www.lua.org/doc/jucs05.pdf"> Lua</a> and <a href="http://en.wikipedia.org/wiki/Dalvik_(software)">Dalvik</a>, instead of directly generating binary code for target architecture. The main source of inspiration, ideas, and examples were the book <a href="http://pragprog.com/titles/tpdsl/language-implementation-patterns">Language Implementation Patterns</a> Ch.10(Building Bytecode Interpreters) and the paper <a href="http://www.lua.org/doc/jucs05.pdf">The Implementation of Lua 5.0</a></p>
<p>Here is a quick overview of developed components:</p>
<ol>
<li>Bytecode Assembler</li>
<li>Register-Based Virtual Machine</li>
</ol>
<p><em><strong>Bytecode Assembler</strong></em> converts assembly program into binary bytecodes. The bytecode is further interpreted by the TinyPie Register-Based Bytecode Interpreter / Virtual Machine.</p>
<p>TinyPie Assembly language grammar:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/asmgrammar.png"><img class="aligncenter size-full wp-image-854" title="asmgrammar" src="http://ruslanspivak.files.wordpress.com/2011/02/asmgrammar.png" alt="" width="460" height="162" /></a></p>
<p>Assembler yields the following components:</p>
<ol>
<li><em>Code memory</em>: This is a <code>bytearray</code> containing bytecode instructions and their operands derived from the assembly source code.</li>
<li><em>Global data memory size</em>: The number of slots allocated in global memory for use with GSTORE and GLOAD assembly commands.</li>
<li><em>Program entry point</em>: An address of main function <code>.def main: ...</code></li>
<li><em>Constant pool</em>: A list of objects (integers, strings, function symbols) that are not part of the code memory. Bytecode instructions refer to those objects via integer index.</li>
</ol>
<p>Here is a factorial function in TinyPie language:</p>
<p style="text-align:center;"><a href="http://ruslanspivak.files.wordpress.com/2011/02/asmfacthighlevel.png"><img class="size-full wp-image-856 aligncenter" title="asmfacthighlevel" src="http://ruslanspivak.files.wordpress.com/2011/02/asmfacthighlevel.png" alt="" width="230" height="110" /></a></p>
<p>Here is an equivalent TinyPie assembly code:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/asm.png"><img class="aligncenter size-full wp-image-860" title="asm" src="http://ruslanspivak.files.wordpress.com/2011/02/asm.png" alt="" width="460" height="320" /></a></p>
<p>Here are the resulting elements produced by the Bytecode Assembler after translating the above assembly code:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/asmcoredump.png"><img class="aligncenter size-full wp-image-862" title="asmcoredump" src="http://ruslanspivak.files.wordpress.com/2011/02/asmcoredump.png" alt="" width="460" height="349" /></a><br />
<em><strong>Virtual Machine architecture</strong></em>(<em>Virtual Machine</em> simulates a hardware processor with general-purpose registers.):</p>
<ol>
<li><strong>IP</strong>: Instruction pointer register that points into the <em>code memory</em> at the next instruction to execute.</li>
<li><strong>CPU</strong>: Instruction dispatcher that simulates <em>fetch-decode-execute</em> cycle with a <em>switch</em> (if elif) statement in a loop &#8211; reads bytecode at IP, decodes its operands and executes corresponding operation.</li>
<li><strong>Global data memory</strong>: a list of global objects. Contents is accessed via integer index.</li>
<li><strong>Code memory</strong>: Holds bytecode instructions and their operands.</li>
<li><strong>Call stack</strong>: Holds StackFrame objects with function return address, parameters, and local variables.</li>
<li><strong>Stack frame</strong>: A StackFrame object that holds all required information to invoke a function:
<ul>
<li>function symbol</li>
<li>function return address</li>
<li>registers hold return value, arguments, locals, and temporary values</li>
</ul>
</li>
<li><strong>FP</strong>: Frame pointer &#8211; a special-purpose register that points to the top of the function <code>call stack</code></li>
<li><strong>Constant pool</strong>: Integers, strings, and function symbols all go into constant pool. Instructions refer to constant pool values via an integer index.</li>
</ol>
<p>High-level overview:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/vmoverview.png"><img class="aligncenter size-full wp-image-869" title="vmoverview" src="http://ruslanspivak.files.wordpress.com/2011/02/vmoverview.png" alt="" width="460" height="691" /></a></p>
<p>Bytecode instructions for TinyPie VM:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/vminstr.png"><img class="aligncenter size-full wp-image-871" title="vminstr" src="http://ruslanspivak.files.wordpress.com/2011/02/vminstr.png" alt="" width="460" height="266" /></a></p>
<p>TinyPie VM comes with a <em><code>tpvm</code></em> command line utility:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/vmcli.png"><img class="aligncenter size-full wp-image-873" title="vmcli" src="http://ruslanspivak.files.wordpress.com/2011/02/vmcli.png" alt="" width="460" height="212" /></a></p>
<p>Sample program:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/vmexample.png"><img class="aligncenter size-full wp-image-881" title="vmexample" src="http://ruslanspivak.files.wordpress.com/2011/02/vmexample.png" alt="" width="408" height="347" /></a></p>
<p>Running VM with the sample program as an input:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/02/vmtrace1.png"><img class="aligncenter size-full wp-image-877" title="vmtrace" src="http://ruslanspivak.files.wordpress.com/2011/02/vmtrace1.png" alt="" width="460" height="754" /></a></p>
<p>The missing piece is conversion from TinyPie AST to TinyPie Assembly code that I need to implement for the TinyPie compiler.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/02/08/register-based-virtual-machine-for-tinypie/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>AST Visualizer for TinyPie</title>
		<link>http://ruslanspivak.com/2011/01/23/ast-visualizer-for-tinypie/</link>
		<comments>http://ruslanspivak.com/2011/01/23/ast-visualizer-for-tinypie/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 00:27:41 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=812</guid>
		<description><![CDATA[If you want to see how TinyPie AST (Abstract Syntax Tree) for different language constructs looks like you can now use gendot command line utility that I&#8217;ve added to the project and that is available in the development mode when you use buildout. This utility generates DOT file than can be further processed by dot [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>If you want to see how <a href="http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/">TinyPie</a> <strong>AST</strong> (<a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax Tree</a>) for different language constructs looks like you can now use <em><strong>gendot</strong></em> command line utility that I&#8217;ve added to the project and that is available in the development mode when you use <a href="http://github.com/rspivak/tinypie"><em>buildout</em></a>. This utility generates <a href="http://www.graphviz.org/">DOT file</a> than can be further processed by <a href="http://www.graphviz.org/">dot</a> program to draw nice graphs.</p>
<p>This is how it works.<br />
First you need to <em>clone</em> or <em>git pull</em> changes from the <a href="http://github.com/rspivak/tinypie">tinypie repo</a>.</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cd tinypie</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">git pull</span></pre>
<p>Rerun buildout to generate <em><strong>gendot</strong></em> utility.</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">bin/buildout</span></pre>
<p>Now you can generate DOT output for <a href="http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/">TinyPie</a> AST. You can pass a file name to <em><strong>gendot</strong></em> or send some text to its standard input.<br />
To generate DOT file for function call, for example, do the following:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">echo -n 'foo(3)' | bin/gendot</span>
digraph astgraph {
   node [shape=plaintext, fontsize=12, fontname="Courier", height=.1];
   ranksep=.3;
   edge [arrowsize=.5]

   node1 [label="BLOCK"];
   node2 [label="CALL"];
   node3 [label="ID (foo)"];
   node4 [label="INT (3)"];

   node2 <span style="color:#aeaeae;font-style:italic;">-&gt;</span> node3
   node2 <span style="color:#aeaeae;font-style:italic;">-&gt;</span> node4
   node1 <span style="color:#aeaeae;font-style:italic;">-&gt;</span> node2
}</pre>
<p>If you save that output and process it further with the <a href="http://www.graphviz.org/">dot</a> command you&#8217;ll get a nice image of function call AST:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">echo -n 'foo(3)' | bin/gendot &gt; funcall.dot</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">dot -Tpng -o funcall.png funcall.dot</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">ls -l funcall.png</span>
-rw-rw-r--. 1 alienoid alienoid 4617 Jan 23 17:37 funcall.png</pre>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/01/funcall.png"><img class="aligncenter size-full wp-image-821" title="funcall" src="http://ruslanspivak.files.wordpress.com/2011/01/funcall.png" alt="" width="227" height="165" /></a></p>
<p>This is how AST looks like for a factorial program:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat factorial.tp</span>
print factorial(5)

def factorial(x):
  if x &lt; 2 return 1
  return x * factorial(x - 1)
.
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat factorial.tp | bin/gendot &gt; factorial.dot</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">dot -Tpng -o factorial.png factorial.dot</span></pre>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/01/factorial.png"><img class="aligncenter size-full wp-image-824" title="factorial" src="http://ruslanspivak.files.wordpress.com/2011/01/factorial.png" alt="" width="460" height="248" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/01/23/ast-visualizer-for-tinypie/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Tree-Based Interpreter for TinyPie language</title>
		<link>http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/</link>
		<comments>http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 12:41:01 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=763</guid>
		<description><![CDATA[I&#8217;ve been working recently on a tree-based interpreter for a very simple Python-like programming language called TinyPie. In contrast to Syntax-Directed Intrepreter this one executes source code by constructing Abstract Syntax Tree from homogeneous nodes and walking the tree. The language is based on Pie language from Language Implementation Patterns Ch.9 To install the interpreter [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been working recently on a tree-based interpreter for a very simple Python-like programming language called <a href="http://github.com/rspivak/tinypie">TinyPie</a>.<br />
In contrast to <a href="http://ruslanspivak.com/2011/01/03/simple-syntax-directed-interpreter-for-an-sql-subset/">Syntax-Directed Intrepreter</a> this one executes source code by constructing Abstract Syntax Tree from homogeneous nodes and walking the tree.</p>
<p>The <a href="http://github.com/rspivak/tinypie">language</a> is based on Pie language from <a href="http://pragprog.com/titles/tpdsl/language-implementation-patterns">Language Implementation Patterns</a> Ch.9</p>
<p>To install the interpreter use either <em>pip install</em> (alternatively you can run <em>$ sudo easy_install tinypie</em>) </p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span>sudo pip install tinypie
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">tinypie factorial.tp</span>
</pre>
<p>or clone Git repo and run <em>buildout</em>:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">git clone git://github.com/rspivak/tinypie.git</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cd tinypie</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">python bootstrap.py </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">bin/buildout </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">bin/tinypie factorial.tp</span>
</pre>
<p><strong>Main interpreter features</strong>:</p>
<ul>
<li>Implemented in Python</li>
<li>Regexp-based lexer</li>
<li>LL(k) recursive-descent parser</li>
<li>Parser constructs homogeneous Abstract Syntax Tree (AST)</li>
<li>Static / lexical scope support.</li>
<li>Interpreter builds complete scope tree during AST construction.</li>
<li>Interpeter manages global memory space and function space stack</li>
<li>Implements external AST visitor</li>
<li>Forward references support</li>
</ul>
<p><strong>High-level overview:</strong></p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/01/treebasedinterp.png"><img class="aligncenter size-full wp-image-766" title="treebasedinterp" src="http://ruslanspivak.files.wordpress.com/2011/01/treebasedinterp.png" alt="" width="460" height="425" /></a></p>
<p><strong>Advantages of tree-based interperter over <a href="http://ruslanspivak.com/2011/01/03/simple-syntax-directed-interpreter-for-an-sql-subset/">syntax-directed one</a></strong>:</p>
<ol>
<li>Symbol definition and symbol resolution happen at different stages:
<ul>
<li>symbol definition is performed during parsing</li>
<li>symbol resolution is performed during interpretation</li>
</ul>
<p>This allows forward references and simplifies implementation &#8211; parser deals with scope tree only and interpreter deals with memory spaces.</li>
<li>More flexible because of AST as an intermediate representation.</li>
</ol>
<p><strong>Language grammar</strong></p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/01/langgram1.png"><img class="aligncenter size-full wp-image-793" title="langgram" src="http://ruslanspivak.files.wordpress.com/2011/01/langgram1.png" alt="" width="460" height="296" /></a></p>
<p><strong>Short language reference</strong></p>
<ul>
<li>statements: <strong><em>print</em></strong>, <em><strong>return</strong></em>, <em><strong>if</strong></em>, <em><strong>while</strong></em>,  and function call</li>
<li>literals: integers and strings</li>
<li>operators: <strong>&lt;</strong>, <strong>==</strong>, +, -, *</li>
<li>Expressions may contain identifiers.</li>
</ul>
<p><strong>Code examples</strong></p>
<pre style="font-size:9pt;">1. Factorial

    print factorial(6)               # forward reference

    def factorial(x):                # function definition
        if x &lt; 2 return 1            # if statement
        return x * factorial(x - 1)  # return statement
    .                                # DOT marks the block end

2. WHILE loop

    index = 0

    while index &lt; 10:
        print index
        index = index + 1
    .                                # DOT marks the block end

3. IF ELSE

    x = 10
    if x == 10 print 'Yes'
    else print 'No'

4. Variable lookup in different scopes

    x = 1        # global variable
    def foo(x):  # 'foo' is defined in global memory space
        print x  # prints 3 (parameter value)
    .            # DOT marks the block end
    def bar():   # 'bar' is defined in global memory space
        x = 7    # modify global variable
    .            # DOT marks the block end

    foo(3)       # prints 3
    bar()
    print x      # prints 7 ('bar' modified global variable)</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/01/21/tree-based-interpreter-for-tinypie-language/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Simple Syntax-Directed Interpreter for an SQL subset</title>
		<link>http://ruslanspivak.com/2011/01/03/simple-syntax-directed-interpreter-for-an-sql-subset/</link>
		<comments>http://ruslanspivak.com/2011/01/03/simple-syntax-directed-interpreter-for-an-sql-subset/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 06:06:58 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=736</guid>
		<description><![CDATA[To warm-up after holidays I implemented a simple Syntax-Directed Interpreter for an SQL subset called NO-SO-SQL Syntax-Directed Interpreter is similar to Syntax-directed translation, but instead of translating source code to another code the interpreter directly executes the source code &#8211; no translations, no intermediate representations. It&#8217;s suitable for simple DSLs with declarative statements. The interpreter [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>To warm-up after holidays I implemented a simple <em><strong><a href="http://github.com/rspivak/nososql">Syntax-Directed Interpreter</a></strong></em> for an SQL subset called <em><strong><a href="http://github.com/rspivak/nososql">NO-SO-SQL</a></strong></em> <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Syntax-Directed Interpreter is similar to <a href="http://en.wikipedia.org/wiki/Syntax-directed_translation">Syntax-directed translation</a>, but instead of translating source code to another code the interpreter directly executes the source code &#8211; no translations, no intermediate representations. It&#8217;s suitable for simple DSLs with declarative statements.<br />
The interpreter itself is based on a Syntax-Directed Interpreter from <a href="http://pragprog.com/titles/tpdsl/language-implementation-patterns">Language Implementation Patterns</a> Ch.9</p>
<p>The main differences are:</p>
<ol>
<li>Lexer is handcrafted</li>
<li>LL(k) recursive-descent parser is handcrafted</li>
<li>It&#8217;s implemented in Python</li>
<li>Added <strong>#</strong> symbol to comment out lines</li>
</ol>
<p>High-level overview of the interpreter:</p>
<p><a href="http://ruslanspivak.files.wordpress.com/2011/01/interp1.png"><img class="aligncenter size-full wp-image-742" title="Syntax-Directed Interpreter" src="http://ruslanspivak.files.wordpress.com/2011/01/interp1.png" alt="" width="224" height="597" /></a></p>
<p>Sample file <em>test.nososql</em>:<br />
<code><br />
create table test (primary key name, passwd, quota);<br />
insert into test set name='John', passwd='xxx', quota=100;<br />
insert into test set name='Jim', passwd='yyy', quota=200;<br />
insert into test set name='Test', passwd='test', quota=30;<br />
result = select passwd, quota from test where name='Jim';<br />
print result;</p>
<p>$ bin/nososql test.nososql<br />
yyy 200<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2011/01/03/simple-syntax-directed-interpreter-for-an-sql-subset/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Convert unix timestamp from the command line</title>
		<link>http://ruslanspivak.com/2010/12/20/convert-unix-timestamp-from-the-command-line/</link>
		<comments>http://ruslanspivak.com/2010/12/20/convert-unix-timestamp-from-the-command-line/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 03:35:35 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=723</guid>
		<description><![CDATA[Here is a small set of useful commands that I use when dealing with unix timestamps. To get a current timestamp: $ date +%s 1292901589 To convert a unix timestamp to human-readable form: $ date -d @1292901589 Mon Dec 20 22:19:49 EST 2010 To convert a unix timestamp on BSD systems you have to use [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Here is a small set of useful commands that I use when dealing with unix timestamps.</p>
<p>To get a current timestamp:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">date +%s</span>
1292901589</pre>
<p>To convert a unix timestamp to human-readable form:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">date -d @1292901589</span>
Mon Dec 20 22:19:49 EST 2010</pre>
<p>To convert a unix timestamp on BSD systems you have to use<em><strong> -r</strong></em> flag:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">date -r 1292901589</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/12/20/convert-unix-timestamp-from-the-command-line/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiline regexp</title>
		<link>http://ruslanspivak.com/2010/12/18/multiline-regexp/</link>
		<comments>http://ruslanspivak.com/2010/12/18/multiline-regexp/#comments</comments>
		<pubDate>Sun, 19 Dec 2010 01:01:40 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=679</guid>
		<description><![CDATA[One late evening my colleague and I were sitting in front of my laptop working on some Python code in Emacs. We needed to quickly make some replacements all over the file. The original code looked something like this and we wanted to remove json.dumps call around dictionaries: def foo(): return json.dumps({ 'key': 6, 'q': [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>One late evening my colleague and I were sitting in front of my laptop working on some Python code in Emacs. We needed to quickly make some replacements all over the file. The original code looked something like this and we wanted to remove <em><strong>json.dumps</strong></em> call around dictionaries:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#fbde2d;">def</span> <span style="color:#ff6400;">foo</span>():
    <span style="color:#fbde2d;">return</span> json.dumps({
        <span style="color:#61ce3c;">'key'</span>: 6,
        <span style="color:#61ce3c;">'q'</span>: 7,
        })

<span style="color:#fbde2d;">def</span> <span style="color:#ff6400;">bar</span>():
    <span style="color:#fbde2d;">return</span> json.dumps({
        <span style="color:#61ce3c;">'key'</span>: 8,
        <span style="color:#61ce3c;">'q'</span>: 9,
        })</pre>
<p>We wanted to make it look like this:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#fbde2d;">def</span> <span style="color:#ff6400;">foo</span>():
    <span style="color:#fbde2d;">return</span> {
        <span style="color:#61ce3c;">'key'</span>: 6,
        <span style="color:#61ce3c;">'q'</span>: 7,
        }

<span style="color:#fbde2d;">def</span> <span style="color:#ff6400;">bar</span>():
    <span style="color:#fbde2d;">return</span> {
        <span style="color:#61ce3c;">'key'</span>: 8,
        <span style="color:#61ce3c;">'q'</span>: 9,
        }</pre>
<p>As you can see a replace regular expression has to deal with code that spans multiple lines and writing Emacs multiline regexp might not be straightforward if you hadn&#8217;t written one before.<br />
I&#8217;ll tell you right away that we couldn&#8217;t figure out quickly how to write that regular expression and had to use &#8220;brute force&#8221;, but next day I found a solution that works and which I can use in the future when I need to deal with multiline regexp.</p>
<p>Here is what I typed in Emacs:<br />
<em>M-x query-replace-regexp</em><br />
<em> Query replace regexp: json.dumps((.*(?:^J.*?)*))</em><br />
<em> Query replace regexp json.dumps((.*(?:^J.*?)*)) with: 1</em></p>
<p>Let&#8217;s take a closer look at the regexp:</p>
<ol>
<li>First <strong><em>.*</em></strong> is reponsible for matching  all characters up to a first newline</li>
<li><em><strong>(?:^J.*?)*</strong></em> &#8211; the most important part. It&#8217;s a shy group that takes care of matching a newline and everything after the newline up to a next newline.  The shy group is faster and doesn&#8217;t introduce new group number so we can use<strong><em> 1</em></strong> to reference an outer group later. The search inside the group is non greedy due to <strong><em>?</em></strong> character and allows us to properly handle contents inside multiple<em> json.dumps</em> expressions in the same file. Also note that<em><strong> ^J</strong></em> is not a real character that you need to type &#8211; in Emacs to match a newline character when carrying out interactive search/replace you have to enter <strong><em>C-q C-j</em></strong> which will be displayed as <em><strong>^J</strong></em>.</li>
</ol>
<p>Here is an EmacsWiki page that helped me figure out some details: <a href="http://www.emacswiki.org/emacs/MultilineRegexp">MultilineRegexp</a></p>
<p>Another approach would be to call shell python command on a region. For the regexp I use <em><strong>(?s)</strong></em> to set a flag <em><strong>re.S</strong></em> (dot matches all) to match all characters including newline. Select a region in Emacs buffer or press <em>C-x h</em> to mark the whole buffer and type:</p>
<p><em>C-u M-|</em><br />
<em> Shell command on region: <strong>python -c &#8220;import sys, re; print re.sub(r&#8217;(?s)json.dumps((.*?))&#8217;, &#8216;g&lt;1&gt;&#8217;, sys.stdin.read())&#8221;</strong></em></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/12/18/multiline-regexp/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>BASH &#8211; how to create an empty file</title>
		<link>http://ruslanspivak.com/2010/12/16/bash-how-to-create-an-empty-file/</link>
		<comments>http://ruslanspivak.com/2010/12/16/bash-how-to-create-an-empty-file/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 12:18:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=673</guid>
		<description><![CDATA[I know for many people this is obvious, but I&#8217;ve recently seen different developers doing something like that to create an empty file: $ echo "" &#62; __init__.py There are &#8220;faster&#8221; ways to do it: [alienoid@capricorn ~]$ touch __init__.py [alienoid@capricorn ~]$ ls -l __init__.py -rw-rw-r--. 1 alienoid alienoid 0 Dec 16 07:13 __init__.py [alienoid@capricorn ~]$ [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I know for many people this is obvious, but I&#8217;ve recently seen different developers doing something like that to create an empty file:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">echo "" &gt; __init__.py</span></pre>
<p>There are &#8220;faster&#8221; ways to do it:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span><span style="font-weight:bold;">touch __init__.py</span>
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span><span style="font-weight:bold;">ls -l __init__.py </span>
-rw-rw-r--. 1 alienoid alienoid 0 Dec 16 07:13 __init__.py
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span>
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span><span style="font-weight:bold;">rm __init__.py </span>
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span>
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span><span style="font-weight:bold;">&gt; __init__.py</span>
<span style="color:#00ffff;">[alienoid@capricorn ~]$ </span><span style="font-weight:bold;">ls -l __init__.py </span>
-rw-rw-r--. 1 alienoid alienoid 0 Dec 16 07:14 __init__.py
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/12/16/bash-how-to-create-an-empty-file/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Serval &#8211; Simple Scheme interpreter in Python</title>
		<link>http://ruslanspivak.com/2010/12/12/serval-simple-scheme-interpreter-in-python/</link>
		<comments>http://ruslanspivak.com/2010/12/12/serval-simple-scheme-interpreter-in-python/#comments</comments>
		<pubDate>Mon, 13 Dec 2010 01:34:12 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=636</guid>
		<description><![CDATA[I&#8217;ve been always fascinated by and interested in interpreters, compilers, and language design. But there is a huge gap between being interested and actually knowing how to implement one whether it&#8217;s a simple interpreter, compiler or a programming language. So couple weeks ago I decided to reduce the gap I had and start with a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been always fascinated by and interested in interpreters, compilers, and language design. But there is a huge gap between being interested and actually knowing how to implement one whether it&#8217;s a simple interpreter, compiler or a programming language.</p>
<p>So couple weeks ago I decided to reduce the gap I had and start with a simple high-level interpreter for a subset of Scheme. Thus after several weekend evenings of code tweaking <a href="http://github.com/rspivak/serval">Serval</a> was born.</p>
<p><a href="http://github.com/rspivak/serval"><strong>Serval</strong></a> is a high-level Scheme interpreter written in Python. It implements a subset of R5RS. The code closely follows Scheme meta-circular evaluator implementation from Ch.4 of the <a href="http://www.amazon.com/Structure-Interpretation-Computer-Programs-Engineering/dp/0262011530/ref=sr_1_1?ie=UTF8&amp;qid=1292201148&amp;sr=8-1">SICP</a> book.</p>
<p>The goals of the project are pretty simple:</p>
<ol>
<li>Self-education (For me there is no better way of gaining and retaining information than by (re)implementing something on my own)</li>
<li>To serve as a potential example for other people interested in interpreter implementation, particularly Scheme interpreter.</li>
<li>Not a goal per se, but I wanted  <a href="http://github.com/rspivak/serval">Serval</a> to be able to run all examples from <a href="http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1292201005&amp;sr=8-1">&#8220;The Little Schemer&#8221;</a> book (that was my test target). The project has a test module <em>test_the_little_schemer.py</em> which runs simple meta-circular evaluator from Ch.10 of the book. Yeah, now I can evaluate Scheme code using Scheme evaluator that is interpreted by Scheme interpreter written in Python <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ol>
<p>To whet your appetite here are some examples of <a href="http://github.com/rspivak/serval">Serval</a> REPL:</p>
<ol>
<li>Defining simple function<br />
<code><br />
serval&gt; (define add1 (lambda (x) (+ x 1)))<br />
ok<br />
serval&gt; (add1 9)<br />
10<br />
</code></li>
<li>Loading representation from a file<br />
<code><br />
serval&gt; (load "/home/alienoid/scheme/the_little_schemer/ch10.ss")<br />
serval&gt; (value '((lambda (x) (cons x x)) 5))<br />
(5 . 5)<br />
</code></li>
</ol>
<p>To install the interpreter use either <em>pip install</em></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span>sudo pip install serval
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">serval</span>
<span style="color:#00ffff;">serval&gt; </span></pre>
<p>or clone Git repo and run <em>buildout</em>:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">git clone git://github.com/rspivak/serval.git</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cd serval/</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">python bootstrap.py </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">bin/buildout </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">bin/serval</span>
<span style="color:#00ffff;">serval&gt; </span></pre>
<p>Resources that I found useful when working on Serval:</p>
<ol>
<li><a href="http://www.amazon.com/gp/product/0262011530/ref=s9_simh_gw_p14_d0_i2?pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_s=center-2&amp;pf_rd_r=14RBNZ3VY9ZDBXPD7VWC&amp;pf_rd_t=101&amp;pf_rd_p=470938631&amp;pf_rd_i=507846">SICP</a></li>
<li><a href="http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992/ref=pd_bxgy_b_text_b">The Little Schemer</a></li>
<li><a href="http://www.amazon.com/Scheme-Programming-Language-4th/dp/026251298X/ref=sr_1_1?ie=UTF8&amp;qid=1292203330&amp;sr=8-1">The Scheme Programming Language</a></li>
<li><a href="http://www.amazon.com/Language-Implementation-Patterns-Domain-Specific-Programming/dp/193435645X/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1292203749&amp;sr=1-1">Language Implementation Patterns</a></li>
<li><a href="http://peter.michaux.ca/articles/scheme-from-scratch-introduction">Scheme from Scratch</a></li>
<li><a href="http://eli.thegreenplace.net/2010/11/06/bob-a-scheme-interpreter-compiler-and-vm-in-python/">Bob Scheme</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/12/12/serval-simple-scheme-interpreter-in-python/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>BASH history &#8211; incremental search forward</title>
		<link>http://ruslanspivak.com/2010/11/25/bash-history-incremental-search-forward/</link>
		<comments>http://ruslanspivak.com/2010/11/25/bash-history-incremental-search-forward/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 01:37:00 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=605</guid>
		<description><![CDATA[In my previous post I wrote about using Ctrl-R for incremental search backward. It&#8217;s about time to move on to incremental search forward. Default BASH key binding for incremental history search forward is Ctrl-S - no surprises here (if you&#8217;re an Emacs user you should feel at home right away without any customizations). The only [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In my <a title="BASH history - reverse intelligent search" href="http://ruslanspivak.com/2010/11/20/bash-history-reverse-intelligent-search/">previous post</a> I wrote about using <em><strong>Ctrl-R</strong></em> for incremental search backward.</p>
<p>It&#8217;s about time to move on to incremental search forward.</p>
<p>Default BASH key binding for incremental history search forward is <em><strong>Ctrl-S </strong></em>- no surprises here (if you&#8217;re an Emacs user you should feel at home right away without any customizations).</p>
<p>The only issue is that that key binding is shadowed by so called terminal flow control key binding. And you probably experienced that at least once when you accidentally pressed <em><strong>Ctrl-S</strong></em> and your terminal &#8220;hang&#8221;. To revive terminal after that you have to press <em><strong>Ctrl-Q</strong></em>.</p>
<p>If you run <em><strong>$ stty -a</strong></em> you&#8217;ll see those key bindings in a form like <em><strong> start = ^Q; stop = ^S</strong></em> ﻿</p>
<p>There are several workarounds to have your search back:</p>
<ol>
<li>Disable terminal flow control altogether: <em><strong>$ stty -ixon</strong></em><br />
Now your <em><strong>Ctrl-S</strong></em> will work like a charm</li>
<li>If you want to continue to use terminal flow control then you can just re-bind its <em><strong>Ctrl-S</strong></em> to, let&#8217;s say, <em><strong>Ctrl-X</strong></em> allowing BASH <em><strong>Ctrl-S</strong></em> to work as incremental history search forward:<br />
<em><strong>$ stty stop ^X</strong></em></li>
<li>Bind readline&#8217;s  <em><strong>forward-search-history</strong></em> function to another key sequence, for example, <em><strong>Alt-S</strong></em>:<br />
- <em><strong>$ bind &#8216;&#8221;es&#8221;: forward-search-history&#8217;</strong></em><br />
- or put this line into <em>~/.inputrc</em> : <em><strong>&#8220;es&#8221;: forward-search-history</strong></em></li>
</ol>
<p>Personally I use <strong><em>(1)</em> / <em>(2)</em></strong> because being an Emacs user it&#8217;s natural for me to use <em><strong>Ctrl-S</strong></em> for incremental search forward and it also plays nicely with <em><strong>Ctrl-R</strong></em> &#8211; after I cycled backwards through matched commands with <em><strong>Ctrl-R</strong></em> I can cycle forward trough them by simply pressing <em><strong>Ctrl-S</strong></em>, works perfectly without a hitch.</p>
<p>Workaround <em><strong>(3)</strong></em> for some reason doesn&#8217;t work as nicely with <em><strong>Ctrl-R</strong></em>, once I press <em><strong>Alt-S</strong></em> after <em><strong>Ctrl-R</strong></em> it clears up typed characters. I put it here just as an alternative for non-Emacs users <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/11/25/bash-history-incremental-search-forward/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>BASH history &#8211; reverse intelligent search</title>
		<link>http://ruslanspivak.com/2010/11/20/bash-history-reverse-intelligent-search/</link>
		<comments>http://ruslanspivak.com/2010/11/20/bash-history-reverse-intelligent-search/#comments</comments>
		<pubDate>Sat, 20 Nov 2010 16:34:19 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=583</guid>
		<description><![CDATA[When I tell developers about Ctrl-R in BASH usually I get responses literally ranging from &#8220;Are you @#$%^&#38;* kidding me? Who doesn&#8217;t know it?&#8221; to &#8220;Thank you. Thank you. Thank you. I owe you a beer&#8221;. Well, I made it up about the beer but I figure that people usually imply it This BASH keybinding [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When I tell developers about <strong><em>Ctrl-R</em></strong> in BASH usually I get responses literally ranging from &#8220;Are you @#$%^&amp;* kidding me? Who doesn&#8217;t know it?&#8221; to &#8220;Thank you. Thank you. Thank you. I owe you a beer&#8221;. Well, I made it up about the beer but I figure that people usually imply it <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>This BASH keybinding is so important for developer&#8217;s productivity that it&#8217;s well worth repeating it over and over again.</p>
<p>OK, here we go. If you know roughly the contents of the command, but can&#8217;t recall where it is in a BASH history list and don&#8217;t want to go through that list by hand, then just press <strong><em>Ctrl-R</em></strong> to do a reverse intelligent search.</p>
<p>As you start typing the search goes back in reverse order to the first command that matches the letters you&#8217;ve typed. By typing more successive letters you make the match more and more specific.</p>
<p>Once you&#8217;ve found the command you have several options:</p>
<ol>
<li>Run it verbatim &#8211; just press <em><strong>Enter</strong></em></li>
<li>Edit it before running &#8211; you can use arrow keys or <a href="http://ruslanspivak.com/2010/09/20/bash-key-bindings/">different key bindings</a> to navigate to the point you want to edit</li>
<li>Cycle through other commands that match the letters you&#8217;ve typed &#8211; press <strong><em>Ctrl-R</em></strong> successively</li>
<li>Quit the search and back to the command line empty-handed &#8211; press <strong><em>Ctrl-G</em></strong></li>
</ol>
<p><strong><em>Update:</em></strong></p>
<p>Added a fourth option that I forgot to mention. Thanks to commenter Taylor for reminding me about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/11/20/bash-history-reverse-intelligent-search/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>How to truncate a file</title>
		<link>http://ruslanspivak.com/2010/11/11/how-to-truncate-a-file/</link>
		<comments>http://ruslanspivak.com/2010/11/11/how-to-truncate-a-file/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 00:44:06 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=570</guid>
		<description><![CDATA[BASH has a very concise way to accomplish that: $ &#62; file [alienoid@capricorn tmp]$ ls -lh archive.log -rw-rw-r--. 1 alienoid alienoid 452M Nov 11 19:17 archive.log [alienoid@capricorn tmp]$ [alienoid@capricorn tmp]$ &#62; archive.log [alienoid@capricorn tmp]$ [alienoid@capricorn tmp]$ ls -lh archive.log -rw-rw-r--. 1 alienoid alienoid 0 Nov 11 19:17 archive.log [alienoid@capricorn tmp]$]]></description>
			<content:encoded><![CDATA[<p></p><p>BASH has a very concise way to accomplish that: <strong>$ &gt; file</strong></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span><span style="font-weight:bold;">ls -lh archive.log </span>
-rw-rw-r--. 1 alienoid alienoid 452M Nov 11 19:17 archive.log
<span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span>
<span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span><span style="font-weight:bold;">&gt; archive.log </span>
<span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span>
<span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span><span style="font-weight:bold;">ls -lh archive.log </span>
-rw-rw-r--. 1 alienoid alienoid 0 Nov 11 19:17 archive.log
<span style="color:#00ffff;">[alienoid@capricorn tmp]$ </span></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/11/11/how-to-truncate-a-file/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Auto insert module header</title>
		<link>http://ruslanspivak.com/2010/11/01/auto-insert-module-header/</link>
		<comments>http://ruslanspivak.com/2010/11/01/auto-insert-module-header/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 10:18:23 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=511</guid>
		<description><![CDATA[It&#8217;s a good development practice to insert at the beginning of a file copyright, license, and author information. Being lazy I automated the process of insertion using Emacs&#8217; skeleton mode and auto insert mode. This is an example skeleton configuration: When I open a new Python file with C-x C-f the header is inserted automatically: [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>It&#8217;s a good development practice to insert at the beginning of a file copyright, license, and author information. Being lazy I automated the process of insertion using Emacs&#8217; <a href="http://www.emacswiki.org/emacs/SkeletonMode">skeleton mode</a> and <a href="http://www.emacswiki.org/emacs/AutoInsertMode">auto insert mode</a>.</p>
<p>This is an example skeleton configuration:<br />
<a href="http://ruslanspivak.files.wordpress.com/2010/10/emacsskeletoninit3.png"><img class="alignleft size-full wp-image-532" title="emacsskeletoninit" src="http://ruslanspivak.files.wordpress.com/2010/10/emacsskeletoninit3.png" alt="" width="450" height="312" /></a></p>
<p>When I open a new Python file with <em><strong>C-x C-f</strong></em> the header is inserted automatically:<br />
<a href="http://ruslanspivak.files.wordpress.com/2010/10/emacsskeletonresult1.png"><img class="alignleft size-full wp-image-529" title="emacsskeletonresult" src="http://ruslanspivak.files.wordpress.com/2010/10/emacsskeletonresult1.png" alt="" width="450" height="236" /></a></p>
<p>Skeletons support Lisp expressions, so I embedded automatic year generation as well as retrieval of organization&#8217;s name, user&#8217;s full name, and user&#8217;s email address. (You may need to add ORGANIZATION and EMAIL environment variables to your <em>.bash_profile</em>)<br />
<em><strong>M-x</strong></em> <em>skeleton-name</em> will call the skeleton interactively and insert it at the cursor&#8217;s position</p>
<p>Alternatively the header insertion automation can be accomplished with <a href="http://code.google.com/p/yasnippet/">yasnippet</a> package, which I use with different programming modes.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/11/01/auto-insert-module-header/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Swapping lines</title>
		<link>http://ruslanspivak.com/2010/10/21/swapping-lines/</link>
		<comments>http://ruslanspivak.com/2010/10/21/swapping-lines/#comments</comments>
		<pubDate>Fri, 22 Oct 2010 02:05:53 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=486</guid>
		<description><![CDATA[Being able to swap lines in Emacs with C-x C-t comes in handy when I edit Python code and want to prettify some imports: import sys import os I move cursor to a line that I want to swap, in this case import os, and press C-x C-t which exchanges the current line and a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Being able to swap lines in Emacs with <strong><em>C-x C-t</em></strong> comes in handy when I edit Python code and want to prettify some imports:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#fbde2d;">import</span> sys
<span style="color:#fbde2d;">import</span> os</pre>
<p>I move cursor to a line that I want to swap, in this case <strong><em>import os</em></strong>, and press <strong><em>C-x C-t</em></strong> which exchanges the current line and a previous line:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#fbde2d;">import</span> os
<span style="color:#fbde2d;">import</span> sys</pre>
<p>A very basic and simple operation. And while the same can be accomplished with cutting and pasting &#8211; swapping is faster in this case.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/21/swapping-lines/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>In-place file rewrite with fileinput</title>
		<link>http://ruslanspivak.com/2010/10/20/in-place-file-rewrite-with-fileinput/</link>
		<comments>http://ruslanspivak.com/2010/10/20/in-place-file-rewrite-with-fileinput/#comments</comments>
		<pubDate>Wed, 20 Oct 2010 12:09:05 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=270</guid>
		<description><![CDATA[When I need to iterate over the lines of all files in sys.argv[1:], I use a fileinput module. This is a typical use of the module. From the official documentation: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When I need to iterate over the lines of all files in <strong><em>sys.argv[1:]</em></strong>, I use a <a href="http://docs.python.org/library/fileinput.html#module-fileinput">fileinput</a> module. This is a typical use of the module.</p>
<p>From the official documentation:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#fbde2d;">import</span> fileinput
<span style="color:#fbde2d;">for</span> line <span style="color:#fbde2d;">in</span> fileinput.input():
    process(line)</pre>
<p><em>This iterates over the lines of all files listed in sys.argv[1:],</em><em> defaulting to sys.stdin if the list is empty.</em></p>
<p>Another interesting feature of this module that I occasionally use is <em>in-place filtering</em> that allows to rewrite input files in place. To enable it I pass keyword argument<strong> inplace=1</strong> to <strong>fileinput.input()</strong>. After that standard output is directed to an input file and printing effectively rewrites the file in place:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#aeaeae;font-style:italic;"># </span><span style="color:#aeaeae;font-style:italic;">inplace.py
</span><span style="color:#fbde2d;">import</span> fileinput

<span style="color:#fbde2d;">def</span> <span style="color:#ff6400;">process</span>(line):
    <span style="color:#fbde2d;">return</span> line.strip() + <span style="color:#61ce3c;">' line'</span>

<span style="color:#fbde2d;">for</span> line <span style="color:#fbde2d;">in</span> fileinput.input(inplace=1):
    <span style="color:#aeaeae;font-style:italic;"># </span><span style="color:#aeaeae;font-style:italic;">standard ouput is directed to an input file
</span>    <span style="color:#aeaeae;font-style:italic;"># </span><span style="color:#aeaeae;font-style:italic;">that's why we need to print here to rewrite the file
</span>    <span style="color:#fbde2d;">print</span> process(line)</pre>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat input1.txt </span>
first
second
<span style="color:#00ffff;">$ </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat input2.txt</span>
third
fourth
<span style="color:#00ffff;">$ </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">python inplace.py input1.txt input2.txt</span>
<span style="color:#00ffff;">$ </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat input1.txt </span>
first line
second line
<span style="color:#00ffff;">$ </span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">cat input2.txt</span>
third line
fourth line</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/20/in-place-file-rewrite-with-fileinput/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Is the file connected to a TTY?</title>
		<link>http://ruslanspivak.com/2010/10/16/is-the-file-connected-to-a-tty/</link>
		<comments>http://ruslanspivak.com/2010/10/16/is-the-file-connected-to-a-tty/#comments</comments>
		<pubDate>Sun, 17 Oct 2010 03:01:41 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=432</guid>
		<description><![CDATA[I remember once a colleague of mine asked me how to determine if a Python console program got its input directly from a terminal or from a pipe or I/O redirection. The answer was an isatty function. In Python every file object has a method isatty that returns True if the file is connected to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I remember once a colleague of mine asked me how to determine if a Python console program got its input directly from a terminal or from a pipe or I/O redirection.</p>
<p>The answer was an <em><strong>isatty</strong></em> function.</p>
<p>In Python every file object has a method <a href="http://docs.python.org/library/stdtypes.html#file.isatty">isatty</a> that returns <em>True</em> if the file is connected to a tty(-like) device, else <em>False</em>. There is also an <a href="http://docs.python.org/library/os.html#os.isatty">os.isatty</a> function.</p>
<p>Here is a test program:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#aeaeae;font-style:italic;"># ttytest.py
</span><span style="color:#fbde2d;">import</span> sys

<span style="color:#fbde2d;">for</span> line <span style="color:#fbde2d;">in</span> sys.stdin:
    <span style="color:#fbde2d;">print</span> <span style="color:#61ce3c;">'Response: %s'</span> % line.strip()

<span style="color:#fbde2d;">print</span> <span style="color:#61ce3c;">'Connected to a tty device: %s'</span> % sys.stdin.isatty()</pre>
<p>Input from a terminal (you may need to press <em>Ctrl-D</em> twice to terminate the input <a href="http://bugs.python.org/issue1633941">http://bugs.python.org/issue1633941</a>):</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">python ttytest.py </span>
<span style="font-weight:bold;">hello</span>
<span style="font-weight:bold;">world</span>
<span style="color:#61ce3c;">Response: hello</span>
<span style="color:#61ce3c;">Response: world</span>
Connected to a tty device: True</pre>
<p>Input from a pipe:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">echo -e 'hellonworld' | python ttytest.py</span>
<span style="color:#61ce3c;">Response: hello</span>
<span style="color:#61ce3c;">Response: world</span>
Connected to a tty device: False</pre>
<p>Input redirection:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">$ </span><span style="font-weight:bold;">echo -e 'hellonworld' &gt; data.txt</span>
<span style="color:#00ffff;">$ </span><span style="font-weight:bold;">python ttytest.py &lt; data.txt</span>
<span style="color:#61ce3c;">Response: hello</span>
<span style="color:#61ce3c;">Response: world</span>
Connected to a tty device: False</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/16/is-the-file-connected-to-a-tty/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Pretty print JSON from the command line</title>
		<link>http://ruslanspivak.com/2010/10/12/pretty-print-json-from-the-command-line/</link>
		<comments>http://ruslanspivak.com/2010/10/12/pretty-print-json-from-the-command-line/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 03:24:57 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=402</guid>
		<description><![CDATA[Recently I&#8217;ve worked on a small project where I needed to pretty print JSON from the command line for quick verification. For the task I created a pp alias in my .bashrc that worked perfectly (all the code is on the same line): alias pp='python -c "import sys, json; print json.dumps( json.load(sys.stdin), sort_keys=True, indent=4)"' Just [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I&#8217;ve worked on a small project where I needed to pretty print JSON from the command line for quick verification.<br />
For the task I created a <strong><em>pp</em></strong> alias in my <em>.bashrc</em> that worked perfectly (all the code is on the same line):</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">
<span style="color:#f8f8f8;">alias</span> <span style="color:#ff6400;">pp</span>=<span style="color:#61ce3c;">'python -c "import sys, json; print json.dumps(
json.load(sys.stdin), sort_keys=True, indent=4)"'</span></pre>
<p>Just today I was re-reading the official Python documentation on a <a href="http://docs.python.org/library/json.html#module-json">json package</a> and came across a small gem &#8211; <strong>json.tool</strong> module that is used for validation and pretty-printing.<br />
I modified my alias which is now way shorter and does the same job as my old one:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">
<span style="color:#f8f8f8;">alias</span> <span style="color:#ff6400;">pp</span>=<span style="color:#61ce3c;">'python -mjson.tool'</span></pre>
<p>And here is pretty-printing in action:</p>
<p>&nbsp;<br />
<img src="http://ruslanspivak.files.wordpress.com/2010/10/pp.png" alt="pretty-print" /></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/12/pretty-print-json-from-the-command-line/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Nuke whitespaces on file saving</title>
		<link>http://ruslanspivak.com/2010/10/11/nuke-whitespaces-on-file-saving/</link>
		<comments>http://ruslanspivak.com/2010/10/11/nuke-whitespaces-on-file-saving/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 04:17:19 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=375</guid>
		<description><![CDATA[In one of my previous posts I wrote how I kept track of whitespaces and a column 80 overflow. And in my config you could see that I used delete-trailing-whitespace with write-file-hooks ;; nuke trailing whitespaces when writing to a file (add-hook 'write-file-hooks 'delete-trailing-whitespace) What I wanted to use with write-file-hooks was whitespace-cleanup, but somehow [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In one of my <a href="http://ruslanspivak.com/2010/09/27/keep-track-of-whitespaces-and-column-80-overflow/">previous posts</a> I wrote how I kept track of whitespaces and a column 80 overflow. And in my config you could see that I used <em>delete-trailing-whitespace</em> with <em>write-file-hooks</em></p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">nuke trailing whitespaces when writing to a file
</span>(add-hook 'write-file-hooks 'delete-trailing-whitespace)
</pre>
<p>What I wanted to use with <em>write-file-hooks</em> was <em><strong>whitespace-cleanup</strong></em>, but somehow it didn&#8217;t work for me with that hook (whitespaces were removed when saving a file, but buffer was marked as containing changes).</p>
<p>Thanks to Valeriy Zamarayev who, <a href="http://ruslanspivak.com/2010/09/27/keep-track-of-whitespaces-and-column-80-overflow/#comment-712">in his comment to my post</a>, mentioned save hook and whitespace-cleanup. This is what I use now to remove whitespaces when saving a file:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">nuke whitespaces when writing to a file
</span>(add-hook 'before-save-hook 'whitespace-cleanup)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/11/nuke-whitespaces-on-file-saving/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Streamline file editing with EmacsClient</title>
		<link>http://ruslanspivak.com/2010/10/03/streamline-file-editing-with-emacsclient/</link>
		<comments>http://ruslanspivak.com/2010/10/03/streamline-file-editing-with-emacsclient/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 03:13:16 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=344</guid>
		<description><![CDATA[In the past when I had to edit a file from the command line in my terminal I did one of the following: Launched Emacs with the file as a command line parameter. That was usually a slow and annoying process. Switched to a running Emacs instance and used C-x C-f to open the file. [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In the past when I had to edit a file from the command line in my terminal I did one of the following:</p>
<ul>
<li>Launched Emacs with the file as a command line parameter. That was usually a slow and annoying process.</li>
<li>Switched to a running Emacs instance and used <em><strong>C-x C-f</strong></em> to open the file. If the file path was too long it was taking some time to enter it and was annoying too.</li>
<li>Resorted to Vi in some simple editing cases because it was faster and less annoying (yes, guilty as charged <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<p>After being annoyed couple times I set out to find  a solution to my problem and it didn&#8217;t take long to find out that in Emacs world existed a perfect one: <a href="http://www.emacswiki.org/emacs/EmacsClient">EmacsClient</a></p>
<p>My problem was solved.</p>
<p>If you&#8217;ve never tried <a href="http://www.emacswiki.org/emacs/EmacsClient">EmacsClient</a> before I urge you to do so &#8211; it&#8217;ll do you some good.</p>
<p>To use it you need to run Emacs in <em>server mode</em> and use a command line utility <strong><em>emacsclient</em></strong> to open a file for editing in an already running Emacs instance. Opening a file for editing in this way is blazingly fast.</p>
<p>I have this line in <em><strong>.emacs</strong></em> to start Emacs in server mode:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">(server-start)</pre>
<p>You can also start server manually from a running Emacs instance: <strong><em>M-x server-start</em></strong></p>
<p>Then from the command line send a file to the running instance with <em>emacsclient</em>:<br />
<strong>$ emacsclient -n </strong><em>your_file_name</em></p>
<p>I simplified <em>emacsclient</em> invocation by creating a function and putting it into my <strong><em>.bashrc</em></strong>:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">ec() {
    emacsclient -n $<span style="color:#ff6400;">1</span>
}</pre>
<p>So now whenever I need to edit a file from the command line I just invoke the <em><strong>ec</strong></em> function with a file as a parameter:</p>
<p><strong>$ ec</strong> <em>file.txt</em></p>
<p>P.S.: You can also set environment variable <strong>EDITOR</strong> to <em>emacsclient</em> to make it a default editor for different utilities relying on the <strong>EDITOR</strong> variable.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/10/03/streamline-file-editing-with-emacsclient/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Keep track of whitespaces and column 80 overflow</title>
		<link>http://ruslanspivak.com/2010/09/27/keep-track-of-whitespaces-and-column-80-overflow/</link>
		<comments>http://ruslanspivak.com/2010/09/27/keep-track-of-whitespaces-and-column-80-overflow/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 02:28:32 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=307</guid>
		<description><![CDATA[When working in Emacs python mode I keep track of whitespaces and column 80 overflow using a whitespace-mode that is part of Emacs 22+ Here is a snippet from my .emacs: ;; nuke trailing whitespaces when writing to a file (add-hook 'write-file-hooks 'delete-trailing-whitespace) ;; display only tails of lines longer than 80 columns, tabs and [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When working in Emacs python mode I keep track of whitespaces and column 80 overflow using a <a href="http://www.emacswiki.org/emacs/WhiteSpace">whitespace-mode</a> that is part of Emacs 22+</p>
<p>Here is a snippet from my <em>.emacs</em>:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">nuke trailing whitespaces when writing to a file
</span>(add-hook 'write-file-hooks 'delete-trailing-whitespace)

<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">display only tails of lines longer than 80 columns, tabs and
</span><span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">trailing whitespaces
</span>(setq whitespace-line-column 80
      whitespace-style '(tabs trailing lines-tail))

<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">face for long lines' tails
</span>(set-face-attribute 'whitespace-line nil
                    <span style="color:#F8F8F8;">:background</span> <span style="color:#61CE3C;">"red1"</span>
                    <span style="color:#F8F8F8;">:foreground</span> <span style="color:#61CE3C;">"yellow"</span>
                    <span style="color:#F8F8F8;">:weight</span> 'bold)

<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">face for Tabs
</span>(set-face-attribute 'whitespace-tab nil
                    <span style="color:#F8F8F8;">:background</span> <span style="color:#61CE3C;">"red1"</span>
                    <span style="color:#F8F8F8;">:foreground</span> <span style="color:#61CE3C;">"yellow"</span>
                    <span style="color:#F8F8F8;">:weight</span> 'bold)

<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">activate minor whitespace mode when in python mode
</span>(add-hook 'python-mode-hook 'whitespace-mode)
</pre>
<p>Because my Emacs is setup to save/restore desktop I&#8217;ve added the following lines to play nicely with the <em>whitespace-mode</em> when restoring a previous session:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#AEAEAE;font-style:italic;">;; </span><span style="color:#AEAEAE;font-style:italic;">save whitespace-mode variables
</span>(add-to-list 'desktop-globals-to-save 'whitespace-line-column)
(add-to-list 'desktop-globals-to-save 'whitespace-style)
</pre>
<p>This is how trailing whitespaces, tabs and long lines tails look in my Emacs buffer:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
<span style="color:#FBDE2D;">import</span> sys

<span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">main</span>():
    <span style="color:#61CE3C;">"""This line is longer than 80 cloumns ...........................</span><span style="color:#ffff00;background-color:#ff0000;font-weight:bold;">.."""</span>
    values = [
        <span style="color:#AEAEAE;font-style:italic;"># next line contains leading tab
</span><span style="color:#ffff00;background-color:#ff0000;font-weight:bold;">        </span><span style="color:#61CE3C;">'qwerty'</span>,
        <span style="color:#61CE3C;">'test'</span>,<span style="color:#ffff00;background-color:#ff0000;font-weight:bold;">    </span>
        ]

<span style="color:#ffff00;background-color:#ff0000;font-weight:bold;">   </span>
<span style="color:#FBDE2D;">if</span> <span style="color:#F8F8F8;">__name__</span> == <span style="color:#61CE3C;">'__main__'</span>:
    main() <span style="color:#AEAEAE;font-style:italic;"># this line contains trailing whitespaces</span><span style="color:#ffff00;background-color:#ff0000;font-weight:bold;">    </span><span style="color:#AEAEAE;font-style:italic;">
</span>
</pre>
<p><strong>UPDATE</strong> November 15th, 2011<br />
In <strong>Emacs 24</strong> you have to add a <strong>face</strong> specifier to the <strong>whitespace-style</strong> to make trailing whitespaces highlighted:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">
(setq whitespace-line-column 80
      whitespace-style '(face tabs trailing lines-tail))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/09/27/keep-track-of-whitespaces-and-column-80-overflow/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>C-w to delete word backward in Conkeror</title>
		<link>http://ruslanspivak.com/2010/09/22/c-w-to-delete-word-backward-in-conkeror/</link>
		<comments>http://ruslanspivak.com/2010/09/22/c-w-to-delete-word-backward-in-conkeror/#comments</comments>
		<pubDate>Thu, 23 Sep 2010 04:03:42 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=293</guid>
		<description><![CDATA[Long time ago after reading Steve Yegge&#8217;s post on Effective Emacs I rebound C-w to &#8216;backward-kill-word and since then I&#8217;ve had the same key binding for both Emacs and BASH. Now that Conkeror is my default browser it makes sense to have C-w to work the same way as in Emacs and BASH. This is [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Long time ago after reading Steve Yegge&#8217;s post on <a href="http://sites.google.com/site/steveyegge2/effective-emacs">Effective Emacs</a> I rebound <em><strong>C-w</strong></em> to <em><strong>&#8216;backward-kill-word</strong></em> and since then I&#8217;ve had the same key binding for both Emacs and BASH.</p>
<p>Now that <a href="http://conkeror.org/">Conkeror</a> is my default browser it makes sense to have <em><strong>C-w</strong></em> to work the same way as in Emacs and BASH.</p>
<p>This is a snippet that I&#8217;ve added to my  <em><strong>~/.conkerorrc</strong></em></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="background-color:#330;">define_key(text_keymap, 'C-w', 'cmd_deleteWordBackward');</span></pre>
<p>Now I have a uniform key binding across my tools.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/09/22/c-w-to-delete-word-backward-in-conkeror/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>BASH key bindings</title>
		<link>http://ruslanspivak.com/2010/09/20/bash-key-bindings/</link>
		<comments>http://ruslanspivak.com/2010/09/20/bash-key-bindings/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 05:34:09 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=279</guid>
		<description><![CDATA[Here is a list of BASH key bindings that I use on a daily basis: Key binding Action Ctrl-r History reverse search Ctrl-a Jump to BOL Ctrl-e Jump to EOL Ctrl-l Clear terminal Ctrl-k Delete from cursor to EOL Ctrl- Undo last operation Ctrl-m Return Ctrl-w Delete word left from cursor Ctrl-u Delete from BOL [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Here is a list of BASH key bindings that I use on a daily basis:</p>
<table border="2" cellspacing="0" cellpadding="6" rules="groups">
<col align="left"></col>
<col align="left"></col>
<thead>
<tr>
<th>Key binding</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ctrl-r</td>
<td>History reverse search</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-a</td>
<td>Jump to BOL</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-e</td>
<td>Jump to EOL</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-l</td>
<td>Clear terminal</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-k</td>
<td>Delete from cursor to EOL</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-</td>
<td>Undo last operation</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-m</td>
<td>Return</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-w</td>
<td>Delete word left from cursor</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-u</td>
<td>Delete from BOL to cursor</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-x Ctrl-e</td>
<td>Open the default editor</td>
</tr>
<tr>
<td></td>
<td>$EDITOR and run edited command</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-p</td>
<td>Previous command in history</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-n</td>
<td>Next command in history</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-f</td>
<td>Move forward a char</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-b</td>
<td>Move backward a char</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-f</td>
<td>Move forward a word</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-b</td>
<td>Move backward a word</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-d</td>
<td>Delete char under cursor</td>
</tr>
<tr>
<td></td>
<td>Exit shell if empty</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-d</td>
<td>Delete forward word</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-y</td>
<td>Paste content of the kill ring</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-t</td>
<td>Swap current char with</td>
</tr>
<tr>
<td></td>
<td>previous char</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-t</td>
<td>Swap current word with</td>
</tr>
<tr>
<td></td>
<td>previous word</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-u</td>
<td>Uppercase word at cursor</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Alt-l</td>
<td>Lowercase word at cursor</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-s</td>
<td>Freeze terminal</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Ctrl-q</td>
<td>Restore frozen terminal</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Shift-PgUp</td>
<td>Scroll screen up</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Shift-PgDn</td>
<td>Scroll screen down</td>
</tr>
</tbody>
</table>
<p>Most of these key bindings work in Emacs too.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/09/20/bash-key-bindings/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>C-m as Return in Conkeror</title>
		<link>http://ruslanspivak.com/2010/09/15/c-m-as-return-in-conkeror/</link>
		<comments>http://ruslanspivak.com/2010/09/15/c-m-as-return-in-conkeror/#comments</comments>
		<pubDate>Thu, 16 Sep 2010 01:56:00 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=272</guid>
		<description><![CDATA[By default C-m is not bound to Return in Conkeror and I became quite addictive to that binding in Emacs. It took me a bit to figure it out, but here is a snippet that should go into .conkerorrc to make C-m to work: require("global-overlay-keymap.js"); define_key_alias("C-m", "return");]]></description>
			<content:encoded><![CDATA[<p></p><p>By default <strong><em>C-m</em></strong> is not bound to <strong><em>Return</em></strong> in <a href="http://conkeror.org">Conkeror</a> and I became quite addictive to that binding in Emacs.<br />
It took me a bit to figure it out, but here is a snippet that should go into <em>.conkerorrc</em> to make <em><strong>C-m</strong></em> to work:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">require(<span style="color:#61ce3c;">"global-overlay-keymap.js"</span>);
define_key_alias(<span style="color:#61ce3c;">"C-m"</span>, <span style="color:#61ce3c;">"return"</span>);</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/09/15/c-m-as-return-in-conkeror/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sequence multiplication and reflected operands</title>
		<link>http://ruslanspivak.com/2010/09/12/sequence-multiplication-and-reflected-operands/</link>
		<comments>http://ruslanspivak.com/2010/09/12/sequence-multiplication-and-reflected-operands/#comments</comments>
		<pubDate>Sun, 12 Sep 2010 17:34:34 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=258</guid>
		<description><![CDATA[My 2 cents for Hidden features of Python &#62;&#62;&#62; 'xyz' * 3 'xyzxyzxyz' &#62;&#62;&#62; &#62;&#62;&#62; [1, 2] * 3 [1, 2, 1, 2, 1, 2] &#62;&#62;&#62; &#62;&#62;&#62; (1, 2) * 3 (1, 2, 1, 2, 1, 2) We get the same result with reflected (swapped) operands &#62;&#62;&#62; 3 * 'xyz' 'xyzxyzxyz' It works like this: [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>My 2 cents for <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">'xyz' * 3</span>
'xyzxyzxyz'
<span style="color:#00ffff;">&gt;&gt;&gt; </span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">[1, 2] * 3</span>
[1, 2, 1, 2, 1, 2]
<span style="color:#00ffff;">&gt;&gt;&gt; </span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">(1, 2) * 3</span>
(1, 2, 1, 2, 1, 2)</pre>
<p>We get the same result with reflected (swapped) operands</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">3 * 'xyz'</span>
'xyzxyzxyz'</pre>
<p>It works like this:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">s = 'xyz'</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">num = 3</span></pre>
<p>To evaluate an expression<strong> s * num</strong> interpreter calls <strong>s.__mul__(num)</strong></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">s * num</span>
'xyzxyzxyz'
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">s.__mul__(num)</span>
'xyzxyzxyz'</pre>
<p>To evaluate an expression <strong>num * s</strong> interpreter calls <strong>num.__mul__(s)</strong></p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">num * s</span>
'xyzxyzxyz'
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">num.__mul__(s)</span>
NotImplemented</pre>
<p>If the call returns <strong><em>NotImplemented</em></strong> then interpreter calls<br />
a reflected operation <strong>s.__rmul__(num)</strong> if operands have different types</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">s.__rmul__(num)</span>
'xyzxyzxyz'</pre>
<p>See <a href="http://docs.python.org/reference/datamodel.html#object.__rmul__">http://docs.python.org/reference/datamodel.html#object.__rmul__</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/09/12/sequence-multiplication-and-reflected-operands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Urlencode and urldecode from a command line</title>
		<link>http://ruslanspivak.com/2010/06/02/urlencode-and-urldecode-from-a-command-line/</link>
		<comments>http://ruslanspivak.com/2010/06/02/urlencode-and-urldecode-from-a-command-line/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 18:22:08 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=224</guid>
		<description><![CDATA[Recently I have worked with a REST Web service and had to URL encode a lot of values from the command line. If all you need is to URL encode data for a POST request you can use curl with &#8211;data-urlencode parameter, but I needed to encode values that went into a URL query string. [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I have worked with a REST Web service and had to URL encode a lot of values from the command line.</p>
<p>If all you need is to URL encode data for a POST request you can use <a href="http://curl.haxx.se/">curl</a> with <strong><em>&#8211;data-urlencode</em></strong> parameter, but I needed to encode values that went into a URL query string.<br />
So for the task I wrote a short code in Python to do just that (there are examples available in BASH or Perl, but this is a pure Python using only standard library):</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">python -c <span style="color:#61ce3c;">"import sys, urllib as ul; print ul.quote_plus(sys.argv[1])"</span></pre>
<p>Assign it to an alias by putting single quotes around the expression and you&#8217;re good to go:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ alias <span style="color:#ff6400;">urlencode</span>=<span style="color:#61ce3c;">'python -c "import sys, urllib as ul; print ul.quote_plus(sys.argv[1])"'</span></pre>
<p>Example:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ <span style="font-weight:bold;">urlencode 'q werty=/;'</span>
q+werty%3D%2F%3B</pre>
<p>And the decode part:</p>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">python -c <span style="color:#61ce3c;">"import sys, urllib as ul; print ul.unquote_plus(sys.argv[1])"</span></pre>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ alias <span style="color:#ff6400;">urldecode</span>=<span style="color:#61ce3c;">'python -c "import sys, urllib as ul; print ul.unquote_plus(sys.argv[1])"'</span></pre>
<pre style="color:#f8f8f8;background-color:#0c1021;font-size:8pt;">$ <span style="font-weight:bold;">urldecode 'q+werty%3D%2F%3B'</span>
q werty=/;</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/06/02/urlencode-and-urldecode-from-a-command-line/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Review of Grok 1.0 Web Development</title>
		<link>http://ruslanspivak.com/2010/04/12/review-of-grok-1-0-web-development/</link>
		<comments>http://ruslanspivak.com/2010/04/12/review-of-grok-1-0-web-development/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 10:03:59 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=204</guid>
		<description><![CDATA[It took me a while to finish reading the book but here we go. I wasn&#8217;t disappointed by the book and absolutely sure that it delivers on its promise to show that Grok can be an excellent fit for many kinds of Web development projects. I think I&#8217;ll have to finish my Grok based blog [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>It took me a while to finish reading <a href="http://www.packtpub.com/grok-1-0-web-development/book?utm_source=ruslanspivak.com&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002621">the book</a> but here we go.</p>
<p><a href="http://www.packtpub.com/grok-1-0-web-development/book?utm_source=ruslanspivak.com&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002621"><img class="alignleft size-thumbnail wp-image-207" title="grok" src="http://ruslanspivak.files.wordpress.com/2010/04/grok1.jpg?w=121" alt="" width="121" height="150" /></a> I wasn&#8217;t disappointed by the book and absolutely sure that it delivers on its promise to show that <a href="http://grok.zope.org/">Grok</a> can be an excellent fit for many kinds of Web development projects.</p>
<p>I think I&#8217;ll have to finish my <a href="http://github.com/rspivak/grok-awesome">Grok based blog</a> now <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Grok is largely based on <a href="http://docs.zope.org/zopetoolkit/">Zope Tookit</a> and that&#8217;s a very powerful set of libraries developed over many years that provides support for forms, full text search, authentication, i18n, security, components, persistence, testing, and many more.</p>
<p>Main distinguishing Grok concepts emphasized by the book:</p>
<ul>
<li>component architecture</li>
<li>object database (ZODB)</li>
<li>object publishing and traversal</li>
<li>convention over configuration and <em>do not repeat yourself</em> (<em>DRY</em>) principle</li>
</ul>
<p>The book introduces a simple <em>&#8220;to-do&#8221;</em> application to the readers. Gradually the application grows with new features like storing data in object database, forms, full text catalog search, security, component architecture.</p>
<p>There is a separate chapter devoted to integration with relational databases. This is especially important topic for Grok because traditionally Zope and Grok were tightly bound to ZODB.</p>
<p>All in all it&#8217;s been a pleasant read and I think it&#8217;s a great introduction to Grok web framework.</p>
<p>P.S. I may sound very optimistic regarding Grok and Zope, but I can&#8217;t do anything about it &#8211; I have a soft spot for Grok, it&#8217;s an excellent piece of software <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Enjoy it!</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/04/12/review-of-grok-1-0-web-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preview of Grok 1.0 Web Development by Carlos de la Guardia</title>
		<link>http://ruslanspivak.com/2010/02/26/preview-of-grok-1-0-web-development-by-carlos-de-la-guardia/</link>
		<comments>http://ruslanspivak.com/2010/02/26/preview-of-grok-1-0-web-development-by-carlos-de-la-guardia/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 07:20:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=188</guid>
		<description><![CDATA[I&#8217;ve been asked by PACKT publishing to review a new book  Grok 1.0 Web Development. I gladly accepted their proposal. For those interested &#8211; yes, they sent me a free PDF version of the book, but I would buy the book anyway because it is about the project I love and associate myself with even [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been asked by <a href="http://www.packtpub.com">PACKT publishing</a> to review a new book  <a href="http://www.packtpub.com/grok-1-0-web-development/book?utm_source=ruslanspivak.com&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002621">Grok 1.0 Web Development</a>.</p>
<p>I gladly accepted their proposal. For those interested &#8211; yes, they sent me a free PDF version of the book, but I would buy the book anyway because it is about the project I love and associate myself with even though I&#8217;ve not been actively participating in it recently.</p>
<p>Personally I think that the release of this book is a major event for the whole Grok community. Having comprehensive documentation for people just starting with a <a href="http://grok.zope.org/">smashing Web framework Grok</a> is of utter importance.</p>
<p>What&#8217;s interesting is that I&#8217;ve been thinking about writing a book on Grok myself, but Carlos de la Guardia beat me to the punch and after skimming through the book I&#8217;m glad he did <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>What I liked instantaneously about the book is the presence of a chapter on integration with relational databases, the topic that in the Zope world was kind of obscure in the past.</p>
<p>When I finish reading the book I&#8217;ll post a full review so stay tuned and meanwhile you can take a sneak peak at the book by reading a freely available <a href="http://www.packtpub.com/files/7481-grok-1-0-Web-development-sample-chapter-5-forms.pdf">Chapter No 5: Forms</a></p>
<p><span style="color:#000000;"><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2010/02/26/preview-of-grok-1-0-web-development-by-carlos-de-la-guardia/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My first crack at Nokia N900 Maemo Python development</title>
		<link>http://ruslanspivak.com/2009/12/28/my-first-crack-at-nokia-n900-maemo-python-development/</link>
		<comments>http://ruslanspivak.com/2009/12/28/my-first-crack-at-nokia-n900-maemo-python-development/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 09:54:09 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=161</guid>
		<description><![CDATA[Got my shiny new Nokia N900 &#8211; to say that I&#8217;m happy is an understatement For me as a long standing Linux user and Pythonista N900 has an unassailable advantage &#8211; its Maemo platform is Linux based and I can program in Python for the platform. So it&#8217;s time to get my feet wet and [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Got my shiny new <a href="http://maemo.nokia.com/n900/">Nokia N900</a> &#8211; to say that I&#8217;m happy is an understatement <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For me as a long standing Linux user and Pythonista N900 has an unassailable advantage &#8211; its <a href="http://maemo.org/">Maemo</a> platform is Linux based and I can program in Python for the platform.</p>
<p>So it&#8217;s time to get my feet wet and learn some Maemo programming. I decided to take a stab at writing a small <a href="http://ichi2.net/anki/index.html">Anki</a> client using Python and Qt. As a result I have a working but still very raw prototype called <a href="http://github.com/rspivak/ktanki">KTAnki</a> that successfully runs on my N900.</p>
<p>For <a href="http://github.com/rspivak/ktanki">KTAnki</a> I used <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro">PyQt4</a> library, though I should take a closer look at Nokia&#8217;s own bindings &#8211; <a href="http://www.pyside.org/">PySide</a>.</p>
<p>Here are some resources that I found helpful when prototyping my first Maemo PyQt application:</p>
<ol>
<li><a href="http://wiki.maemo.org/N900_USB_networking">N900 USB Networking</a></li>
<li><a href="http://wiki.maemo.org/PyMaemo/QuickStartGuide">PyMaemo QuickStart Guide</a></li>
<li><a href="http://wiki.forum.nokia.com/index.php/Getting_started_with_PyQt_for_Maemo">Getting started with PyQt for Maemo</a></li>
<li><a href="http://www.slideshare.net/guestb404461/pyqt-application-development-on-maemo">PyQt Application Development On Maemo</a></li>
<li><a href="http://blogs.forum.nokia.com/blog/kate-alholas-forum-nokia-blog/2009/12/01/hildonized-applications-for-maemo-5-with-qt4.5.3-and-qt4.6">Hildonized applications for Maemo 5 with Qt4.5.3 and Qt4.6</a></li>
<li><a href="http://www.qtrac.eu/pyqtbook.html">Rapid GUI Programming with Python and Qt</a></li>
<li><a href="http://doc.trolltech.com/">Qt Reference Documentation</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/12/28/my-first-crack-at-nokia-n900-maemo-python-development/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>CSSBuilder for Data URIs</title>
		<link>http://ruslanspivak.com/2009/11/30/cssbuilder-for-data-uris/</link>
		<comments>http://ruslanspivak.com/2009/11/30/cssbuilder-for-data-uris/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 08:15:57 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=152</guid>
		<description><![CDATA[I&#8217;ve added a new repository for CSSBuilder at http://github.com/rspivak/cssbuilder CSSBuilder is a command line utility and library written in Python for embedding Data URIs into CSS files. You can find more information about Data URI at: http://en.wikipedia.org/wiki/Data_URI_scheme http://www.nczonline.net/blog/2009/10/27/data-uris-explained/ http://www.phpied.com/data-urls-what-are-they-and-how-to-use/ &#160;]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve added a new repository for CSSBuilder at <a href="http://github.com/rspivak/cssbuilder">http://github.com/rspivak/cssbuilder</a></p>
<p>CSSBuilder is a command line utility and library written in Python for embedding Data URIs into CSS files.</p>
<p>You can find more information about Data URI at:</p>
<p><a href="http://en.wikipedia.org/wiki/Data_URI_scheme">http://en.wikipedia.org/wiki/Data_URI_scheme</a></p>
<p><a href="http://www.nczonline.net/blog/2009/10/27/data-uris-explained/">http://www.nczonline.net/blog/2009/10/27/data-uris-explained/</a></p>
<p><a href="http://www.phpied.com/data-urls-what-are-they-and-how-to-use/">http://www.phpied.com/data-urls-what-are-they-and-how-to-use/</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/11/30/cssbuilder-for-data-uris/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rebinding variable outside of the local scope</title>
		<link>http://ruslanspivak.com/2009/10/07/rebinding-variable-outside-of-the-local-scope/</link>
		<comments>http://ruslanspivak.com/2009/10/07/rebinding-variable-outside-of-the-local-scope/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 04:04:52 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=130</guid>
		<description><![CDATA[The other day I had to explain why in Python in contrast to Perl/Lisp/Scheme one can&#8217;t rebind variable outside of the local scope besides the global scope, i.e. the following function will result in an UnboundLocalError exception in Python 2.x def outer(): count = 0 def inner(): count += 1 # rebinding inner() print count [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>The other day I had to explain why in Python in contrast to Perl/Lisp/Scheme one can&#8217;t rebind variable outside of the local scope besides the global scope, i.e. the following function will result in an <em>UnboundLocalError</em> exception in <em><strong>Python 2.x</strong></em></p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">outer</span>():
    count = 0
    <span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">inner</span>():
        count += 1 <span style="color:#AEAEAE;font-style:italic;"># </span><span style="color:#AEAEAE;font-style:italic;">rebinding
</span>    inner()
    <span style="color:#FBDE2D;">print</span> count</pre>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">outer()</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "scope.py", line 8, in outer
    inner()
  File "scope.py", line 6, in inner
    count += 1 # rebinding
UnboundLocalError: local variable 'count' referenced before assignment</pre>
<p>There are several workarounds.</p>
<p>For one thing it is possible to use a variable holding a mutable object:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">outer</span>():
    ns = <span style="color:#F8F8F8;">dict</span>(count=0)
    <span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">inner</span>():
        ns[<span style="color:#61CE3C;">'count'</span>] += 1 <span style="color:#AEAEAE;font-style:italic;"># </span><span style="color:#AEAEAE;font-style:italic;">rebinding
</span>    inner()
    <span style="color:#FBDE2D;">print</span> ns[<span style="color:#61CE3C;">'count'</span>]</pre>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">outer()</span>
1</pre>
<p>Another approach is to use a function object itself to store the variable:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">outer</span>():
    outer.count = 0
    <span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">inner</span>():
        outer.count += 1 <span style="color:#AEAEAE;font-style:italic;"># </span><span style="color:#AEAEAE;font-style:italic;">rebinding
</span>    inner()
    <span style="color:#FBDE2D;">print</span> outer.count</pre>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">outer()</span>
1</pre>
<p>The good news is that there is no need for workarounds anymore in <em><strong>Python 3</strong></em> which introduced <a href="http://docs.python.org/3.1/reference/simple_stmts.html#nonlocal"><strong>nonlocal</strong></a> keyword:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">outer</span>():
    count = 0
    <span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">inner</span>():
        nonlocal count
        count += 1 <span style="color:#AEAEAE;font-style:italic;"># </span><span style="color:#AEAEAE;font-style:italic;">rebinding
</span>    inner()
    <span style="color:#FBDE2D;">print</span>(count)
</pre>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">outer()</span>
1</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/10/07/rebinding-variable-outside-of-the-local-scope/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Downcase with replace-regexp</title>
		<link>http://ruslanspivak.com/2009/04/06/downcase-with-replace-regexp/</link>
		<comments>http://ruslanspivak.com/2009/04/06/downcase-with-replace-regexp/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 01:45:02 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=117</guid>
		<description><![CDATA[Recently I&#8217;ve been working with CSS files and wanted to replace color definitions with downcased equivalents, i.e. #FFFFFF; would become #ffffff; To do that I used pretty well known feature of Emacs, namely use of Lisp expressions in the replacement string of replace-regexp function. Commands entered in minibuffer: M-x replace-regexp RET (#.*)  RET ,(downcase 1) [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I&#8217;ve been working with CSS files and wanted to replace color definitions with downcased equivalents, i.e. <strong>#FFFFFF;</strong> would become <strong>#ffffff;</strong></p>
<p>To do that I used pretty well known feature of Emacs, namely use of <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Replace.html">Lisp expressions</a> in the replacement string of <strong>replace-regexp</strong> function.</p>
<p>Commands entered in minibuffer:</p>
<p><strong>M-x replace-regexp RET (#.*)  RET ,(downcase 1) RET</strong></p>
<p>The only problem with that code is that if you have variable <strong>case-fold-search</strong> in Emacs set to <strong>true</strong> (which is the case in my Emacs by default) <strong>replace-regexp</strong> will report about successful replace but string won&#8217;t be downcased anyway. To quickly switch off <strong>case-fold-search</strong> I used <strong>M-: (setq case-fold-search nil)</strong> and after that downcasing worked as expected.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/04/06/downcase-with-replace-regexp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IPython profile for Grok</title>
		<link>http://ruslanspivak.com/2009/03/30/ipython-profile-for-grok/</link>
		<comments>http://ruslanspivak.com/2009/03/30/ipython-profile-for-grok/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 06:46:27 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=111</guid>
		<description><![CDATA[To use IPython shell from Grok based project is easy, just add ipython to eggs directive in your buildout.cfg My part with ipython added looks like this: [app] recipe = zc.recipe.egg eggs = grok-awesome ipython Paste PasteScript PasteDeploy interpreter = python-console But I wanted to be able to inspect Grok instance and use path TAB [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>To use IPython shell from Grok based project is easy, just add <em>ipython</em> to eggs directive in your <em>buildout.cfg</em></p>
<p>My part with <em>ipython</em> added looks like this:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">[<span style="color:#8DA6CE;">app</span>]
<span style="color:#FF6400;">recipe</span> = zc.recipe.egg
<span style="color:#FF6400;">eggs</span> = grok-awesome
       ipython
       Paste
       PasteScript
       PasteDeploy
<span style="color:#FF6400;">interpreter</span> = python-console</pre>
<p>But I wanted to be able to inspect Grok instance and use path TAB auto-completion to navigate ZODB hierarchy.</p>
<p>Inspired by existing IPython profile fo Zope2 I whipped out basic implementation for Grok.</p>
<p>It&#8217;s available under <a href="http://github.com/rspivak/grok-ipython/tree">grok-ipython</a>. Now all IPython power can be used when inspecting objects in Grok instance:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#F8F8F8;background-color:#0C1021;">(mygrok)[alienoid@capricorn grok-awesome]$ bin/ipython -p grok</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">IPython shell for Grok.</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#F8F8F8;background-color:#0C1021;">Bound object names:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">-------------------</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  root</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  ctx</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#F8F8F8;background-color:#0C1021;">Bound command names:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">--------------------</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  cdg / ;cdg</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  lsg / ;lsg</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  pwdg</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  sync</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">  commit</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#F8F8F8;background-color:#0C1021;">Grok IPython 0.9.1   Py 2.5.2</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">1</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">root</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">1</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;zope.app.folder.folder.Folder object at 0x9003e6c&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">2</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">ctx</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">2</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;zope.app.folder.folder.Folder object at 0x9003e6c&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">3</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">;cdg blog</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#00cd00;background-color:#0C1021;">------&gt; </span><span style="color:#F8F8F8;background-color:#0C1021;">cdg("blog")</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">3</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">u'/blog'</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">4</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">ctx</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">4</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;grokawesome.blog.Blog object at 0x81d2d6c&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">5</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">;cdg </span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">my-first-post  second-post    </span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">5</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">;cdg my-first-post</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#00cd00;background-color:#0C1021;">------&gt; </span><span style="color:#F8F8F8;background-color:#0C1021;">cdg("my-first-post")</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">5</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">u'/blog/my-first-post'</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">6</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">ctx</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">6</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;grokawesome.entry.BlogEntry object at 0xb7d556ac&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">7</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">pwdg</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;">Out[</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">7</span><span style="color:#cd0000;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">u'/blog/my-first-post'</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">8</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">ctx?</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Type:</span><span style="color:#F8F8F8;background-color:#0C1021;">           </span><span style="color:#F8F8F8;background-color:#0C1021;">BlogEntry</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Base Class:</span><span style="color:#F8F8F8;background-color:#0C1021;">     </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;class 'grokawesome.entry.BlogEntry'&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">String Form:</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;grokawesome.entry.BlogEntry object at 0xb7d556ac&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Namespace:</span><span style="color:#F8F8F8;background-color:#0C1021;">      </span><span style="color:#F8F8F8;background-color:#0C1021;">Interactive</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Length:</span><span style="color:#F8F8F8;background-color:#0C1021;">         </span><span style="color:#F8F8F8;background-color:#0C1021;">0</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">File:</span><span style="color:#F8F8F8;background-color:#0C1021;">           </span><span style="color:#F8F8F8;background-color:#0C1021;">/home/alienoid/mygrok/grok-awesome/src/grokawesome/entry.py</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Docstring:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">    &lt;no docstring&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span>
<span style="color:#00cd00;background-color:#0C1021;">In [</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">9</span><span style="color:#00cd00;background-color:#0C1021;">]: </span><span style="color:#F8F8F8;background-color:#0C1021;">ctx??</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Type:             </span><span style="color:#F8F8F8;background-color:#0C1021;">BlogEntry</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Base Class:       </span><span style="color:#F8F8F8;background-color:#0C1021;">&lt;class 'grokawesome.entry.BlogEntry'&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">String Form:</span><span style="color:#F8F8F8;background-color:#0C1021;">   &lt;grokawesome.entry.BlogEntry object at 0xb7d556ac&gt;</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Namespace:        </span><span style="color:#F8F8F8;background-color:#0C1021;">Interactive</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Length:           </span><span style="color:#F8F8F8;background-color:#0C1021;">0</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">File:             </span><span style="color:#F8F8F8;background-color:#0C1021;">/home/alienoid/mygrok/grok-awesome/src/grokawesome/entry.py</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#cd0000;background-color:#0C1021;font-weight:bold;">Source:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">class</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">BlogEntry</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">grok</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">Container</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">grok</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">implements</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">IBlogEntry</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">portal_type</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#0000ee;background-color:#0C1021;font-weight:bold;">'blogentry'</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">created</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">property</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">DCProperty</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#0000ee;background-color:#0C1021;font-weight:bold;">'created'</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">modified</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">property</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">DCProperty</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#0000ee;background-color:#0C1021;font-weight:bold;">'modified'</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#F8F8F8;background-color:#0C1021;">

</span><span style="color:#F8F8F8;background-color:#0C1021;">    </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">def</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">__init__</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">title</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">content</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">                 </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">summary</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#0000ee;background-color:#0C1021;font-weight:bold;">u''</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">                 </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">categories</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">None</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">                 </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">allow_comments</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">False</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">:</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">super</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">BlogEntry</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">,</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">__init__</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">(</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">)</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">title</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">title</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">content</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">content</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">summary</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#0000ee;background-color:#0C1021;font-weight:bold;">''</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">if</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">summary</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">is</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">None</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">else</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">summary</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">categories</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">[</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">]</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">if</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">categories</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">is</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">None</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#00cd00;background-color:#0C1021;font-weight:bold;">else</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">categories</span><span style="color:#F8F8F8;background-color:#0C1021;">
</span><span style="color:#F8F8F8;background-color:#0C1021;">        </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">self</span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">.</span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">allow_comments</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#cdcd00;background-color:#0C1021;font-weight:bold;">=</span><span style="color:#F8F8F8;background-color:#0C1021;"> </span><span style="color:#ffffff;background-color:#0C1021;font-weight:bold;">allow_comments</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/30/ipython-profile-for-grok/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>TinyMCE widget in Grok</title>
		<link>http://ruslanspivak.com/2009/03/24/tinymce-widget-in-grok/</link>
		<comments>http://ruslanspivak.com/2009/03/24/tinymce-widget-in-grok/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 22:48:26 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=100</guid>
		<description><![CDATA[I have added TinyMCE widget to grok-awesome for editing html and it was easy as pie. If you want TinyMCE in your Grok based project it can be achieved with following steps: 1. Add dependencies to setup.py into install_requires section: 'hurry.tinymce', 'hurry.zopetinymce', hurry.tinymce allows you to include TinyMCE into your project without additional burden, you [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I have added TinyMCE widget to <a href="http://github.com/rspivak">grok-awesome</a> for editing html and it was easy as pie.</p>
<p>If you want <a href="http://tinymce.moxiecode.com/">TinyMCE</a> in your Grok based project it can be achieved with following steps:</p>
<p><strong>1</strong>. Add dependencies to <em>setup.py</em> into <em>install_requires</em> section:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">                        <span style="color:#61CE3C;">'hurry.tinymce'</span>,
                        <span style="color:#61CE3C;">'hurry.zopetinymce'</span>,</pre>
<p><a href="http://pypi.python.org/pypi/hurry.tinymce/">hurry.tinymce</a> allows you to include TinyMCE into your project without additional burden, you don&#8217;t need to do anything. Well, almost &#8211; just make sure to call:<br />
<strong><em>from hurry.tinymce import tinymce<br />
tinymce.need()</em></strong><br />
to trigger inclusion of TinyMCE in the web page.</p>
<p><strong>2</strong>. Create custom widget which calls <em>tinymce.need()</em> as noted above  and initializes TinyMCE</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#FBDE2D;">from</span> zope.app.form.browser <span style="color:#FBDE2D;">import</span> TextAreaWidget
<span style="color:#FBDE2D;">from</span> hurry.tinymce <span style="color:#FBDE2D;">import</span> tinymce

<span style="color:#FF6400;">template</span> = <span style="color:#61CE3C;">"""%(widget_html)s
&lt;script type="</span>text/javascript<span style="color:#61CE3C;">"&gt;
  tinyMCE.init({
    mode : "</span>exact<span style="color:#61CE3C;">",
    elements: "</span>%(elements)s<span style="color:#61CE3C;">",
    theme: "</span>advanced<span style="color:#61CE3C;">"
  });
&lt;/script&gt;"""</span>

<span style="color:#FBDE2D;">class</span> <span style="color:#8DA6CE;">TinyMCEWidget</span>(TextAreaWidget):
    <span style="color:#61CE3C;">"""Widget to edit html using TinyMCE WYSIWYG editor."""</span>

    <span style="color:#FBDE2D;">def</span> <span style="color:#FF6400;">__call__</span>(<span style="color:#FBDE2D;">self</span>, *args, **kw):
        widget_html = <span style="color:#F8F8F8;">super</span>(TinyMCEWidget, <span style="color:#FBDE2D;">self</span>).__call__(*args, **kw)
        tinymce.need()
        <span style="color:#FBDE2D;">return</span> template % {<span style="color:#61CE3C;">'widget_html'</span>: widget_html,
                           <span style="color:#61CE3C;">'elements'</span>: <span style="color:#FBDE2D;">self</span>.name,
                           }</pre>
<p><strong>3</strong>. In your add/edit form use your custom widget for the field you want and off you go:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">form_fields[<span style="color:#61CE3C;">'content'</span>].custom_widget = TinyMCEWidget</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/24/tinymce-widget-in-grok/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Decode hex pairwise with zip</title>
		<link>http://ruslanspivak.com/2009/03/20/decode-hex-pairwise-with-zip/</link>
		<comments>http://ruslanspivak.com/2009/03/20/decode-hex-pairwise-with-zip/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 16:34:55 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=68</guid>
		<description><![CDATA[The other day I had to decode strings containing hex numbers into plain integers. I could use built-in int([ x [, radix]]) with radix=16 to convert a string to an integer and forget about it, but I needed to decode pairs from the hex number so that in the end from the string &#8216;FFEEDD&#8217; I [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>The other day I had to decode strings containing hex numbers into plain integers.</p>
<p>I could use built-in <strong><em>int([ x [, radix]])</em></strong> with <strong><em>radix=16</em></strong> to convert a string to an integer and forget about it, but I needed to decode pairs from the hex number so that in the end from the string &#8216;FFEEDD&#8217; I get 255, 238, 221</p>
<p>But wouldn&#8217;t you know it, there is a standard solution to get pairs in Python and it&#8217;s built-in <em>zip</em> function.</p>
<p>It&#8217;s a well known function for experienced developers, but there is one documented feature of it that doesn&#8217;t always catch one&#8217;s eye and it&#8217;s a general form for clustering a data series into n-length groups <strong>zip(*[iter(s)]*n)</strong> which is described in official docs for <a href="http://docs.python.org/library/functions.html">zip built-in</a>.</p>
<p>With that in mind solution to my problem boils down to a one-line decoder:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ff00;background-color:#0C1021;">&gt;&gt;&gt; </span><span style="font-weight:bold;">s = 'FFDDEE'</span>
<span style="color:#00ff00;background-color:#0C1021;">&gt;&gt;&gt; </span><span style="font-weight:bold;">[int(''.join(pair), 16) for pair in zip(*[iter(s)]*2)]</span>
[255, 221, 238]</pre>
<p>For those wondering how it works:</p>
<p>1) <em>iter(s)</em> creates iterable from the <em>s</em></p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ff00;background-color:#0C1021;">&gt;&gt;&gt; </span><span style="font-weight:bold;">iter(s)</span>
&lt;iterator object at 0x8a3c2cc&gt;</pre>
<p>2) <em>[iter(s)] * 2</em> creates list of 2 iterators that all use the same underlying iterable <em>iter(s)</em>. The important thing is that created iterators <strong><em>share the same iterable</em></strong>, so when some data is consumed by first iterator that data becomes unavailable for the second iterator and vice versa.</p>
<p>You can see from the output that iterator objects are located at the same address. If you are new to this behavior you can read on about <a href="http://docs.python.org/library/stdtypes.html#typesseq">shallow copies</a>.</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ff00;background-color:#0C1021;">&gt;&gt;&gt; </span><span style="font-weight:bold;">[iter(s)]*2</span>
[&lt;iterator object at 0x8a3c2cc&gt;, &lt;iterator object at 0x8a3c2cc&gt;]</pre>
<p>3) leading <strong>*</strong> in zip&#8217;s parameter unpacks list from step (2) into two separate parameters for zip function. Basically it becomes <em>zip(iterator, iterator)</em>.</p>
<p>More about unpacking argument list you can read in official <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">docs</a>.</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="color:#00ff00;background-color:#0C1021;">&gt;&gt;&gt; </span><span style="font-weight:bold;">zip(*[iter(s)]*2)</span>
[('F', 'F'), ('D', 'D'), ('E', 'E')]</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/20/decode-hex-pairwise-with-zip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refresh Firefox page from Emacs</title>
		<link>http://ruslanspivak.com/2009/03/16/refresh-firefox-page-from-emacs/</link>
		<comments>http://ruslanspivak.com/2009/03/16/refresh-firefox-page-from-emacs/#comments</comments>
		<pubDate>Mon, 16 Mar 2009 18:26:04 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=57</guid>
		<description><![CDATA[I often need to refresh page in Firefox when I edit page template or javascript file. This is especially true when working on grok-awesome. Though I use tiling window manager StumpWM and it&#8217;s very easy to switch to running Firefox with keyboard shortcut and make refresh, it&#8217;s even easier not to leave focus from Emacs [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I often need to refresh page in Firefox when I edit page template or javascript file. This is especially true when working on <a href="http://ruslanspivak.com/2009/03/12/grok-awesome/">grok-awesome</a>.</p>
<p>Though I use tiling window manager <a href="http://www.nongnu.org/stumpwm/">StumpWM</a> and it&#8217;s very easy to switch to running Firefox with keyboard shortcut and make refresh, it&#8217;s even easier not to leave focus from Emacs window and just send command to Firefox to refresh itself.<br />
For that I use:</p>
<ul>
<li> <a href="http://wiki.github.com/bard/mozrepl">MozRepl</a> firefox plugin to allow connect to Firefox&#8217;s REPL. After installation in Tools -&gt; MozRepl menu I chose &#8216;Activate on startup&#8217; for convenience</li>
<li> MozRepl Emacs <a href="http://wiki.github.com/bard/mozrepl/emacs-integration">integration</a> (If you use <a href="http://ourcomments.org/Emacs/nXhtml/doc/nxhtml.html">nXhtml</a> package in Emacs you already have that integration and can skip this part)</li>
</ul>
<p>Command to refresh Firefox is <strong>BrowserReload();</strong></p>
<p>Final touch is small anonymous function to send that command to mozrepl, keybinding to <strong>C-x p</strong> and we&#8217;re all set:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">(global-set-key (kbd <span style="color:#61CE3C;">"C-x p"</span>)
                (<span style="color:#FBDE2D;">lambda</span> ()
                  (interactive)
                  (comint-send-string (inferior-moz-process)
                                      <span style="color:#61CE3C;">"BrowserReload();"</span>)))</pre>
<p>Now anytime just press <strong>C-x p</strong> and refresh command will be sent to Firefox starting along the way mozrepl session in your Emacs if it&#8217;s not been already started.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/16/refresh-firefox-page-from-emacs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grok Awesome</title>
		<link>http://ruslanspivak.com/2009/03/12/grok-awesome/</link>
		<comments>http://ruslanspivak.com/2009/03/12/grok-awesome/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 20:15:07 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=49</guid>
		<description><![CDATA[I&#8217;ve started developing blog software for &#8220;A Smashing Web Framework&#8221; Grok. The reasons behind that: There is no full-featured blog software for Grok. There is a simple version Grokstar, but as for me it doesn&#8217;t fit the bill. I created simple blog for Zope3 several years ago and let it languish. Now it&#8217;s time to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve started developing blog software for &#8220;A Smashing Web Framework&#8221; <a href="http://grok.zope.org/">Grok</a>.</p>
<p>The reasons behind that:</p>
<ul>
<li>There is no full-featured blog software for Grok. There is a simple version <a href="http://svn.zope.org/Grokstar/">Grokstar</a>, but as for me it doesn&#8217;t fit the bill.</li>
<li>I created simple blog for Zope3 several years ago and let it languish. Now it&#8217;s time to revive it taking into account how Grok simplifies development with Zope3 technologies.</li>
<li>I&#8217;m not completely happy with WordPress. For one thing, I&#8217;d like to have easy-to-use REST API so I can use it in my Emacs to make posts.</li>
<li>I simply love <a href="http://grok.zope.org/">Grok</a>. You should try it and you&#8217;ll love it too.</li>
</ul>
<p>My fledgling project lives on GitHub and it&#8217;s called <a href="http://github.com/rspivak/grok-awesome/tree/master">grok-awesome</a> <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/12/grok-awesome/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Emacs dark theme + IPython colors</title>
		<link>http://ruslanspivak.com/2009/03/09/emacs-dark-theme-ipython-colors/</link>
		<comments>http://ruslanspivak.com/2009/03/09/emacs-dark-theme-ipython-colors/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 07:15:09 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=39</guid>
		<description><![CDATA[Ever wondered how to make IPython colors be nice on dark background of your dark (no pun intended) Emacs theme like blackboard ? Just add to your .emacs (setq py-python-command-args '("-pylab" "-colors" "Linux")) before you load ipython package (setq py-python-command-args '("-pylab" "-colors" "Linux")) (require 'ipython) Now IPython uses &#8216;Linux&#8217; color scheme which is suitable for [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Ever wondered how to make IPython colors be nice on dark background of your dark (no pun intended) Emacs theme like <a href="http://blog.jdhuntington.com/2008/11/emacs-color-theme-blackboard.html">blackboard </a>?</p>
<p>Just add to your .emacs</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;"><span style="background-color:#4f94cd;">(</span>setq py-python-command-args '(<span style="color:#61CE3C;">"-pylab"</span> <span style="color:#61CE3C;">"-colors"</span> <span style="color:#61CE3C;">"Linux"</span>)<span style="background-color:#4f94cd;">)</span></pre>
<p>before you load ipython package</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">(setq py-python-command-args '(<span style="color:#61CE3C;">"-pylab"</span> <span style="color:#61CE3C;">"-colors"</span> <span style="color:#61CE3C;">"Linux"</span>))
(<span style="color:#FBDE2D;">require</span> '<span style="color:#D8FA3C;">ipython</span>)</pre>
<p>Now IPython uses &#8216;Linux&#8217; color scheme which is suitable for dark background with light fonts instead of default &#8216;LightBG&#8217;.</p>
<p>Here it is:</p>
<pre style="color:#F8F8F8;background-color:#0C1021;font-size:8pt;">Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38)
Type "copyright", "credits" or "license" for more information.

IPython 0.9.1 -- An enhanced Interactive Python.
?         -&gt; Introduction and overview of IPython's features.
%quickref -&gt; Quick reference.
help      -&gt; Python's own help system.
object?   -&gt; Details about 'object'. ?object also works, ?? prints more.

  Welcome to pylab, a matplotlib-based Python environment.
  For more information, type 'help(pylab)'.

<span style="color:#00ff00;background-color:#0C1021;">In [</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">1</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">]: </span><span style="font-weight:bold;">d = dict()</span>

<span style="color:#00ff00;background-color:#0C1021;">In [</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">2</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">]: </span><span style="font-weight:bold;">?d</span>
<span style="color:#ff0000;font-weight:bold;">Type:           </span>dict
<span style="color:#ff0000;font-weight:bold;">Base Class:     </span>&lt;type 'dict'&gt;
<span style="color:#ff0000;font-weight:bold;">String Form:</span>    {}
<span style="color:#ff0000;font-weight:bold;">Namespace:      </span>Interactive
<span style="color:#ff0000;font-weight:bold;">Length:         </span>0
<span style="color:#ff0000;font-weight:bold;">Docstring:
</span>    dict() -&gt; new empty dictionary.
    dict(mapping) -&gt; new dictionary initialized from a mapping object's
        (key, value) pairs.
    dict(seq) -&gt; new dictionary initialized as if via:
        d = {}
        for k, v in seq:
            d[k] = v
    dict(**kwargs) -&gt; new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)

<span style="color:#00ff00;background-color:#0C1021;">In [</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">3</span><span style="color:#00ff00;background-color:#0C1021;font-weight:bold;">]: </span></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/09/emacs-dark-theme-ipython-colors/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>&#8220;Release It!&#8221; is just what the doctor ordered</title>
		<link>http://ruslanspivak.com/2009/03/02/release-it-is-just-what-the-doctor-ordered/</link>
		<comments>http://ruslanspivak.com/2009/03/02/release-it-is-just-what-the-doctor-ordered/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 19:34:37 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[uncategorized]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/?p=30</guid>
		<description><![CDATA[I&#8217;ve just finished reading excellent book Release It!: Design and Deploy Production-Ready Software If you are involved or plan to be involved in developing any system that must be available 24 x 7 x 365 then you owe it to yourself to read this book. The key ideas you should understand are: system will fail [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve just finished reading excellent book <a href="http://www.pragprog.com/titles/mnee/release-it"><em>Release It!: Design and Deploy Production-Ready Software</em></a></p>
<p>If you are involved or plan to be involved in developing any system that must be available 24 x 7 x 365 then you owe it to yourself to read this book.</p>
<p>The key ideas you should understand are:</p>
<ul>
<li>system will fail</li>
</ul>
<ul>
<li>life of software only begins when you release it into production</li>
</ul>
<p>With that in mind the book is a treasure trove of useful advices how to make your system scale and succeed in production.</p>
<p>The book resonates with my own personal experience in developing and maintaining critical Python application and many things that Michael Nygard describes I learned the hard way: blocked threads, socket timeouts, integration point failures and latency, asynchronous handling, caching, database growth and of course &#8220;cold shivers&#8221; you get when the system goes down.</p>
<p>While book is sprinkled with notes about Java related issues it&#8217;s nevertheless technology agnostic which makes it a valuable source of information for every developer.</p>
<p>It gets two thumbs up from me.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2009/03/02/release-it-is-just-what-the-doctor-ordered/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Autovivication and Y Combinator in Python</title>
		<link>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/</link>
		<comments>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 22:45:55 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.wordpress.com/?p=29</guid>
		<description><![CDATA[Sometimes you may need to have nested dictionaries initialized without much hassle. &#8220;Autovivication&#8221; comes in handy. What you want to achieve is: &#62;&#62;&#62; d = dict() &#62;&#62;&#62; d['q']['w']['r'] = 777 Of course what you&#8217;ll get will be: &#62;&#62;&#62; d['q']['w']['r'] = 777 Traceback (most recent call last): File "&#60;stdin&#62;", line 1, in &#60;module&#62; KeyError: 'q' If [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes you may need to have nested dictionaries initialized without much hassle.</p>
<p>&#8220;Autovivication&#8221; comes in handy. What you want to achieve is:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = dict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
</pre>
<p>Of course what you&#8217;ll get will be:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
<span style="color:#87cefa;">KeyError</span>: 'q'
</pre>
<p>If you don&#8217;t need deeply nested dictionaries <strong>defaultdict </strong> with <em>dict default factory</em> will do the job:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">from collections import defaultdict</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defaultdict(dict)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;type 'dict'&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['a']['b'] = 33</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;type 'dict'&gt;, {'a': {'b': 33}})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['a']['b']</span>
33
</pre>
<p>Here are another ways to have unlimited level of nested dictionaries.<br />
<strong>1)</strong> Define custom class inheriting from built-in <strong>dict</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">class</span> <span style="color:#98fb98;">default_dict</span>(dict):
    <span style="color:#00ffff;">def</span> <span style="color:#87cefa;">__missing__</span>(<span style="color:#00ffff;">self</span>, key):
        <span style="color:#00ffff;">self</span>[key] = value = <span style="color:#00ffff;">self</span>.__class__()
        <span style="color:#00ffff;">return</span> value
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = default_dict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
{}
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
{'q': {'w': {'r': 777}}}
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
<p><strong>2)</strong> Recursive function + <strong>defaultdict</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">make_dict</span>():
    <span style="color:#00ffff;">return</span> defaultdict(make_dict)
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">from collections import defaultdict</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defaultdict(make_dict)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {'q': defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {'w': defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {'r': 777})})})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
<p><strong>3)</strong> And for fun you can use <a href="http://en.wikipedia.org/wiki/Y_combinator">Y Combinator</a> (in short &#8211; making anonymous lambda recursive) which is actually as (2) but you don&#8217;t have to have recursive function defined:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">Y</span>(g):
    <span style="color:#00ffff;">return</span> ((<span style="color:#00ffff;">lambda</span> f: f(f))
            (<span style="color:#00ffff;">lambda</span> f:
                 g(<span style="color:#00ffff;">lambda</span> x: f(f)
                   (x))))

<span style="color:#eedd82;">defdict</span> = Y(<span style="color:#00ffff;">lambda</span> mk_dict:
                <span style="color:#00ffff;">lambda</span> x=<span style="color:#00ffff;">None</span>: defaultdict(<span style="color:#00ffff;">lambda</span> x=<span style="color:#00ffff;">None</span>: mk_dict(x)))
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defdict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function &lt;lambda&gt; at 0xb7c52a74&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function &lt;lambda&gt; at 0xb7c52a74&gt;, {'q': defaultdict(&lt;function &lt;lambda&gt; at 0xb7c56c6c&gt;, {'w': defaultdict(&lt;function &lt;lambda&gt; at 0xb7c56a74&gt;, {'r': 777})})})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Array module in Erlang</title>
		<link>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/</link>
		<comments>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 03:47:14 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://ruslanspivak.wordpress.com/?p=28</guid>
		<description><![CDATA[Recent Erlang releases (since R12B) have array module included. Now binary search algorithm can be implemented quite efficiently with functional arrays: -module(bsa). -export([binsearch/2]). binsearch(Arr, Key) -&#62; binsearch(Arr, Key, 0, array:size(Arr)). binsearch(Arr, Key, LowerBound, UpperBound) -&#62; Mid = (LowerBound + UpperBound) div 2, Item = array:get(Mid, Arr), if UpperBound &#60; LowerBound -&#62; -1; Key &#60; Item [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recent Erlang releases (since R12B) have <a href="http://www.erlang.org/doc/man/array.html">array module</a> included.</p>
<p>Now <a href="http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/">binary search</a> algorithm can be implemented quite  <a href="http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/">efficiently</a> with functional arrays:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(bsa).
<span style="color:#87cefa;">-export</span>([binsearch/2]).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>) -&gt;
    binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, 0, array:<span style="color:#00ffff;">size</span>(<span style="color:#eedd82;">Arr</span>)).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">UpperBound</span>) -&gt;
    <span style="color:#eedd82;">Mid</span> = (<span style="color:#eedd82;">LowerBound</span> + <span style="color:#eedd82;">UpperBound</span>) div 2,
    <span style="color:#eedd82;">Item</span> = array:<span style="color:#00ffff;">get</span>(<span style="color:#eedd82;">Mid</span>, <span style="color:#eedd82;">Arr</span>),
    <span style="color:#00ffff;">if</span>
        <span style="color:#eedd82;">UpperBound</span> &lt; <span style="color:#eedd82;">LowerBound</span> -&gt;<span style="color:#87cefa;"> </span>-1;
        <span style="color:#eedd82;">Key</span> &lt; <span style="color:#eedd82;">Item</span> -&gt;
            binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">Mid</span>-1);
        <span style="color:#eedd82;">Key</span> &gt; <span style="color:#eedd82;">Item</span> -&gt;
            binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">Mid</span>+1, <span style="color:#eedd82;">UpperBound</span>);
        true -&gt;
            <span style="color:#eedd82;">Mid</span>
    <span style="color:#00ffff;">end</span>.
</pre>
<p>Running time for <em>lists based</em> binary search (just for comparison):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;"><span style="color:#00ffff;">56&gt; </span><span style="font-weight:bold;">{Time, Val} = timer:tc(search, binsearch,</span>
<span style="color:#00ffff;">56&gt; </span><span style="font-weight:bold;">                       [lists:seq(1, 1000000), 1000000]).</span>
{506513,  1000000}</pre>
<p>Running time for <em>array based</em> binary search:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;"><span style="color:#00ffff;">57&gt; </span><span style="font-weight:bold;">f().</span>
ok
<span style="color:#00ffff;">58&gt; </span><span style="font-weight:bold;">{Time, Val} = timer:tc(bsa, binsearch,</span>
<span style="color:#00ffff;">58&gt; </span><span style="font-weight:bold;">              [array:from_list(lists:seq(1, 1000000)), 1000000]).</span>
{17,  999999}</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Part V</title>
		<link>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/</link>
		<comments>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/#comments</comments>
		<pubDate>Fri, 16 Nov 2007 05:18:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/</guid>
		<description><![CDATA[Previous parts: Intro, Part I, Part II, Part III and Part IV List comprehensions. List comprehensions is very familiar topic for Python programmer. It&#8217;s a syntactic sugar which provides a succinct notation for producing elements in list. Erlang: [Expr &#124;&#124; Qualifier1,...,QualifierN] Expr &#8211; is an arbitrary expression Qualifier is either a generator or a filter. [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>, <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a>, <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">Part III</a> and <a href="http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/">Part IV</a></p>
<h3>List comprehensions.</h3>
<p>List comprehensions is very familiar topic for Python programmer. It&#8217;s a syntactic sugar which provides a succinct notation for producing elements in list.</p>
<h4><u><strong>Erlang:</strong></u></h4>
<pre>[Expr || Qualifier1,...,QualifierN]</pre>
<p><u><em>Expr</em></u> &#8211; is an arbitrary expression<br />
<u><em>Qualifier</em></u> is either a <strong>generator</strong> or a <strong>filter</strong>.<br />
A <strong>generator</strong> is of form <code>Pattern &lt;- ListExpr </code> where <em>ListExpr</em> evaluates to a list of terms.<br />
A <strong>filter</strong> expression should evaluate to <em>true</em> or <em>false.</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,2,3,4,5,6], X &gt; 3].</span>
[4,5,6]</pre>
<p>This is read as: list of X such that X is taken from list [1,2,3,4,5,6] and X is greater than 3.</p>
<p>In foregoing example: <u><em>X &lt;- [1,2,3,4,5,6]</em></u> is a <strong>generator</strong> and <em><u>X &gt; 3</u></em> is a <strong>filter</strong>.</p>
<p>Several filters can be combined:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,a,2,3,b,4,5,6], X &gt; 3].</span>
[a,b,4,5,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,a,2,3,b,4,5,6], integer(X), X &gt; 3].</span>
[4,5,6]</pre>
<p>Generator part may act as a filter in list comprehension:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">[X || {X, a} &lt;- [{1, a}, {2, b}, {3, a}, erlang]].</span>
[1,3]</pre>
<p>Generators can be combined too in list comprehensions. This is the Cartesian product of two lists:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">[{X, Y} || X &lt;- [1, 2, 3], Y &lt;- [a, b]].</span>
[{1,a},{1,b},{2,a},{2,b},{3,a},{3,b}]</pre>
<p>This is how elegantly quicksort algorithm is solved with the help of list comprehensions in Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(sort).
<span style="color:#87cefa;">-export</span>([qsort/1]).

<span style="color:#87cefa;">qsort</span>([]) -&gt;<span style="color:#87cefa;"> </span>[];
<span style="color:#87cefa;">qsort</span>([<span style="color:#eedd82;">Pivot</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    qsort([<span style="color:#eedd82;">X</span> || <span style="color:#eedd82;">X</span> &lt;- <span style="color:#eedd82;">Tail</span>, <span style="color:#eedd82;">X</span> &lt; <span style="color:#eedd82;">Pivot</span>])
        ++ [<span style="color:#eedd82;">Pivot</span>] ++
        qsort([<span style="color:#eedd82;">X</span> || <span style="color:#eedd82;">X</span> &lt;- <span style="color:#eedd82;">Tail</span>, <span style="color:#eedd82;">X</span> &gt;= <span style="color:#eedd82;">Pivot</span>]).</pre>
<p>Compile and run:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/sort", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,sort}
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">sort:qsort([7, 5, 9, 3, 6]).</span>
[3,5,6,7,9]</pre>
<p>Usage of list comprehensions instead of some higher-order functions:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">lists:map(fun(X) -&gt; X*2 end, [1, 2, 3]).</span>
[2,4,6]
<span style="color:#00ffff;">9&gt; </span><span style="font-weight:bold;">[X*2 || X &lt;- [1, 2, 3]].</span>
[2,4,6]</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">10&gt; </span><span style="font-weight:bold;">lists:filter(fun(X) -&gt; X rem 2 == 0 end, [1, 2, 3, 4]).</span>
[2,4]
<span style="color:#00ffff;">11&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1, 2, 3, 4], X rem 2 == 0].</span>
[2,4]</pre>
<h4><u>Python:</u></h4>
<pre><strong>[</strong>expression <strong>for</strong> expr1 <strong>in</strong> seq1 <strong>if</strong> cond1
            <strong>for</strong> expr2 <strong>in</strong> seq2 <strong>if</strong> cond2
            <strong>for</strong> exprN <strong>in</strong> seqN <strong>if</strong> condN<strong>]</strong></pre>
<p>this actually transforms to:</p>
<pre>
for expr1 in seq1:
    if not cond1:
        continue
    for expr2 in seq2:
        if not cond2:
            continue
        for exprN in seqN:
            if not condN:
                continue</pre>
<p>So in Python Cartesian product of two lists <em>[1, 2, 3 ]</em> and <em>['a', 'b']</em> will look like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">[(x, y) for x in [1, 2, 3] for y in ['a', 'b']]</span>
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]</pre>
<h4><u>Variable bindings and scope rules in List Comprehensions:</u></h4>
<p>Current Python 2.x &#8220;leaks&#8221; loop variable into surrounding scope. This should be solved in Python 3.0</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name 'x' is not defined
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist = [x for x in 'abc']</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist</span>
['a', 'b', 'c']
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
'c'</pre>
<p>To avoid leaking loop variable into surrounding scope we can use generator expression which doesn&#8217;t &#8220;leak&#8221;:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist = list(x for x in 'abc')</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist</span>
['a', 'b', 'c']
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name 'x' is not defined</pre>
<p>Erlang has following scope rules for variables in list comprehensions(from Erlang manual):</p>
<ul>
<li> all variables which occur in a generator pattern are         assumed to be &#8220;fresh&#8221; variables</li>
<li> any variables which are defined before the list         comprehension and which are used in filters have the values         they had before the list comprehension</li>
<li> no variables may be exported from a list comprehension</li>
</ul>
<p>So, Erlang doesn&#8217;t &#8220;leak&#8221; variables:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1, 2, 3]].</span>
[1,2,3]
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X.</span>
** 1: variable 'X' is unbound **</pre>
<p>Be careful, sometimes you need to move some pattern matching operations into filter:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(listcomp).
<span style="color:#87cefa;">-export</span>([select/2]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">This select produces following warning during compilation:
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">Warning: variable 'X' shadowed in generate
</span><span style="color:#87cefa;">select</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">List</span>) -&gt;
    [<span style="color:#eedd82;">Y</span> || {<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">Y</span>} &lt;- <span style="color:#eedd82;">List</span>].</pre>
<p>The function doesn&#8217;t produce desired result:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">listcomp:select(b, [{b, 1}, {c, 2}, {b, 3}]).</span>
[1,2,3]</pre>
<p>So we modify generator and move pattern matching operation into filter to achieve what we need:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(listcomp).
<span style="color:#87cefa;">-export</span>([select/2]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">Moving X from pattern matching into filter
</span><span style="color:#87cefa;">select</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">List</span>) -&gt;
    [<span style="color:#eedd82;">Y</span> || {<span style="color:#eedd82;">X1</span>, <span style="color:#eedd82;">Y</span>} &lt;- <span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">X</span> == <span style="color:#eedd82;">X1</span>].</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">listcomp:select(b, [{b, 1}, {c, 2}, {b, 3}]).</span>
[1,3]</pre>
<p>As you saw, while different in syntax, both languages provide valuable language construct which allows to write shorter and more elegant programs.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Delete blank lines with flush-lines</title>
		<link>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/</link>
		<comments>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/#comments</comments>
		<pubDate>Sun, 21 Oct 2007 23:12:07 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/</guid>
		<description><![CDATA[Sometimes after I copy-paste code snippets from web page into emacs buffer I get text with superfluous blank lines delimiting code. Marking region and running M-x flush-lines RET ^$ RET quickly makes it better by removing those pesky blank lines. This is, of course, makes sense only if pasted code doesn&#8217;t contain blank lines you [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes after I copy-paste code snippets from web page into  emacs buffer I get text with superfluous blank lines delimiting code.</p>
<p>Marking region and running <strong>M-x flush-lines RET ^$ RET</strong> quickly makes it better by removing those pesky blank lines. This is, of course, makes sense only if pasted code doesn&#8217;t contain blank lines you want to preserve.</p>
<p><em>Update</em>:<br />
You may need to use something more complex than simple <strong>^$</strong> (something like <strong>^W*$</strong> as regexp) if &#8220;blank&#8221; line contains some whitespace characters.</p>
<p>Example before:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-export</span>([test1/0,

         test2/0,

         test3/0,

         double/1]).</pre>
<p>After marking region and applying <strong>M-x flush-lines RET ^W*$ RET</strong>  (in your case just <strong>^$</strong> may be sufficient):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Incremental search forward</title>
		<link>http://ruslanspivak.com/2007/10/05/incremental-search-forward/</link>
		<comments>http://ruslanspivak.com/2007/10/05/incremental-search-forward/#comments</comments>
		<pubDate>Fri, 05 Oct 2007 21:41:36 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/05/incremental-search-forward/</guid>
		<description><![CDATA[Well-known incremental search forward(isearch-forward Lisp function) which is invoked with C-s has also additional useful key-bindings which I use often to instruct what to search. After you pressed C-s in buffer they are: C-w to yank next word or character in buffer onto the end of the search string, and search for it. You can [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Well-known incremental search forward(<strong>isearch-forward</strong> Lisp function) which is invoked with <strong>C-s</strong> has also additional useful key-bindings which I use often to instruct what to search. After you pressed <strong>C-s</strong> in buffer they are:</p>
<ol>
<li><strong>C-w</strong> to yank next word or character in buffer onto the end of the search string, and search for it. You can repeatedly press <strong>C-w</strong> consuming next word or character.</li>
<li><strong>C-y</strong> to yank rest of line onto end of search string and search for it.</li>
<li><strong>M-n</strong>/<strong>M-p</strong> to search for the next/previous item in the search ring.</li>
</ol>
<p>As usual for more information read help (<strong>C-h k C-s</strong> or <strong>C-h f isearch-forward RET</strong> ).</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/05/incremental-search-forward/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>align-regexp</title>
		<link>http://ruslanspivak.com/2007/10/03/align-regexp/</link>
		<comments>http://ruslanspivak.com/2007/10/03/align-regexp/#comments</comments>
		<pubDate>Wed, 03 Oct 2007 00:16:01 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/03/align-regexp/</guid>
		<description><![CDATA[This interactive Emacs Lisp function was very handy for me during some log files analysis. You mark region, invoke function, provide regexp and voila &#8211; your region is aligned. Example data from align-regexp help: Fred (123) 456-7890 Alice (123) 456-7890 Mary-Anne (123) 456-7890 Joe (123) 456-7890 Let&#8217;s say we want to align region on &#8220;(&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This interactive Emacs Lisp function was very handy for me during some log files analysis.</p>
<p>You mark region, invoke function, provide <em>regexp </em>and voila &#8211; your region is aligned.</p>
<p>Example data from <strong>align-regexp</strong> help:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Fred (123) 456-7890
Alice (123) 456-7890
Mary-Anne (123) 456-7890
Joe (123) 456-7890</pre>
<p>Let&#8217;s say we want to align region on &#8220;<strong>(</strong>&#8221; character. For that we mark region we want to align and invoke function with: <strong>M-x align-regexp RET (  RET</strong><br />
Result of such invocation will be:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Fred      (123) 456-7890
Alice     (123) 456-7890
Mary-Anne (123) 456-7890
Joe       (123) 456-7890</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/03/align-regexp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Part IV</title>
		<link>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/</link>
		<comments>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/#comments</comments>
		<pubDate>Tue, 02 Oct 2007 16:17:49 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/</guid>
		<description><![CDATA[Previous parts: Intro, Part I, Part II and Part III Funs &#8211; sequel Continuing previous post about functions let&#8217;s remember about Fun. I already mentioned it in Part I and promised to show its advanced forms. So, here we go. Fun with one clause: 1&#62; Double = fun(X) -&#62; X * 2 end. #Fun&#60;erl_eval.6.56006484&#62; 2&#62; [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>, <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a> and <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">Part III</a></p>
<h3>Funs &#8211; sequel</h3>
<p>Continuing previous post about functions let&#8217;s remember about <strong>Fun</strong>. I already mentioned it in <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a> and promised to show its advanced forms. So, here we go.</p>
<p><strong>Fun</strong> with one <strong>clause</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Double = fun(X) -&gt; X * 2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Double(2).</span>
4</pre>
<p>But <strong>Fun</strong> actually has the same <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">function declaration syntax as regular function</a>, except that it has no name in declaration, so we can have this:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">Big = fun (X) when X &gt; 100 -&gt; true;</span>
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">          (X) -&gt; false</span>
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">      end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">lists:filter(Big, [20, 30, 120, 130]).</span>
[120,130]</pre>
<p>As you see our <strong>Fun</strong> has <strong>two clauses</strong> separated by <strong>semicolon(;)</strong> and first clause has also <strong>guard</strong>, ie syntax is the same as in regular function declaration.</p>
<p>There are also following fun expressions that can be used:</p>
<ol>
<li><strong>fun FunctionName/Arity</strong> (<em>FunctionName</em> should point to local function defined in the same module with our <strong>fun</strong>)</li>
<li><strong>fun Module:FunctionName/Arity</strong> (<em>FunctionName</em> should be exported from module <em>Module</em>)</li>
</ol>
<p><strong>fun FunctionName/Arity</strong> is just <em>syntactic sugar </em>for <strong>fun (X1, ..Xn) -&gt; FunctionName(X1, .., Xn) end.</strong></p>
<p>Let&#8217;s take a look on foregoing in action and create <em>mymath.erl</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).

<span style="color:#87cefa;">test1</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">X</span> * 2 <span style="color:#00ffff;">end</span>, [1, 2, 3]).

<span style="color:#87cefa;">test2</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> double_local/1, [1, 2, 3]).

<span style="color:#87cefa;">test3</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> mymath:double/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported
</span><span style="color:#87cefa;">double_local</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, exported
</span><span style="color:#87cefa;">double</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.</pre>
<p>Compile and test it (I&#8217;m compiling as usual in Emacs with <strong>C-c C-k</strong>):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">mymath:test1().</span>
[2,4,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">mymath:test2().</span>
[2,4,6]
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">mymath:test3().</span>
[2,4,6]</pre>
<p>Also <strong>tuple of type {Module, FunctionName}</strong> is interpreted as a <strong>fun Module:FunctionName/Arity</strong> which you already saw. This usage is deprecated, but to be complete here is an example:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">Append = {lists, append}.</span>
{lists,append}
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">Append([1, 2], [3, 4, 5]).</span>
[1,2,3,4,5]</pre>
<p>As you already noted <strong>Fun</strong> in Erlang is <em>&#8220;richer&#8221;</em> than <strong>lambda</strong> in Python.</p>
<h3> Built-in functions, BIFs</h3>
<p>Both Erlang and Python provide built-in functions that are always available and do not require explicit usage of module name to use them.</p>
<p><u>Python:</u></p>
<p>Read more about builtins in <a href="http://docs.python.org/lib/builtin.html">library reference</a>.</p>
<p>In Python shell you can inspect in addition contents of __builtins__ module if you need:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">import pprint</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">pprint.pprint(dir(__builtins__))</span>
['ArithmeticError',
 'AssertionError',
 ...
 'type',
 'unichr',
 'unicode',
 'vars',
 'xrange',
 'zip']</pre>
<p><u>Erlang:</u><br />
Most of the built-in functions belong to module <em>erlang</em> and they are <strong>auto-imported</strong>.<br />
To get list of all BIFs with description read <em>man erlang</em>.<br />
In Eshell you can get list of functions that belong to <em>erlang</em> module with <strong>m(Module).</strong> command:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">m(erlang).</span>
Module erlang compiled: No compile time info available
Compiler options:  []
Object file: preloaded
<span style="color:#87cefa;">Exports</span>:
'!'/2                         list_to_existing_atom/1
'$erase'/1                    list_to_float/1
'$erase'/0                    list_to_integer/2
'$get'/1                      list_to_integer/1
'$get'/0                      list_to_pid/1
'$get_keys'/1                 list_to_tuple/1
'$put'/2                      load_module/2
'*'/2                         loaded/0
'+'/1                         localtime/0
'+'/2                         localtime_to_universaltime/1
'++'/2                        localtime_to_universaltime/2
...
ok</pre>
<p>Take into account though that not all functions in above list that you&#8217;ll see are auto-imported and may require usage of <em>module:</em> prefix. Again, for more information read <em>man erlang</em> (either in command line with <strong>erl -man erlang</strong> or if you use Emacs take a look at <a href="http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/">Erlang man pages in Emacs</a>)</p>
<h3>Macros</h3>
<p>Python does not have them, Erlang does. In Erlang they are not as powerful as in <a href="http://www.gigamonkeys.com/book/macros-defining-your-own.html">Common Lisp</a>, but more like in C.</p>
<p>They are defined in following form:</p>
<pre><strong>-define(Const, Replacement).
-define(Func(Var1,...,VarN), Replacement).</strong></pre>
<p>Whenever erlang preprocessor encounters expression of form <strong>?MacroName</strong> it expands corresponding macro.<br />
Define <em>utils.erl</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(utils).
<span style="color:#87cefa;">-export</span>([foo/0]).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">TIMEOUT</span>, 100).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">FUNCMACRO</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">Y</span>), {<span style="color:#eedd82;">X</span>, x, <span style="color:#eedd82;">Y</span>, y}).

<span style="color:#87cefa;">foo</span>() -&gt;
    io:format(<span style="color:#ffa07a;">"TIMEOUT = ~p~n"</span>, [?<span style="color:#7fffd4;">TIMEOUT</span>]),
    ?<span style="color:#7fffd4;">FUNCMACRO</span>(3, 7).</pre>
<p>Compile and run:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">utils:foo().</span>
TIMEOUT = 100
{3,x,7,y}</pre>
<p>There are also some predefined macros:</p>
<dl>
<dt> <strong><code>?MODULE</code></strong> </dt>
<dd> The name of the current module. </dd>
<dt> <strong><code>?MODULE_STRING</code></strong>. </dt>
<dd> The name of the current module as a string. </dd>
<dt> <strong><code>?FILE</code></strong>. </dt>
<dd> The file name of the current module. </dd>
<dt> <strong><code>?LINE</code></strong>. </dt>
<dd> The current line number. </dd>
<dt> <strong><code>?MACHINE</code></strong>. </dt>
<dd> The machine name, <code>'BEAM'</code>.</dd>
</dl>
<p>Having <strong>?MODULE</strong> we can rewrite earlier example with <strong>Fun</strong> as:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).

<span style="color:#87cefa;">test1</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">X</span> * 2 <span style="color:#00ffff;">end</span>, [1, 2, 3]).

<span style="color:#87cefa;">test2</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> double_local/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">test3() -&gt; lists:map(fun mymath:double/1, [1, 2, 3]).
</span><span style="color:#87cefa;">test3</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> ?<span style="color:#7fffd4;">MODULE</span>:double/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported
</span><span style="color:#87cefa;">double_local</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, exported
</span><span style="color:#87cefa;">double</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.</pre>
<p>And as usual compile and run to see that result is the same:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;"> mymath:test1().</span>
[2,4,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;"> mymath:test2().</span>
[2,4,6]
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;"> mymath:test3().</span>
[2,4,6]</pre>
<p>In addition there is also <strong>flow control</strong> in macros. Some of corresponding macro directives are:</p>
<ul>
<li><strong>ifdef(Macro).</strong> &#8211; Evaluate the following lines only if <em>Macro</em> is defined.</li>
<li><strong>else.</strong> &#8211; It&#8217;s used after <em>ifdef</em> or <em>ifndef</em></li>
<li><strong>endif. </strong>- Marks the end of <em>ifdef</em> or <em>ifndef</em> directive</li>
</ul>
<p>Example in <em>utils.erl</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(utils).
<span style="color:#87cefa;">-export</span>([foo/0]).

<span style="color:#87cefa;">-ifdef</span>(<span style="color:#7fffd4;">debug</span>).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">LOG</span>(<span style="color:#eedd82;">Msg</span>), io:format(<span style="color:#ffa07a;">"{~p:~p}: ~p~n"</span>, [?<span style="color:#7fffd4;">MODULE</span>, ?<span style="color:#7fffd4;">LINE</span>, <span style="color:#eedd82;">Msg</span>])).
<span style="color:#87cefa;">-else</span>.
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">LOG</span>(<span style="color:#eedd82;">Msg</span>), true).
<span style="color:#87cefa;">-endif</span>.

<span style="color:#87cefa;">foo</span>() -&gt;
    ?<span style="color:#7fffd4;">LOG</span>(<span style="color:#ffa07a;">"Debug is enabled"</span>).</pre>
<p>To turn LOG macro on <em>debug</em> should be defined. This can be achieved from command line with <strong>erlc -Ddebug utils.erl</strong> or from Eshell using <strong>c/2</strong> function:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c(utils, {d, debug}).</span>
{ok,utils}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">utils:foo().</span>
{utils:11}: "Debug is enabled"
ok</pre>
<p>To turn LOG macro off <em>debug</em> should be omitted:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">c(utils).</span>
{ok,utils}
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">utils:foo().</span>
true</pre>
<p>To be continued.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating tables in Emacs</title>
		<link>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/</link>
		<comments>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/#comments</comments>
		<pubDate>Mon, 01 Oct 2007 13:13:18 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/</guid>
		<description><![CDATA[Sometimes I need to create tables in Emacs as it was in post describing comparison and arithmetic operations in Python and Erlang. Over time I became aware of several means to create tables and export them in different formats in Emacs(at the moment I&#8217;m personally interested in plain ASCII and HTML): Excellent org-mode has built-in [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes I need to create tables in Emacs as it was in <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">post</a> describing comparison and arithmetic operations in Python and Erlang.</p>
<p>Over time I became aware of several means to create tables and export them in different formats in Emacs(at the moment I&#8217;m personally interested in plain ASCII and HTML):</p>
<ol>
<li>Excellent <a href="http://orgmode.org/">org-mode</a> has built-in <a href="http://orgmode.org/org.html#Tables">table editor</a>  which allows easily format tables in plain ASCII</li>
<li><a href="http://table.sourceforge.net/">table.el</a> with its advanced ability to construct table layout</li>
</ol>
<p>Both modes (technically though Table mode in <em>table.el</em> is not mode) are part of modern Emacs and both allow export table in HTML format.</p>
<p>To quickly create tables personally I prefer <em>table.el</em> which provides also following features:</p>
<ol>
<li>A cell can be split horizontally and vertically.</li>
<li>A cell can span into an adjacent cell.</li>
</ol>
<p>Use <strong>C-h b </strong>in table to get self-descriptive information about table.el key bindings. In contrast to <em>org-mode</em>(or its <em>orgtbl-mode</em> minor mode) <em>table.el</em> has no special bindings to copy row/cell and yank it. But this is easily achieved by using usual region commands for rows and rectangular commands for cells.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Part III</title>
		<link>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/</link>
		<comments>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/#comments</comments>
		<pubDate>Sun, 23 Sep 2007 23:53:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/</guid>
		<description><![CDATA[Previous parts: Intro, Part I and Part II Today we are going to take a look at functions. In Erlang there is no direct correspondence to what we have in Python: 1. default values, keyword arguments and formal parameter of form **name def foo(key, name='ruslan', type='unknown', **kw): print 'key = %s, name = %s, type [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a> and <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a></p>
<p>Today we are going to take a look at functions.<br />
In Erlang there is no direct correspondence to what we have in Python:</p>
<p>1. default values, keyword arguments and formal parameter of form <strong>**name</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">foo</span>(key, name=<span style="color:#ffa07a;">'ruslan'</span>, type=<span style="color:#ffa07a;">'unknown'</span>, **kw):
    <span style="color:#00ffff;">print</span> <span style="color:#ffa07a;">'key = %s, name = %s, type = %s'</span> % (key, name, type)
    <span style="color:#00ffff;">for</span> key, val <span style="color:#00ffff;">in</span> kw.items():
        <span style="color:#00ffff;">print</span> <span style="color:#ffa07a;">'%s = %s'</span> % (key, val)</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">foo(1)</span>
key = 1, name = ruslan, type = unknown
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">foo(1, type='known', x=1, y=10)</span>
key = 1, name = ruslan, type = known
y = 10
x = 1</pre>
<p>2. formal parameter of form <strong>*name</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">double_sum</span>(*args):
    <span style="color:#00ffff;">return</span> sum(x * 2 <span style="color:#00ffff;">for</span> x <span style="color:#00ffff;">in</span> args)</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">double_sum(2, 4, 5)</span>
22</pre>
<p>Let&#8217;s take a look at Erlang&#8217;s <u><em>function declaration syntax</em> (</u>a bit modified from Erlang Reference Manual):</p>
<ol>
<li><strong>Function declaration</strong> consists of function <strong>clauses</strong> separated by <strong>semicolons (;) </strong>and terminated by <strong>period (.)</strong></li>
<li><strong>Function clause</strong> consists of <strong>head</strong> and <strong>body</strong> separated by <strong>-&gt;</strong></li>
<li>A <strong>clause head</strong> consists of <em>function name</em> (which is atom), <em>argument list</em>(each argument is <strong>pattern</strong>) and optional <strong>guard sequence</strong> beginning with keyword <strong>when</strong>.</li>
<li>A <strong>clause body</strong> consists of sequence of expressions separated by <strong>comma (,)</strong></li>
</ol>
<h4>Name(Pattern11,&#8230;,Pattern1N) [when GuardSeq1] -&gt;<br />
Body1;<br />
&#8230;;<br />
Name(PatternK1,&#8230;,PatternKN) [when GuardSeqK] -&gt;<br />
BodyK.</h4>
<h4></h4>
<h4>where Body is in form:<br />
Expr1,<br />
Expr2,<br />
&#8230;<br />
ExprN</h4>
<p>Number of arguments in function is called <strong>arity</strong>. Function is uniquely identified by combination of <u><em>module name</em></u>, <u><em>function name</em></u> and <u><em>function&#8217;s arity</em></u> and this form is often written as <strong>m:f/N</strong>. Two functions in the module with the same name, but different arity<br />
are completely different functions, remember it.</p>
<p>Enough dry theory, let&#8217;s define our Erlang <em>factorial</em> function in module <em>mymath.erl</em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1;
<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1).</pre>
<p>What we have here:</p>
<p>1) <strong>function declaration</strong> of one function called  <em>factorial</em><br />
2) there are two <strong>clauses</strong><br />
- first clause separated by <strong>semicolon (;)</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1;</pre>
<p>- second and final clause terminated with <strong>period (.)</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1).</pre>
<p>3) Every clause (first and second) has correspondingly head and body. Head consists of function&#8217;s name, in our case it&#8217;s <u>factorial</u> and after follows arguments list which contains patterns. In first clause pattern is <strong>0</strong>, in second &#8211; <strong>N</strong>.</p>
<p>How this works:</p>
<p>When function is entered, the function clauses are pattern matched against passed arguments. Pattern matching happens in order functions are defined in module. So when you enter</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">mymath:factorial(5).</span>
120</pre>
<p>first <strong>5</strong> is matched against clause <strong>factorial(0)</strong> and fails as <strong>5 != 0</strong>, then <strong>5</strong> is matched against <strong>N</strong> in second clause and pattern matching succeeds. As a result unbound variable <strong>N</strong> in pattern becomes bound and gets value <strong>5</strong>. This leads to execution of body of second clause, namely<strong> N * factorial(N-1)</strong>. This happens recursively until <strong>N</strong> becomes <strong>0</strong> and first clause<strong> factorial(0)</strong> is executed terminating recursion.<br />
The same <em>factorial</em> function will look in Python without pattern matching like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">factorial</span>(n):
    <span style="color:#00ffff;">if</span> n == 0:
        <span style="color:#00ffff;">return</span> 1
    <span style="color:#00ffff;">return</span> n * factorial(n-1)</pre>
<p>In Python&#8217;s version we &#8220;hardcoded&#8221; branching in function&#8217;s body.</p>
<p>The benefits of pattern matching are that when conditions inside function become complex you may do your job better and write less code using pattern matching and also if you have big function this may mean that you do not have to modify body of your function but to add another clause with corresponding pattern.</p>
<p>Earlier I mentioned that function clauses are pattern matched in order they are defined in module. For our function this is important. If we change order of clauses this will lead to problems, as the condition to terminate recursion never appear:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>When compiling we will get warning (use <strong>C-c C-k</strong> in Emacs or <strong>c(mymath).</strong> in Eshell to compile)</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
<span style="color:#ffc0cb;font-weight:bold;text-decoration:underline;">/home/alienoid/dev/erlang/mymath.erl</span><span style="text-decoration:underline;">:</span><span style="color:#eedd82;text-decoration:underline;">6</span><span style="text-decoration:underline;">:</span><span style="text-decoration:underline;"> Warning</span>: this clause cannot match because a previous clause at line 4 always matches
{ok,mymath}</pre>
<p>indicating that second clause will never match, but still you can call the function (it will most likely to crash after eating all your available memory).</p>
<p>You can easily avoid that problem introducing <strong>guard</strong> that starts with keyword <strong>when</strong> in function clause&#8217;s head:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>Now you can put those two clauses in any order you like. I should also add that if during pattern matching no matched function clause is found a <em>function_clause</em> run time error will occur:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">mymath:factorial(-4).</span>

=ERROR REPORT==== 24-Sep-2007::01:53:25 ===
Error in process &lt;0.29.0&gt; with exit value: {function_clause,[{mymath,factorial,[-4]},{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop,3}]}

** exited: {function_clause,[{mymath,factorial,[-4]},
                             {erl_eval,do_apply,5},
                             {shell,exprs,6},
                             {shell,eval_loop,3}]} **</pre>
<p>What is <strong>guard</strong> anyway ? Guards make pattern matching more powerful, they can be used to perform different tests and comparison operations on variables in a pattern as you could see.  You can have several <em>guard expressions</em> in clause separated by <strong>commans (,). </strong>The guard<strong> </strong>containing several guard expressions evaluates to <strong>true</strong> only if every guard expression evaluates to true. Example of guard containing several guard expressions:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_integer</span>(<span style="color:#eedd82;">N</span>), <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>For above definition calling <u>mymath:factorial(5)</u> reads as: <strong>choose clause factorial(N) when (N is integer AND N &gt; 0)</strong></p>
<p>There are also <strong>guard sequences</strong> which have form <strong>guard1; guard2; &#8230;; guardN</strong> and guard sequence evaluates to true if at least one guard is evaluated to true:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_integer</span>(<span style="color:#eedd82;">N</span>), <span style="color:#eedd82;">N</span> &gt; 0; <span style="color:#7fffd4;">is_list</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>For above definition calling <u>mymath:factorial(5)</u> reads as: <strong>choose clause factorial(N) when (N is integer AND N &gt; 0) OR N is list</strong>.</p>
<p>You have probably noted that the way we defined our factorial function means that it will be calling itself recursively and this will use stack and stack is not infinite resource. We need to do something about our function and this means to make it <strong>tail recursive</strong>. When last expression in function body is function call this means that call is <strong>tail recursive</strong> and this is how infinite loop may be done without consuming stack resources. So here is our new <strong>tail-recursive</strong> function <u><em>factorial</em></u> that uses accumulator to pass value of previous calculation:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">this one is exported, arity is 1
</span><span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    factorial(<span style="color:#eedd82;">N</span>, 1).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported, arity is 2
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">tail-recursive, uses accumulator to store
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">calculation between invocations
</span><span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>, <span style="color:#eedd82;">Acc</span>) <span style="color:#00ffff;">when</span> <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    factorial(<span style="color:#eedd82;">N</span>-1, <span style="color:#eedd82;">N</span>*<span style="color:#eedd82;">Acc</span>);
<span style="color:#87cefa;">factorial</span>(0, <span style="color:#eedd82;">Acc</span>) -&gt;
    <span style="color:#eedd82;">Acc</span>.</pre>
<p>In foregoing example you can see guards, tail-recursion, usage of accumulators, functions with different arities. Experiment with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>comment-dwim and comment-style</title>
		<link>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/</link>
		<comments>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/#comments</comments>
		<pubDate>Thu, 20 Sep 2007 21:24:11 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/</guid>
		<description><![CDATA[In my previous post I mentioned that if you use Emacs and you&#8217;re editing Erlang source code you can easily comment whole marked region by invoking M-; to which by default bound interactive Lisp function comment-dwim. This works in different modes and it&#8217;s very handy especially if your language of choice has no multiline comments. [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In my <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">previous post</a> I mentioned that if you use Emacs and you&#8217;re editing Erlang source code you can easily comment whole marked region by invoking <strong>M-;</strong> to which by default bound interactive Lisp function  <strong>comment-dwim</strong>. This works in different modes and it&#8217;s very handy especially if your language of choice has no multiline comments.</p>
<p>So far so good, but I must admit sometimes I get the blues when I comment some nested code blocks with <strong>M-;</strong> keystrokes. Well, maybe I&#8217;m blowing things out of proportion about my sadness, but in any case recently I came across really nice small blog post called <a href="http://edward.oconnor.cx/2007/09/comment-style">comment-style</a> and since then I&#8217;m happy with comments produced in nested blocks. Let&#8217;s see why.</p>
<p>When you comment marked regions in Emacs buffer with <strong>M-;</strong> the <strong>comment-style</strong> variable defines the way regions are commented.  Default value is <strong>plain</strong>.</p>
<p>Buffer with Python code before commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#00ffff;">if</span> key == seq[mid]:
        <span style="color:#00ffff;">return</span> mid
    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>Buffer with Python code after commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#ff4500;"># if key == seq[mid]:
</span><span style="color:#ff4500;">#         </span><span style="color:#ff4500;">return mid
</span>    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>As you see visually elements of commented block are not on the same line.</p>
<p>Example with Erlang code before commenting (somewhat far-fetched example though our main concern are comments, not code here):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            io:format(<span style="color:#ffa07a;">"Hd = ~p~n"</span>, [<span style="color:#eedd82;">Hd</span>]),
            true,
            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>After commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">io:format("Hd = ~p~n", [Hd]),
</span><span style="color:#ff4500;">%%             </span><span style="color:#ff4500;">true,
</span>            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>So the visual issue with comments is the same.</p>
<p>After reading foregoing blog post about comment-style I&#8217;ve added this line to my <em>.emacs</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(setq comment-style 'indent)</pre>
<p>Easy as pie and which means (taken from Emacs help): &#8221; &#8230;`<em>comment-start&#8217; markers should not be put at the left margin but at the current indentation of the region to comment</em>.&#8221;</p>
<p>After that addition foregoing commented block in Python mode will look like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#ff4500;"># if key == seq[mid]:
</span>    <span style="color:#ff4500;">#     return mid
</span>    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>in Erlang mode:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">io:format("Hd = ~p~n", [Hd]),
</span>            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">true,
</span>            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>Now I am happy. Thank you, <a href="http://edward.oconnor.cx/2007/09/comment-style">Edward</a> for the tip.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Part II</title>
		<link>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/</link>
		<comments>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/#comments</comments>
		<pubDate>Sun, 16 Sep 2007 21:54:23 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/</guid>
		<description><![CDATA[In this short tutorial we will take a look at comparison operations, some arithmetic operations and modules. You may also want to skim over Inro and Part I. Comparison operations Python Erlang Description Erlang Example --------+--------+-----------------------+---------------- &#60; &#60; strictly less than --------+--------+-----------------------+---------------- &#60;= =&#60; less than or equal --------+--------+-----------------------+---------------- &#62; &#62; strictly greater than --------+--------+-----------------------+---------------- [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In this short tutorial we will take a look at comparison operations, some arithmetic operations and modules. You may also want to skim over <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Inro</a> and <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>.</p>
<h3><u><strong>Comparison operations</strong></u></h3>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
 Python   Erlang   Description             Erlang Example
 --------+--------+-----------------------+----------------
  &lt;        &lt;        strictly less than
 --------+--------+-----------------------+----------------
  &lt;=       =&lt;       less than or equal
 --------+--------+-----------------------+----------------
  &gt;        &gt;        strictly greater than
 --------+--------+-----------------------+----------------
  &gt;=       &gt;=       greater than or equal
 --------+--------+-----------------------+----------------
  !=       /=       not equal
 --------+--------+-----------------------+----------------
  ==       ==       equal                   1&gt; 1 == 1.
                                            true
                                            2&gt; 1 == 1.0.
                                            true
 --------+--------+-----------------------+----------------
           =:=      exactly equal to        1&gt; 1 =:= 1.
                                            true
                                            2&gt; 1 =:= 1.0.
                                            false
 --------+--------+-----------------------+----------------
           =/=      exactly not equal to
 --------+--------+-----------------------+----------------
  is                object identity
 --------+--------+-----------------------+----------------
  is not            negated obj identity</pre>
<h4><u>Python notes</u></h4>
<p>Above comparison operations are supported by all objects. In Python you can chain comparisons:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y, z = 1, 3, 7</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x &lt; y &lt;= z</span>
True
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x &lt; y and y &lt;= z</span>
True</pre>
<p>Foregoing examples are identical, except that in second case <em><strong>y</strong></em> is evaluated twice.</p>
<h4><u>Erlang notes</u></h4>
<p>Following order is defined:</p>
<p><em>number &lt; atom &lt; reference &lt; fun &lt; port &lt; pid &lt; tuple &lt; list &lt; binary</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">5 &lt; erlang.</span>
true
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">erlang &lt; make_ref().</span>
true</pre>
<p>Both Erlang comparison operators (<strong>&lt;, =&lt;, &gt;, &gt;=, /=, ==</strong>) and Python comparison operators(<strong>&lt;, &lt;=, &gt;, &gt;=, !=, ==</strong>) make type coerce, &#8220;narrower&#8221; type is widened to that of another, ie when comparing integer and float first integer is converted to float, etc.<br />
Erlang has special operators without type coerce though: <strong>=:= </strong>and <strong>=/=</strong></p>
<h3><strong><u>Arithmetic operations</u></strong></h3>
<p>I&#8217;ll provide only several operations, for more take a look at corresponding language references.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
 Python   Python Desc.         Erlang    Erlang Desc.   Example
 --------+--------------------+---------+--------------+--------------------
  x % y    remainder            X rem Y   integer        &gt;&gt;&gt; 7 % 3
           of x / y                       remainder      1
                                          of X / Y       &gt;&gt;&gt; 7.0 % 3
                                                         1.0

                                                         1&gt; 7 rem 3.
                                                         1
                                                         1&gt; 7.0 rem 3.
                                                         =ERROR REP..
 --------+--------------------+---------+--------------+--------------------
  x / y    quotient             X / Y     floating       &gt;&gt;&gt; 7 / 3
           of x and y                     point          2
                                          division       &gt;&gt;&gt; 7.0 / 3
                                                         2.3333333333333335

                                                         1&gt; 7 / 3.
                                                         2.33333
 --------+--------------------+---------+--------------+--------------------
  x // y   (floored) quotient   X div Y   integer        &gt;&gt;&gt; 7 // 3
           of x and y,                    division       2
           integer division                              &gt;&gt;&gt; 7.5 // 3
           (result type is                               2.0
           not forced to be
           int)                                          1&gt; 7 div 3.
                                                         2</pre>
<h3><u><strong>Modules</strong></u></h3>
<p>Code in Erlang is organized into units called modules, which is familiar word for Python programmer.</p>
<p>Let&#8217;s define sample module with function declaration stored in file <em><strong>mymath.erl</strong></em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([fact/1]).

<span style="color:#87cefa;">fact</span>(0) -&gt;<span style="color:#87cefa;"> </span>1;
<span style="color:#87cefa;">fact</span>(<span style="color:#eedd82;">N</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">N</span> * fact(<span style="color:#eedd82;">N</span>-1).</pre>
<p><u>What we see here:</u></p>
<ol>
<li> module&#8217;s source code is stored in file with <strong>.erl</strong> extension</li>
<li>module consists of <strong>attributes</strong> and <strong>function declarations</strong> which are terminated by <strong>period</strong> (<strong>.</strong>)</li>
<li>we should provide module declaration defining name of the module</li>
</ol>
<ul>
<li>module name should be atom</li>
<li>module name is the same as file name minus <strong>.erl</strong> extension</li>
<li>module declaration is mandatory</li>
<li>module declaration attribute should be defined first.</li>
</ul>
<p>To make functions defined in module accessible outside the module we need to export them, for this <strong>-export</strong> module attribute exists. We write exported functions inside square brackets in form of <strong>func/N</strong> where <strong>N</strong> is the number of arguments of function, called <strong>arity.</strong> I&#8217;ll repeat that functions not pointed in <strong>-export</strong> will not be accessible outside module.</p>
<p>Before code can be run, module must be compiled. Resulting compiled file will contain extension <strong>.beam</strong></p>
<p>If you use Emacs you can compile module with <strong>C-c C-k</strong> and see results in erlang shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}</pre>
<p>Or you can compile it directly in shell. Make sure your shell&#8217;s current directory is where your <strong>mymath.erl</strong> lives, if it&#8217;s not the case use <em><strong>cd</strong></em> command in erlang shell, <em>cd(&#8220;/path/to/dir/with/mymath.erl&#8221;)</em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c(mymath).</span>
{ok,mymath}</pre>
<p>To invoke our function <strong>fact</strong> we use syntax <strong>mod:func</strong> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">mymath:fact(4).</span>
24</pre>
<p>Erlang has also <strong>-import</strong> attribute which allows to import functions into modules, so that you don&#8217;t need to use fully-qualified name <strong>mod:func</strong> to invoke function, again familiar behaviour and naming to Python programmer.</p>
<p>Erlang allows to insert code from file as-is with <strong>-include</strong> attribute at point where <strong>-import </strong>is defined, this is used to include records and macro definitions, for example.</p>
<p>Comments in Erlang module begin with character &#8220;<strong>%</strong>&#8220;, continue up to end-of-line and may be placed anywhere except inside string and quoted atoms.<br />
Like in Python Erlang has no multiline comments.<br />
If you use Emacs you can easily comment whole region with <strong>M-;</strong> command after you marked it.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([fact/1, print_double/1]).
<span style="color:#87cefa;">-import</span>(lists, [foreach/2]).
<span style="color:#87cefa;">-include</span>(<span style="color:#ffa07a;">"my_records.hrl"</span>).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum(L) -&gt;
</span><span style="color:#ff4500;">%%     </span><span style="color:#ff4500;">sum(L, 0).
</span>
<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum([H|T], Acc) -&gt;
</span><span style="color:#ff4500;">%%     </span><span style="color:#ff4500;">sum(T, H+Acc);
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum([], Acc) -&gt; Acc.
</span>
<span style="color:#87cefa;">fact</span>(0) -&gt;<span style="color:#87cefa;"> </span>1;
<span style="color:#87cefa;">fact</span>(<span style="color:#eedd82;">N</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">N</span> * fact(<span style="color:#eedd82;">N</span>-1).
<span style="color:#87cefa;">print_double</span>(<span style="color:#eedd82;">L</span>) -&gt;
    foreach(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span>io:format(<span style="color:#ffa07a;">"Double of ~p = ~p~n"</span>, [<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">X</span>*2]) <span style="color:#00ffff;">end</span>, <span style="color:#eedd82;">L</span>).</pre>
<p>Fin.</p>
<p>Next tutorial will be devoted to thorough exploration of functions in Erlang.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How to say big numbers in English: Common Lisp</title>
		<link>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/</link>
		<comments>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/#comments</comments>
		<pubDate>Wed, 12 Sep 2007 09:08:46 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/</guid>
		<description><![CDATA[When i was describing notations and representation of numbers in Erlang(and Python) i forgot to mention very cool feature of format function in Common Lisp, with which i got acquainted exploring highly-recommended Practical Common Lisp book. This feature is ~R directive which knows how to say really big numbers in English words. Here is the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When i was describing <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">notations and representation of numbers in Erlang(and Python)</a> i forgot to mention very cool feature of <strong>format </strong>function in Common Lisp, with which i got acquainted exploring highly-recommended <a href="http://www.gigamonkeys.com/book/">Practical Common Lisp</a> book.</p>
<p>This feature is  <strong>~R</strong> directive which knows how to say really big numbers in English words.</p>
<p>Here is the example (I use <a href="http://sbcl.sourceforge.net/">SBCL</a> + <a href="http://common-lisp.net/project/slime/">SLIME</a>):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">CL-USER&gt; </span>(format nil "~R" 1604872898756737459538)
<span style="color:#ff0000;">"one sextillion six hundred four quintillion eight hundred seventy-two
quadrillion eight hundred ninety-eight trillion seven hundred fifty-six
billion seven hundred thirty-seven million four hundred fifty-nine
thousand five hundred thirty-eight"</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Part I</title>
		<link>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/</link>
		<comments>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/#comments</comments>
		<pubDate>Sun, 09 Sep 2007 15:06:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/</guid>
		<description><![CDATA[Let&#8217;s skim over data types in Erlang today. Check previous tutorial for introduction. Numbers In Erlang there are two types of numeric literals: integers and floats. In Python there are four of them: plain integers(usually called just integers), long integers, floating point numbers, and imaginary numbers. In addition to conventional notation Erlang has its own [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Let&#8217;s skim over data types in Erlang today. Check <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">previous tutorial</a> for introduction.</p>
<h3><u><strong>Numbers</strong></u></h3>
<p>In Erlang there are two types of numeric literals: <strong>integers</strong> and <strong>floats</strong>.<br />
In Python there are four of them: <strong>plain integers</strong>(usually called just integers), <strong>long integers</strong>, <strong>floating point numbers</strong>, and <strong>imaginary numbers</strong>.</p>
<p>In addition to conventional notation Erlang has its own specific notations:<br />
1)  <strong>$char</strong><br />
Gives ASCII value of char<br />
2)  <strong>base#value</strong><br />
Produces integer. Base is in range [2,36]</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">$A.</span>
65
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">2#111.</span>
7
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">16#1A.</span>
26
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">5.</span>
5
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">2.55.</span>
2.55000</pre>
<p>In Python we can define <em>octinteger </em>and <em>hexinteger</em> correspondingly with:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">017, 0x1A</span>
<span style="background-color:#40e0d0;">(</span>15, 26<span style="background-color:#40e0d0;">)</span></pre>
<p>To produce integer from different bases in Python we may use built-in<strong> int</strong>([x[, <em>radix</em>]]), where <em>radix</em> is in range [2,36]:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">int("111", 2), int("1A", 16)</span>
<span style="background-color:#40e0d0;">(</span>7, 26<span style="background-color:#40e0d0;">)</span></pre>
<h3><u><strong>Atom</strong></u></h3>
<p>An atom is a literal or a constant with name. Atoms should start with<em> small letter</em> or it should be enclosed in single quote(&#8216;) if it contains other characters than alphanumeric characters, _, or @.<br />
Atoms can not have values like variables, they are simply names (constant with name).</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">erlang.</span>
erlang
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">'hello world'.</span>
'hello world'
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">'Erlang'.</span>
'Erlang'</pre>
<p>In Python there are also atoms in form of identifiers or literals, but no correspondence with Erlang&#8217;s <em>constant with name</em> type of atom.</p>
<p>More examples with atoms to come when we get acquainted with other data types<br />
and parts of Erlang.</p>
<h3><u><strong>Binary</strong></u></h3>
<p>From a reference manual:<br />
<em> &#8220;A binary is used to store an area of untyped memory.<br />
Binaries are expressed using the bit syntax.&#8221;</em></p>
<p>This data type allows to store large raw chunks of memory in an efficient way, much more space-efficient than in lists or tuples.</p>
<p>Binaries are written in double less-than and greater-than brackets and printed in that form as well.<br />
They can be constructed from set of constants or string literal:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">&lt;&lt;1,2,3&gt;&gt;.</span>
&lt;&lt;1,2,3&gt;&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">&lt;&lt;"erlang"&gt;&gt;.</span>
&lt;&lt;"erlang"&gt;&gt;</pre>
<p>Or from bound variables:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">A = 1, B = 2, C = 3.</span>
3
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">Bin = &lt;&lt;A, B, C&gt;&gt;.</span>
&lt;&lt;1,2,3&gt;&gt;</pre>
<p>Remember <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">pattern matching </a>?<br />
Binary (<strong>Bin</strong> for short) can also be used for matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">&lt;&lt;X, Y, Z&gt;&gt; = Bin.</span>
&lt;&lt;1,2,3&gt;&gt;
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">X.</span>
1
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">Y.</span>
2
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">Z.</span>
3</pre>
<p>There is more than that, namely <strong>bit syntax</strong> which allows to pack/unpack sequences of bits in Bin. Actually bit syntax is an extension to pattern matching.<br />
Let&#8217;s pack three variables into 16 bit memory area in a variable <em>Mem</em>, then unpack it to another three variables using bit syntax:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X = 2.</span>
2
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Y = 40.</span>
40
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">Z = 30.</span>
30
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">Mem = &lt;&lt;X:3, Y:7, Z:6&gt;&gt;.</span>
&lt;&lt;74,30&gt;&gt;
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">&lt;&lt;X1:3, Y1:7, Z1:6&gt;&gt; = Mem.</span>
&lt;&lt;74,30&gt;&gt;
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">X1.</span>
2
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">Y1.</span>
40
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">Z1.</span>
30</pre>
<p>In foregoing output you see that after packing shell prints packed three variables as &lt;&lt;74,30&gt;&gt; which is 16 bits.</p>
<p>In Python 2.5 there is no built-in data type to support binary data, but in Python 3000 binary data is represented by a separate mutable <em>&#8220;bytes&#8221;</em> data type.</p>
<h3><u><strong>Fun</strong></u></h3>
<p>Fun is an <em>anonymous</em> function, ie without name.</p>
<p>In Python this is infamous <strong>lambda</strong>, which had many debates whether it should remain in language or not. Personally i like <strong>lambda</strong> and glad it survived and will continue its life in Python 3000.</p>
<p>But Ok, back to Erlang&#8217;s <strong>Fun</strong>. Here how we can define it in shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Double = fun(X) -&gt; X * 2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Double(4).</span>
8</pre>
<p>In contrast to Python Erlang&#8217;s Fun can contain statements and is <em>&#8220;more advanced&#8221;</em> in general:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Print_val = fun(X) -&gt; io:format("X = ~p~n", [X]), X*2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Print_val(3).</span>
X = 3
6</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val = lambda x: print 'x = %d' % x; x*2</span>
  File "&lt;stdin&gt;", line 1
    print_val = lambda x: print 'x = %d' % x; x*2
                              ^
<span style="color:#87cefa;">SyntaxError</span>: invalid syntax
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val = lambda x: x*2</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val(3)</span>
6</pre>
<p>More advanced examples of Fun like Funs with several different clauses i&#8217;ll show when discussing in details functions in Erlang in upcoming tutorials.</p>
<h3><u><strong>Tuple</strong></u></h3>
<p>It&#8217;s a compound data type with fixed number of terms (Term is a piece of data of any data type). Number of elements in tuple is called <strong>size</strong> of tuple.<br />
Syntax of tuples is:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Tuple = {ruslan, 28}.</span>
{ruslan,28}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Info = {data, Tuple}.</span>
<span style="background-color:#40e0d0;">{</span>data,{ruslan,28}<span style="background-color:#40e0d0;">}</span></pre>
<p>In Python tuples are defined with or without enclosing parentheses:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">tup = "ruslan", 28</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">tup</span>
('ruslan', 28)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">info = ('data', tup)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">info</span>
<span style="background-color:#40e0d0;">(</span>'data', ('ruslan', 28)<span style="background-color:#40e0d0;">)</span></pre>
<p>To get number of elements in tuple.</p>
<p>Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">size(Info).</span>
2</pre>
<p>Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">len(info)</span>
2</pre>
<h3><u><strong>List</strong></u></h3>
<p>List is a compound data type with variable number of terms. Number of elements in a list is called <strong>length</strong> of the list.</p>
<p>List is declared in square brackets like in Python.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">List = [1, 2, 3, "erlang"].</span>
<span style="background-color:#40e0d0;">[</span>1,2,3,"erlang"<span style="background-color:#40e0d0;">]</span></pre>
<p>Now Erlang specific part, which may be familiar to you if you know a bit Lisp and its CAR/CDR stuff:<br />
List is either an empty list [] or may be represented as head (first element &#8211; CAR in Lisp) and tail (remainder of list &#8211; CDR in Lisp) which is also a list and often you can see it in form like <strong>[H|T]</strong>.<br />
This representation is recursive:<br />
[]<br />
]<br />
[b | ]]<br />
[a | [b | ]]]<br />
are all lists actually.</p>
<p>Let&#8217;s define list in shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">List = [a, 1, {b, 2}].</span>
<span style="background-color:#40e0d0;">[</span>a,1,{b,2}<span style="background-color:#40e0d0;">]</span></pre>
<p>and unpack it with pattern matching to head and tail:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">[H|T] = List.</span>
[a,1,{b,2}]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">H.</span>
a
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">T.</span>
<span style="background-color:#40e0d0;">[</span>1,{b,2}<span style="background-color:#40e0d0;">]</span></pre>
<p>As you see <em>T(tail)</em> above is also a list.</p>
<p>We can also construct list using head and tail syntax:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">List2 = .</span>
</pre>
<p>Working with Erlang you&#8217;ll see/use this syntax quite often.</p>
<p>To get number of elements in list.</p>
<p>Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">length(List2).</span>
3</pre>
<p>Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">len([1, 2, 3, "python"])</span>
4</pre>
<h3><u><strong>String</strong></u></h3>
<p>In Python string type is immutable sequence of characters. In Python there is no separate character type, a character is represented by a string of one item. String literals are written in single or double quotes:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">'xyz', "xyz"</span>
<span style="background-color:#40e0d0;">(</span>'xyz', 'xyz'<span style="background-color:#40e0d0;">)</span></pre>
<p>In Erlang strings are enclosed in double quotes, but unlike Python string is not separate data type actually. String &#8220;erlang&#8221; is just shorthand for list [$e, $r, $l, $a, $n, $g].</p>
<p>Adjacent string literals are concatenated at compile time:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">"hello" ", world" " in " "erlang".</span>
"hello, world in erlang"</pre>
<p>In Python behaviour with adjacent strings is the same:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">'hello' ', world' ' in ' 'python'</span>
'hello, world in python'</pre>
<h3><u><strong>Boolean</strong></u></h3>
<p>Again unlike Python Erlang has no built-in <strong>Boolean</strong> type, but it uses atoms <strong>true</strong> and <strong>false</strong> to denote <em>Boolean</em> values:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">1 &lt; 2.</span>
true
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">true or false.</span>
true</pre>
<p>In Python Boolean is separate data type:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">type(True), type(False)</span>
(&lt;type 'bool'&gt;, &lt;type 'bool'&gt;)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">1 &lt; 2</span>
True
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">True or False</span>
True</pre>
<h3><strong><u>Record</u></strong></h3>
<p>Record is a data structure to hold fixed number of elements and it provides method to associate a name with particular element in tuple. It resembles <em>structure</em> in <em>C</em>. Record is not true data type, it is <em>&#8220;tuple in disguise&#8221;</em>(TM).<br />
It&#8217;s syntax is:<br />
<strong> -record(Name, {key1=Default1, key2, &#8230;}).</strong></p>
<p>But in shell we can not use <strong>-record</strong> syntax and we do not yet know about modules where it can be defined, so we&#8217;ll use <strong>&#8216;rd&#8217;</strong> shell command to define record:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">rd(info, {name="ruslan", age=28, height, weight}).</span>
info</pre>
<p>Now let&#8217;s create instance of record:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = #info{}.</span>
#info{name = "ruslan",age = 28,height = undefined,weight = undefined}
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">X.</span>
#info<span style="background-color:#40e0d0;">{</span>name = "ruslan",age = 28,height = undefined,weight = undefined<span style="background-color:#40e0d0;">}</span></pre>
<p>As you see <em>height</em> and <em>weight</em> got <em>&#8220;undefined&#8221;</em> value.</p>
<p>To extract fields of record we use pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">#info{name=Name, age=Age} = X.</span>
#info{name = "ruslan",age = 28,height = undefined,weight = undefined}
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">Name.</span>
"ruslan"
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">Age.</span>
28</pre>
<p>We can also access field of record with <strong>&#8220;dot syntax&#8221;</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">X#info.name.</span>
"ruslan"</pre>
<p>Erlang has more data types like <strong>Pid</strong>, <strong>Port identifier</strong>, <strong>Reference</strong> which will be described later in more advanced topics.There is no direct correspondence to Python&#8217;s built-in data types like <em>dictionaries</em> and <em>sets</em>, but Erlang has modules which provide the same semantics.</p>
<p>That&#8217;s it for today.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Erlang for Python programmers: Intro</title>
		<link>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/</link>
		<comments>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/#comments</comments>
		<pubDate>Sun, 26 Aug 2007 22:51:32 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/</guid>
		<description><![CDATA[I assume you have already installed Erlang on your system and are able to run erlang shell either from command line or from within Emacs (C-c C-z). This is a view of Eshell from my Emacs: Erlang (BEAM) emulator version 5.5.2 [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.5.2 (abort with ^G) 1&#62; Let&#8217;s do a simple thing [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I assume you have already installed <a href="http://www.erlang.org/doc/installation_guide/part_frame.html">Erlang</a> on your system and are able to run erlang shell either from command line or from within <a href="http://www.erlang.org/doc/apps/tools/erlang_mode_chapter.html">Emacs</a> (<em>C-c C-z</em>).</p>
<p>This is a view of Eshell from my Emacs:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Erlang (BEAM) emulator version 5.5.2  [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.5.2  (abort with ^G)
<span style="color:#00ffff;">1&gt; </span></pre>
<p>Let&#8217;s do a simple thing and try to assign a value to a variable in the Eshell. First you should know that variables in Erlang start with uppercase letter or underscore (_), for example:</p>
<ul>
<li>X</li>
<li>Name</li>
<li>Address</li>
<li>_</li>
<li>_NoWarn</li>
</ul>
<p>Ok, let&#8217;s finally assign some value to a variable X:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">2&gt;</span></pre>
<p>So far, so good. Make sure to type final &#8220;.&#8221; at the end of expression when you are done entering code.</p>
<p>Let&#8217;s assign new value to X:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = 5.</span>

=ERROR REPORT==== 27-Aug-2007::00:23:02 ===
Error in process &lt;0.29.0&gt; with exit value: {{badmatch,5},[{erl_eval,expr,3}]}

** exited: {{badmatch,5},[{erl_eval,expr,3}]} **
<span style="color:#00ffff;">3&gt; </span></pre>
<p>Here you need to understand and remember couple of things:</p>
<ol>
<li>Erlang uses <strong>single assignment</strong>, a variable can only be bound once, bar none.</li>
<li>In  expression <strong>X =  5</strong> operator <strong>= </strong>is not an assignment, but <strong>match operator </strong>and variables are bound to values using <strong>pattern matching </strong>mechanism.</li>
</ol>
<p>I think it won&#8217;t be an exaggeration if I say that <em>Pattern Matching</em> permeates Erlang. To understand why we got ERROR REPORT in above example with <strong>{badmatch, 5}</strong> let&#8217;s dive into this pattern matching a bit.</p>
<p>When you use pattern matching&#8217;s = operator left side called <strong>pattern</strong> is matched against right side which is a <strong>term</strong>(piece of data of any Erlang&#8217;s data type: integer, float, list, tuple, etc). If your matching fails you get run-time error, if it succeeds then any unbound variable in lefthand pattern becomes bound.</p>
<p>Returning to our example &#8211; first we had an unbound variable:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X.</span>
** 1: variable 'X' is unbound **
<span style="color:#00ffff;">2&gt; </span></pre>
<p>Then we bound value to variable X with pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">X.</span>
4
<span style="color:#00ffff;">4&gt; </span></pre>
<p>Now as the variable X is bound we can&#8217;t change its value any more (remember <strong>single assignment</strong>?) otherwise we&#8217;ll get <strong>badmatch</strong> error like in foregoing X = 5 (4 does not match 5), but we may use = to <strong>match </strong>our variable:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">5&gt; </span></pre>
<p>Let&#8217;s add a bit of tuples to pattern matching. In Erlang tuple is defined inside {&#8230;}. ie:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">{2, 3}.</span>
{2,3}
<span style="color:#00ffff;">6&gt; </span></pre>
<p>and now pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">{X, Y} = {2, 3}.</span>

=ERROR REPORT==== 27-Aug-2007::01:10:45 ===
Error in process &lt;0.29.0&gt; with exit value: {{badmatch,{2,3}},[{erl_eval,expr,3}]}

** exited: {{badmatch,{2,3}},[{erl_eval,expr,3}]} **
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">{X, Y} = {4, 3}.</span>
{4,3}
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">X.</span>
4
<span style="color:#00ffff;">9&gt; </span><span style="font-weight:bold;">Y.</span>
3
<span style="color:#00ffff;">10&gt; </span></pre>
<p>In first attempt we tried to match X with 2 and the matching failed as the value of X is 4, in a second attempt the matching succeeded and unbound variable Y also got its value (became bound).</p>
<p>This may look to you like <strong>tuple unpacking</strong> in Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y = (4, 3)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y</span>
(4, 3)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y = (5, 3)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y</span>
<span style="background-color:#40e0d0;">(</span>5, 3<span style="background-color:#40e0d0;">)</span></pre>
<p>but it&#8217;s only visual similarity, though i must admit, useful one.</p>
<p>That&#8217;s it for today, later you&#8217;ll see how pattern matching is uber-useful and how it is used in different parts of Erlang&#8217;s constructs.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Erlang man pages in Emacs</title>
		<link>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/</link>
		<comments>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/#comments</comments>
		<pubDate>Sun, 19 Aug 2007 11:56:47 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/</guid>
		<description><![CDATA[Well it&#8217;s actually as simple as running M-x man RET module_name RET in minibuffer. I&#8217;m using Erlang setup from rpm on FC7 and by default man pages are located under /usr/lib/erlang/man/ so to use above command in minibuffer you must make sure you have your erlang&#8217;s man path either in /etc/man.config or you&#8217;ve added it [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Well it&#8217;s actually as simple as running <em>M-x man RET module_name RET</em> in minibuffer.</p>
<p>I&#8217;m using Erlang setup from rpm on FC7 and by default man pages are located under <em>/usr/lib/erlang/man/ </em>so to use above command in minibuffer you must make sure you have your erlang&#8217;s man path either in <em>/etc/man.config</em> or you&#8217;ve added it into <em>MANPATH </em>with something like<em> export MANPATH=$MANPATH:/usr/lib/erlang/man </em>in your <em>.bash_profile </em>in case your Erlang man pages are not in location accessible by default.</p>
<p>You may also pass man path in minibuffer manually without changing /etc/man.config or MANPATH. In my case to view man page for <em>&#8216;lists&#8217; </em>module it will look like:</p>
<p><em>M-x man RET -M /</em><em>usr/lib/erlang/man lists </em><em>RET</em></p>
<p>I&#8217;ve customized some stuff for myself in emacs and made binding to F6 key so that whenever i set cursor on module name in my erlang buffer and press F6 i get man page in another window poped up describing module at point. So if you have in your code or in any buffer, for example:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">(em@localhost)2&gt; </span>lists:reverse([1, 2, 3]).</pre>
<p>you need to move cursor to <strong>lists</strong> and press F6. Quite handy if you consult man pages often, which is the case for me now as i learn Erlang.</p>
<p>Here is the corresponding elisp helper function and key binding from my dot emacs:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(<span style="color:#00ffff;">defun</span> <span style="color:#87cefa;">get-erl-man</span> ()
  (interactive)
  (<span style="color:#00ffff;">let*</span> ((man-path <span style="color:#ffa07a;">"/usr/lib/erlang/man"</span>)
         (man-args (format <span style="color:#ffa07a;">"-M %s %s"</span> man-path (current-word))))
    (man man-args)))

(global-set-key [(f6)] (<span style="color:#00ffff;">lambda</span> () (interactive) (get-erl-man)))</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Htmlize your Erlang code buffer</title>
		<link>http://ruslanspivak.com/2007/08/18/htmlize-your-erlang-code-buffer/</link>
		<comments>http://ruslanspivak.com/2007/08/18/htmlize-your-erlang-code-buffer/#comments</comments>
		<pubDate>Sat, 18 Aug 2007 21:37:06 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/18/htmlize-your-erlang-code-buffer/</guid>
		<description><![CDATA[Recently I&#8217;ve begun to make blog posts and now want to have highlighting of Erlang&#8217;s code(actually any code , be it Python, Lisp, etc) in my posts. I&#8217;m using The One True Editor and it goes without saying that i want to convert my erlang code into html from within emacs to have corresponding syntax [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I&#8217;ve begun to make blog posts and now want to have highlighting of Erlang&#8217;s code(actually any code , be it Python, Lisp, etc) in my posts. I&#8217;m using <a href="http://www.gnu.org/software/emacs/">The One True Editor</a> and it goes without saying that i want to convert my erlang code into html from within emacs to have corresponding syntax coloring. <a href="http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el">Htmlize package</a> to the rescue!</p>
<p>After you downloaded package and put</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(add-to-list 'load-path <span style="color:#ffa07a;">"path_to_your_htmlize.el"</span>)
(<span style="color:#00ffff;">require</span> '<span style="color:#7fffd4;">htmlize</span>)</pre>
<p>into your dot emacs &#8211; you are ready to use it.</p>
<p><em>M-x htmlize-buffer<strong> </strong></em>or <em>M-x htmlize-region</em> will convert whole buffer or selected region with associated decorations into HTML( See <em>C-h a htmlize RET</em> for more functions). By default <a href="http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el">htmlize</a> will make HTML output in <em>css</em> mode which is not very suitable for inserting into blog post as output includes also style sheets. Excerpt from htmlize documentation:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#ff4500;">;; </span><span style="color:#ff4500;">htmlize supports three types of HTML output, selected by setting
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">`</span><span style="color:#7fffd4;">htmlize-output-type</span><span style="color:#ff4500;">': `</span><span style="color:#7fffd4;">css</span><span style="color:#ff4500;">', `</span><span style="color:#7fffd4;">inline-css</span><span style="color:#ff4500;">', and `</span><span style="color:#7fffd4;">font</span><span style="color:#ff4500;">'.  In `</span><span style="color:#7fffd4;">css</span><span style="color:#ff4500;">'
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">mode, htmlize uses cascading style sheets to specify colors; it
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">generates classes that correspond to Emacs faces and uses &lt;span
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">class=FACE&gt;...&lt;/span&gt; to color parts of text.  In this mode, the
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">produced HTML is valid under the 4.01 strict DTD, as confirmed by
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">the W3C validator.  `</span><span style="color:#7fffd4;">inline-css</span><span style="color:#ff4500;">' is like `</span><span style="color:#7fffd4;">css</span><span style="color:#ff4500;">', except the CSS is
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">put directly in the STYLE attribute of the SPAN element, making it
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">possible to paste the generated HTML to other documents.  In `</span><span style="color:#7fffd4;">font</span><span style="color:#ff4500;">'
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">mode, htmlize uses &lt;font color="..."&gt;...&lt;/font&gt; to colorize HTML,
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">which is not standard-compliant, but works better in older
</span><span style="color:#ff4500;">;; </span><span style="color:#ff4500;">browsers.  `</span><span style="color:#7fffd4;">css</span><span style="color:#ff4500;">' mode is the default.
</span></pre>
<p><em>inline-css</em> is the type of output i want. This can be achieved by customizing <em>htmlize-output-type</em> variable with <em>M-x customize htmlize RET </em>or directly modifying dot emacs. Converting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(add-to-list 'load-path <span style="color:#ffa07a;">"path_to_your_htmlize.el"</span>)
(<span style="color:#00ffff;">require</span> '<span style="color:#7fffd4;">htmlize</span>)</pre>
<p>with htmlize-region and then applying <em>nxml-mode</em> to produced result gives:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ad00;">&lt;!</span><span style="color:#acacfc;">DOCTYPE</span> html <span style="color:#acacfc;">PUBLIC</span> <span style="color:#00ad00;">"</span><span style="color:#70f170;">-//W3C//DTD HTML 4.01//EN</span><span style="color:#00ad00;">"</span><span style="text-decoration:underline;">&gt;</span>
<span style="color:#00ad00;">&lt;!--</span><span style="font-style:italic;"> Created by htmlize-1.34 in inline-css mode. </span><span style="color:#00ad00;">--&gt;</span>
<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">html</span><span style="color:#00ad00;text-decoration:underline;">&gt;</span>
  <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">head</span><span style="color:#00ad00;">&gt;</span>
    <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">title</span><span style="color:#00ad00;">&gt;</span>.emacs<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">title</span><span style="color:#00ad00;">&gt;</span>
  <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">head</span><span style="color:#00ad00;">&gt;</span>
  <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">body</span> <span style="color:#acacfc;">style</span>=<span style="color:#00ad00;">"</span><span style="color:#70f170;">color: #ffffff; background-color: #000000;</span><span style="color:#00ad00;">"</span><span style="color:#00ad00;">&gt;</span>
    <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">pre</span><span style="color:#00ad00;">&gt;</span>
(add-to-list 'load-path <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">span</span> <span style="color:#acacfc;">style</span>=<span style="color:#00ad00;">"</span><span style="color:#70f170;">color: #ffa07a;</span><span style="color:#00ad00;">"</span><span style="color:#00ad00;">&gt;</span>"path_to_your_htmlize.el"<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">span</span><span style="color:#00ad00;">&gt;</span>)
(<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">span</span> <span style="color:#acacfc;">style</span>=<span style="color:#00ad00;">"</span><span style="color:#70f170;">color: #00ffff;</span><span style="color:#00ad00;">"</span><span style="color:#00ad00;">&gt;</span>require<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">span</span><span style="color:#00ad00;">&gt;</span> '<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">span</span> <span style="color:#acacfc;">style</span>=<span style="color:#00ad00;">"</span><span style="color:#70f170;">color: #7fffd4;</span><span style="color:#00ad00;">"</span><span style="color:#00ad00;">&gt;</span>htmlize<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">span</span><span style="color:#00ad00;">&gt;</span>)
<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">pre</span><span style="color:#00ad00;">&gt;</span>
  <span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">body</span><span style="color:#00ad00;">&gt;</span>
<span style="color:#00ad00;">&lt;</span><span style="color:#acacfc;">/</span><span style="color:#acacfc;">html</span><span style="color:#00ad00;">&gt;</span></pre>
<p>As you see I need to cut contents between <em>&lt;pre&gt;</em> <em>&lt;/pre&gt;</em> including<br />
<em>&lt;pre&gt;</em> tags itself to insert that then directly into blog post. After that i need manually copy/paste styles from <em>&lt;body&gt;</em>  tag into <em>&lt;pre&gt;</em> tag and also add font-size: 8pt to meet my taste. Being lazy i&#8217;ve implemented function  <em>my-htmlize-region</em> in elisp to make that job for me every time i press F5 key:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(<span style="color:#00ffff;">defun</span> <span style="color:#87cefa;">my-htmlize-region</span> (beg end)
  <span style="color:#ffa07a;">"Htmlize region and put into &lt;pre&gt; tag style that is left in &lt;body&gt; tag
plus add font-size: 8pt"</span>
  (interactive <span style="color:#ffa07a;">"r"</span>)
  (<span style="color:#00ffff;">let*</span> ((buffer-faces (htmlize-faces-in-buffer))
         (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
         (pre-tag (format
                   <span style="color:#ffa07a;">"&lt;pre style="%s font-size: 8pt"&gt;"</span>
                   (mapconcat #'identity (htmlize-css-specs
                                          (gethash 'default face-map)) <span style="color:#ffa07a;">" "</span>)))
         (htmlized-reg (htmlize-region-for-paste beg end)))
    (switch-to-buffer-other-window <span style="color:#ffa07a;">"*htmlized output*"</span>)
    <span style="color:#ff4500;">; </span><span style="color:#ff4500;">clear buffer
</span>    (kill-region (point-min) (point-max))
    <span style="color:#ff4500;">; </span><span style="color:#ff4500;">set mode to have syntax highlighting
</span>    (nxml-mode)
    (<span style="color:#00ffff;">save-excursion</span>
      (insert htmlized-reg))
    (<span style="color:#00ffff;">while</span> (re-search-forward <span style="color:#ffa07a;">"&lt;pre&gt;"</span> nil t)
      (replace-match pre-tag nil nil))
    (goto-char (point-min))))

(global-set-key [(f5)] (<span style="color:#00ffff;">lambda</span> (beg end)
                         (interactive <span style="color:#ffa07a;">"r"</span>) (my-htmlize-region beg end)))
</pre>
<p>So now selecting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(add-to-list 'load-path <span style="color:#ffa07a;">"path_to_your_htmlize.el"</span>)
(<span style="color:#00ffff;">require</span> '<span style="color:#7fffd4;">htmlize</span>)</pre>
<p>and pressing F5 i get this in another buffer:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">pre</span> <span style="color:#ACACFC;">style</span>=<span style="color:#00AD00;">"</span><span style="color:#70F170;">color: #ffffff; background-color: #000000; font-size: 8pt</span><span style="color:#00AD00;">"</span><span style="color:#00AD00;">&gt;</span>
(add-to-list 'load-path <span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">span</span> <span style="color:#ACACFC;">style</span>=<span style="color:#00AD00;">"</span><span style="color:#70F170;">color: #ffa07a;</span><span style="color:#00AD00;">"</span><span style="color:#00AD00;">&gt;</span>"path_to_your_htmlize.el"<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">/</span><span style="color:#ACACFC;">span</span><span style="color:#00AD00;">&gt;</span>)
(<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">span</span> <span style="color:#ACACFC;">style</span>=<span style="color:#00AD00;">"</span><span style="color:#70F170;">color: #00ffff;</span><span style="color:#00AD00;">"</span><span style="color:#00AD00;">&gt;</span>require<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">/</span><span style="color:#ACACFC;">span</span><span style="color:#00AD00;">&gt;</span> '<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">span</span> <span style="color:#ACACFC;">style</span>=<span style="color:#00AD00;">"</span><span style="color:#70F170;">color: #7fffd4;</span><span style="color:#00AD00;">"</span><span style="color:#00AD00;">&gt;</span>htmlize<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">/</span><span style="color:#ACACFC;">span</span><span style="color:#00AD00;">&gt;</span>)
<span style="color:#00AD00;">&lt;</span><span style="color:#ACACFC;">/</span><span style="color:#ACACFC;">pre</span><span style="color:#00AD00;">&gt;</span></pre>
<p>As you see it&#8217;s just what i want:<br />
<em>&lt;pre&gt;</em> tags with content and <em>&lt;pre&gt;</em> tag contains style from above mentioned  <em>&lt;body&gt;</em> tag plus <em>font-size</em> is added too.</p>
<p>Factorial in Erlang with syntax coloring as i have it in my Emacs:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(factorial).
<span style="color:#87cefa;">-export</span>([factorial/1, factorial_rec/1]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">tail recursion
</span><span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">Num</span>) -&gt;
    factorial(<span style="color:#eedd82;">Num</span>, 1).

<span style="color:#87cefa;">factorial</span>(1, <span style="color:#eedd82;">Acc</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">Acc</span>;
<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">Num</span>, <span style="color:#eedd82;">Acc</span>) -&gt;
    factorial(<span style="color:#eedd82;">Num</span>-1, <span style="color:#eedd82;">Num</span> * <span style="color:#eedd82;">Acc</span>).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">recursion
</span><span style="color:#87cefa;">factorial_rec</span>(1) -&gt;<span style="color:#87cefa;"> </span>1;
<span style="color:#87cefa;">factorial_rec</span>(<span style="color:#eedd82;">Num</span>) -&gt;
    <span style="color:#eedd82;">Num</span> * factorial_rec(<span style="color:#eedd82;">Num</span>-1).
</pre>
<p>This is a joy of using Emacs.</p>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/18/htmlize-your-erlang-code-buffer/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>More about binary search in Erlang</title>
		<link>http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/</link>
		<comments>http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/#comments</comments>
		<pubDate>Thu, 16 Aug 2007 22:20:51 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/</guid>
		<description><![CDATA[In my previous post My Erlang binary search I&#8217;ve implemented binary search in Python and Erlang as small exercise for myself after reading Half-baked Ideas blog post. Good article pointing to specifics of implementation of that algorithm in Erlang was posted on Erlane&#8217;s blog which is in a nutshell: binary search in Erlang implemented on [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In my previous post <a href="http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/">My Erlang binary search</a> I&#8217;ve implemented binary search in Python and Erlang as small exercise for myself after reading <a href="http://erl.nfshost.com/wordpress/2007/08/11/binary-search/">Half-baked Ideas blog post</a>. Good article pointing to specifics of implementation of that algorithm in Erlang was posted on <a href="http://erlane-project.blogspot.com/2007/08/binary-search-ultimate-test.html">Erlane&#8217;s blog</a> which is in a nutshell: binary search in Erlang implemented on list data structure is less efficient than linear search.</p>
<p>So to grasp why linear search which is O(N) is faster in Erlang then binary search which is in theory O(logN) go and read that <a href="http://erlane-project.blogspot.com/2007/08/binary-search-ultimate-test.html">article.</a><br />
In Python list data structure (I&#8217;m talking here about CPython) is implemented as mutable and extensible vector of references to objects(we might say array of pointers), here is the excerpt from listobject.h:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">typedef</span> <span style="color:#00ffff;">struct</span> {
    PyObject_VAR_HEAD
    <span style="color:#ff4500;">/* </span><span style="color:#ff4500;">Vector of pointers to list elements.  list[0] is ob_item[0], etc. </span><span style="color:#ff4500;">*/</span>
    <span style="color:#98fb98;">PyObject</span> **<span style="color:#eedd82;">ob_item</span>;

    <span style="color:#ff4500;">/* </span><span style="color:#ff4500;">ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 &lt;= ob_size &lt;= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     </span><span style="color:#ff4500;">*/</span>
    <span style="color:#98fb98;">Py_ssize_t</span> <span style="color:#eedd82;">allocated</span>;
} <span style="color:#eedd82;">PyListObject</span>;</pre>
<p>So <a href="http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/">Python version</a> works as expected regarding efficiency.  While my goal  of implementing  binary search algorithm in Erlang was learning Erlang and not particulary developing optimized version of that algorithm or using another one it&#8217;s always good to pick <a href="http://erlane-project.blogspot.com/2007/08/binary-search-ultimate-test.html">new tricks of the trade</a> along the way and for me the issue with my implementation of <a href="http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/">binary search in Erlang</a> just boils down to: your experience and know your tools (language, os, editor(emacs <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , etc )</p>
<p>As <em>Aldous Huxly</em> said: <em><span class="body">&#8220;Experience is not what happens to you; it&#8217;s what you do with what happens to you.&#8221;. </span></em><span class="body">So make errors (not many <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  in your programs, fix them and gain new experience with your new language. </span></p>
<p><span class="body"><a href="http://erlane-project.blogspot.com/2007/08/from-java-to-erlang-or-how-to-structure.html">Another post by Erlane team</a></span>  is good reading describing paradigm shifts when you are newbie and are on your own way to Erlang/OTP wizardry.</p>
<pre></pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Erlang binary search</title>
		<link>http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/</link>
		<comments>http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/#comments</comments>
		<pubDate>Wed, 15 Aug 2007 00:34:10 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.wordpress.com/2007/08/15/my-erlang-binary-search/</guid>
		<description><![CDATA[I was lurking and watching Erlang quite some time during this year and finally decided give it a shot after Programming Erlang was released. I ordered book in pdf format to rest assured i&#8217;ll get it in fastest possible way. After i read book a bit i was hooked Today i came across binary search [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I was lurking and watching Erlang quite some time during this year and finally decided give it a shot after <a href="http://www.pragmaticprogrammer.com/titles/jaerlang/index.html">Programming Erlang</a> was released. I ordered book in pdf format to rest assured i&#8217;ll get it in fastest possible way. After i read book a bit i was hooked</p>
<p>Today i came across <a href="http://erl.nfshost.com/wordpress/2007/08/11/binary-search/">binary search in Erlang</a> blog post and decided to implement quickly binary search myself. My first attempt was to do it in python as it&#8217;s my daily job&#8217;s programming language and it turned this way (no check for edge cases like empty sequence):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#00ffff;">if</span> key == seq[mid]:
        <span style="color:#00ffff;">return</span> mid
    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)
</pre>
<p>After i looked at code a bit i was surprised i wrote it recursively, earlier i would do it like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key):
    start = 0
    end = len(seq) - 1

    <span style="color:#00ffff;">while</span> <span style="color:#00ffff;">True</span>:
        <span style="color:#00ffff;">if</span> end &lt; start:
            <span style="color:#00ffff;">return</span> -1
        mid = (start + end) / 2
        <span style="color:#00ffff;">if</span> key == seq[mid]:
            <span style="color:#00ffff;">return</span> mid
        <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
            end = mid - 1
        <span style="color:#00ffff;">else</span>:
            start = mid + 1
</pre>
<p>Erlang obviously bends my mind <img src='http://ruslanspivak.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>And my version in Erlang which was just exercise for myself and mainly looks like in <a href="http://erl.nfshost.com/wordpress/2007/08/11/binary-search/">original blog post</a>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(search).
<span style="color:#87cefa;">-export</span>([binsearch/2]).
<span style="color:#87cefa;">-import</span>(lists, [nth/2]).
<span style="color:#87cefa;">-include_lib</span>(<span style="color:#ffa07a;">"eunit/include/eunit.hrl"</span>).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">Key</span>) -&gt;
    binsearch(<span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">Key</span>, 1, <span style="color:#00ffff;">length</span>(<span style="color:#eedd82;">List</span>)).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">UpperBound</span>) -&gt;
    <span style="color:#00ffff;">if</span>
        <span style="color:#eedd82;">UpperBound</span> &lt; <span style="color:#eedd82;">LowerBound</span> -&gt;<span style="color:#87cefa;"> </span>-1;
        true -&gt;
            <span style="color:#eedd82;">Mid</span> = (<span style="color:#eedd82;">LowerBound</span> + <span style="color:#eedd82;">UpperBound</span>) div 2,
            <span style="color:#eedd82;">Item</span> = nth(<span style="color:#eedd82;">Mid</span>, <span style="color:#eedd82;">List</span>),
            <span style="color:#00ffff;">if</span>
                <span style="color:#eedd82;">Key</span> &lt; <span style="color:#eedd82;">Item</span> -&gt;
                    binsearch(<span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">Mid</span>-1);
                <span style="color:#eedd82;">Key</span> &gt; <span style="color:#eedd82;">Item</span> -&gt;
                    binsearch(<span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">Mid</span>+1, <span style="color:#eedd82;">UpperBound</span>);
                true -&gt;
                    <span style="color:#eedd82;">Mid</span>
            <span style="color:#00ffff;">end</span>
    <span style="color:#00ffff;">end</span>.

<span style="color:#87cefa;">setup_test_</span>() -&gt;
    {setup,
     <span style="color:#00ffff;">fun</span>() -&gt;<span style="color:#87cefa;"> </span>[7, 11, 14, 40, 50] <span style="color:#00ffff;">end</span>,
     <span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">L</span>) -&gt;
             [?<span style="color:#7fffd4;">_assertMatch</span>(3, binsearch(<span style="color:#eedd82;">L</span>, 14)),
              ?<span style="color:#7fffd4;">_assertMatch</span>(-1, binsearch(<span style="color:#eedd82;">L</span>, 70))]
     <span style="color:#00ffff;">end</span>
    }.</pre>
<p>Running unit tests:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">(em@localhost)1&gt; </span><span style="font-weight:bold;">search:test().</span>
  All 2 tests successful.
ok</pre>
]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced

Served from: ruslanspivak.com @ 2013-05-23 08:23:16 -->