<?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>Bradley Froehle</title>
	<atom:link href="http://bfroehle.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://bfroehle.com</link>
	<description>PhD Candidate, UC Berkeley</description>
	<lastBuildDate>Sun, 28 Apr 2013 22:35:28 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Story of a bug in Ubuntu</title>
		<link>http://bfroehle.com/2013/04/story-of-a-bug-in-ubuntu/</link>
		<comments>http://bfroehle.com/2013/04/story-of-a-bug-in-ubuntu/#comments</comments>
		<pubDate>Sat, 27 Apr 2013 16:57:06 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=201</guid>
		<description><![CDATA[I just came across this lovely writeup of a particularly annoying bug I helped squash in Ubuntu 12.04. The bug caused applications like evince and eog to load incredibly slowly, taking almost a full minute to open a PDF. It turned out to have a relatively banal cause — an initialization procedure didn&#8217;t immediately signal [...]]]></description>
				<content:encoded><![CDATA[<p>I just came across this <a href="http://www.linux.it/~ema/2012/09/02/story-of-a-bug-in-ubuntu/">lovely writeup</a> of a <a href="https://bugs.launchpad.net/ubuntu/precise/+source/geis/+bug/997630">particularly annoying</a> bug <a href="https://bugs.launchpad.net/ubuntu/precise/+source/geis/+bug/997630/comments/19">I helped squash</a> in Ubuntu 12.04. The bug caused applications like evince and eog to load <em>incredibly</em> slowly, taking almost a full minute to open a PDF. It turned out to have a relatively banal cause — an initialization procedure didn&#8217;t immediately signal its failure and instead the library would wait a full 5 seconds for the initialization to finish before giving up.</p>
<p>Thanks for the writeup, <a href="http://www.linux.it/~ema/">Emanuele Rocca</a>. I think this shows the power of open source software. An obscure bug affecting only a handful of people can still get fixed, even without much help from the original developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2013/04/story-of-a-bug-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting Markdown to reStructuredText</title>
		<link>http://bfroehle.com/2013/04/converting-md-to-rst/</link>
		<comments>http://bfroehle.com/2013/04/converting-md-to-rst/#comments</comments>
		<pubDate>Sat, 27 Apr 2013 02:22:02 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=198</guid>
		<description><![CDATA[A quick one-liner, which I recently used to convert a Markdown formatted README to reStructuredText, suitable for posting to PyPI: pandoc --from=markdown --to=rst --output=README.rst README.md]]></description>
				<content:encoded><![CDATA[<p>A quick <a href="http://stackoverflow.com/questions/10718767/have-the-same-readme-both-in-markdown-and-restructuredtext">one-liner</a>, which I recently used to convert a <a href="http://daringfireball.net/projects/markdown/">Markdown</a> formatted README to <a href="http://docutils.sourceforge.net/rst.html">reStructuredText</a>, suitable for posting to <a href="https://pypi.python.org/">PyPI</a>:</p>
<pre>pandoc --from=markdown --to=rst --output=README.rst README.md</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2013/04/converting-md-to-rst/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing screen resolution in RealVNC</title>
		<link>http://bfroehle.com/2013/04/changing-screen-resolution-in-realvnc/</link>
		<comments>http://bfroehle.com/2013/04/changing-screen-resolution-in-realvnc/#comments</comments>
		<pubDate>Wed, 24 Apr 2013 19:56:46 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[realvnc]]></category>
		<category><![CDATA[resolution]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=184</guid>
		<description><![CDATA[These days I do most of my work in a RealVNC session on a remote Ubuntu workstation. This provides me with a consistent environment, regardless of whether I&#8217;m at work, a coffee shop, or at home. One major annoyance with the default configuration is that the screen resolution cannot be changed after the virtual desktop [...]]]></description>
				<content:encoded><![CDATA[<p>These days I do most of my work in a RealVNC session on a remote Ubuntu workstation. This provides me with a consistent environment, regardless of whether I&#8217;m at work, a coffee shop, or at home. One major annoyance with the default configuration is that the screen resolution cannot be changed after the virtual desktop is started.</p>
<p>The key to getting around this problem is to provide RealVNC with a <a href="http://stackoverflow.com/questions/15816/changing-the-resolution-of-a-vnc-session-in-linux">complete list of screen resolutions</a> you would like to have available when starting RealVNC. For example, my <code>.vnc/config</code> file contains</p>
<pre># Additional Resolutions
-randr 800x600,1024x768,1280x800,1280x960,1280x1024,1344x756,1680x1050,1920x1080,1920x1200,3360x1050,1024x700,1200x740,1600x1000,3200x1000,1680x1020,768x1024</pre>
<p>After restarting RealVNC, you can easily change the screen resolution using the <code>xrandr</code> command. You can list screen resolutions by running <code>xrandr</code>:</p>
<pre>$ xrandr
 SZ:    Pixels          Physical       Refresh
 0    800 x 600    ( 203mm x 152mm )   0
 1   1024 x 768    ( 260mm x 195mm )   0
 2   1280 x 800    ( 325mm x 203mm )   0
 3   1280 x 960    ( 325mm x 244mm )   0
 4   1280 x 1024   ( 325mm x 260mm )   0
 5   1344 x 756    ( 341mm x 192mm )   0
 6   1680 x 1050   ( 427mm x 267mm )   0
*7   1920 x 1080   ( 488mm x 274mm )  *0
 8   1920 x 1200   ( 488mm x 305mm )   0
 9   3360 x 1050   ( 853mm x 267mm )   0
 10  1024 x 700    ( 260mm x 178mm )   0
 11  1200 x 740    ( 305mm x 188mm )   0
 12  1600 x 1000   ( 406mm x 254mm )   0
 13  3200 x 1000   ( 813mm x 254mm )   0
 14  1680 x 1020   ( 427mm x 259mm )   0
 15   768 x 1024   ( 195mm x 260mm )   0
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none
</pre>
<p>To switch to a different resolution just run <code>xrandr -s &lt;resolution&gt;</code>, where the resolution is either the item number, like <code>12</code>, or resolution, like <code>1600x1000</code>.</p>
<p>Afterwards, especially in recent versions of Ubuntu (12.04 and later), you may find that the background Nautilus desktop <a href="https://bugs.launchpad.net/ubuntu/+source/unity-2d/+bug/992791">didn&#8217;t get the memo</a> that the screen resolution was changed. To work around this, it&#8217;s often easiest to quit and restart Nautilus:</p>
<pre>
$ nautilus -q; sleep 1; nautilus -n &gt; /dev/null 2&gt;&amp;1 &amp; disown %
</pre>
<p>If you find yourself doing this a lot, as I did, you may want to consider writing a little script to automate the task. I named my script <code>xres</code> and have posted the <a href="https://gist.github.com/bfroehle/5455103">source as a gist</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2013/04/changing-screen-resolution-in-realvnc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RealVNC on Ubuntu 13.04 Raring Ringtail</title>
		<link>http://bfroehle.com/2013/04/realvnc-on-ubuntu-13-04-raring-ringtail/</link>
		<comments>http://bfroehle.com/2013/04/realvnc-on-ubuntu-13-04-raring-ringtail/#comments</comments>
		<pubDate>Mon, 08 Apr 2013 02:01:28 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[13.04]]></category>
		<category><![CDATA[raring]]></category>
		<category><![CDATA[realvnc]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=159</guid>
		<description><![CDATA[I just spent a few hours getting the free version RealVNC working in Ubuntu 13.04 Raring Ringtail (Beta 2). Here are the steps that I needed to take: Disable the X Server Render extension. Copy /etc/vnc/config to /etc/vnc/config.custom and add -extension RENDER Create a custom xstartup file. Copy /etc/vnc/xstartup to /etc/vnc/xstartup.custom and make the following [...]]]></description>
				<content:encoded><![CDATA[<p>I just spent a few hours getting the free version <a href="http://www.realvnc.com/">RealVNC</a> working in <a href="https://wiki.ubuntu.com/RaringRingtail/TechnicalOverview">Ubuntu 13.04 Raring Ringtail (Beta 2)</a>. Here are the steps that I needed to take:</p>
<ol>
<li><a href="http://kb.realvnc.com/questions/235/VNC+Server+in+Virtual+Mode+does+not+work+out-of-the-box+under+Ubuntu+12.10">Disable the X Server Render extension</a>.  Copy <code>/etc/vnc/config</code> to <code>/etc/vnc/config.custom</code> and add
<pre>-extension RENDER</pre>
</li>
<li>Create a custom <code>xstartup</code> file. Copy <code>/etc/vnc/xstartup</code> to <code>/etc/vnc/xstartup.custom</code> and make the following changes:
<ul>
<li>Remove the line
<pre>[ -x /etc/vnc/xstartup.custom ] &amp;&amp; exec /etc/vnc/xstartup.custom</pre>
</li>
<li>Add <code>"gnome-fallback"</code> to the list of valid sessions by replacing
<pre>for SESSION in &quot;ubuntu-2d&quot; &quot;2d-gnome&quot;; do</pre>
<p>with</p>
<pre>for SESSION in &quot;ubuntu-2d&quot; &quot;2d-gnome&quot; &quot;gnome-fallback&quot;; do</pre>
</li>
<li>Add to the top of the file:
<pre>unset XDG_RUNTIME_DIR</pre>
</li>
</ul>
</li>
</ol>
<p>I found it necessary to unset <code>XDG_RUNTIME_DIR</code> because I could not figure out a way to guarantee the directory it points to actually exists.  When the directory did not exist I experienced 100% CPU utilization bugs in <code>indicator-datetime-service</code> and <code>gnome-settings-daemon</code>.</p>
<p>Briefly, the <code>XDG_RUNTIME_DIR</code> variable and directory that it points to are managed by a PAM module in <a href="http://packages.ubuntu.com/raring/libpam-xdg-support">libpam-xdg-support</a>.  When <code>jsmith</code> logs in over SSH, the PAM module creates a directory <code>/run/users/jsmith</code> and increments a session count stored in <code>/run/users/.jsmith.lock</code>.  When <code>jsmith</code> later logs out, the session count is decremented.  When the session count reaches zero the directory is deleted.  Since RealVNC does not appear to use the PAM session machinery, there is no way to guarantee that the session count remains positive if only a VNC session is active.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2013/04/realvnc-on-ubuntu-13-04-raring-ringtail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A data descriptor for __doc__</title>
		<link>http://bfroehle.com/2012/11/property-for-doc-attribute/</link>
		<comments>http://bfroehle.com/2012/11/property-for-doc-attribute/#comments</comments>
		<pubDate>Thu, 08 Nov 2012 19:57:27 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[descriptor]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[__doc__]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=137</guid>
		<description><![CDATA[In Python, suppose you want to implement a class which has a dynamically generated docstring. The easiest way to do this would be to use the @property decorator for the __doc__ attribute. (You also need your class to be a &#8220;new-style&#8221; class, i.e., inherit from object). For example: class A(object): &#34;&#34;&#34;Docstring for class.&#34;&#34;&#34; def __init__(self, [...]]]></description>
				<content:encoded><![CDATA[<p>In Python, suppose you want to implement a class which has a dynamically generated docstring.  The easiest way to do this would be to use the <code>@property</code> decorator for the <code>__doc__</code> attribute.  (You also need your class to be a &#8220;new-style&#8221; class, i.e., inherit from <code>object</code>).  For example:</p>
<pre>
class A(object):
    &quot;&quot;&quot;Docstring for class.&quot;&quot;&quot;
    def __init__(self, x):
        self.x = x
    @property
    def __doc__(self):
        return &quot;My value of x is %s.&quot; % self.x
</pre>
<p>This gives the desired result:</p>
<pre>
&gt;&gt;&gt; a = A(10)
&gt;&gt;&gt; print(a.__doc__)
My value of x is 10.
</pre>
<p>But hides the docstring for the class <code>A</code>:</p>
<pre>
&gt;&gt;&gt; A.__doc__
&lt;property at 0x2083db8&gt;
</pre>
<p>Read on to see how we can fix this.<span id="more-137"></span></p>
<p>To fix this, we can implement a custom class implementing the <a href="http://docs.python.org/2/howto/descriptor.html#descriptor-protocol">descriptor protocol</a>.  The default <a href="http://docs.python.org/2/howto/descriptor.html#properties">property descriptor</a> behaves as:</p>
<pre>
class Property(object):
    ...
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError, &quot;unreadable attribute&quot;
        return self.fget(obj)
</pre>
<p>Here we see that if `obj is None`, that is, if we attempt to access `__doc__` on the class itself the property descriptor returns itself. To solve our problem we can instead return a string, perhaps something like:</p>
<pre>
class DocstringProperty(object):
    def __init__(self, fget, class_doc):
        self.fget = fget
        self.class_doc = class_doc
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self.class_doc
        else:
            return self.fget(obj)
</pre>
<p>I&#8217;ve provided a fuller implementation and a function decorator in <a href="https://gist.github.com/4041015">gist #4041015</a>.</p>
<p>For example:</p>
<pre>
&gt;&gt;&gt; class A(object):
...     &quot;&quot;&quot;Main docstring&quot;&quot;&quot;
...     def __init__(self, x):
...         self.x = x
...     @docstring_property(__doc__)
...     def __doc__(self):
...         return &quot;My value of x is %s.&quot; % self.x
&gt;&gt;&gt; A.__doc__
&#039;Main docstring&#039;
&gt;&gt;&gt; a = A(10)
&gt;&gt;&gt; print(a.__doc__)
My value of x is 10.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2012/11/property-for-doc-attribute/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Instance Methods &amp; Cython Functions</title>
		<link>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/</link>
		<comments>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 03:35:19 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Cython]]></category>
		<category><![CDATA[instancemethod]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=121</guid>
		<description><![CDATA[One of the great features of Python is the ability to define methods outside of classes. For example, we can define a function which increments the attribute x and add it to a Point class: def incx(self): self.x += 1 class Point(object): def __init__(self, x): self.x = x incx = incx We can then create [...]]]></description>
				<content:encoded><![CDATA[<p>One of the great features of <a href="http://python.org">Python</a> is the ability to define methods outside of classes. For example, we can define a function which increments the attribute <code>x</code> and add it to a <code>Point</code> class:</p>
<pre>def incx(self):
    self.x += 1

class Point(object):
    def __init__(self, x): self.x = x
    incx = incx</pre>
<p>We can then create a point at the origin and increment <code>x</code>:</p>
<pre>In [2]: p = Point(0)

In [3]: p.incx()

In [4]: print p.x
1</pre>
<p>The same code which defines <code>Point</code> continues to work if we move <code>incx</code> to another file, say <code>demo.py</code>, and import it using <code>from demo import incx</code>.</p>
<p>But if we were to put <code>incx</code> in <a href="https://raw.github.com/gist/1686654/demo.pyx"><code>demo.pyx</code></a> and compile it (using <code>python <a href="https://raw.github.com/gist/1686654/setup.py">setup.py</a> build_ext --inplace</code>), we get a strange error when running our <a href="https://raw.github.com/gist/1686654/bad.py">simple test</a>:</p>
<pre>$ python bad.py
Traceback (most recent call last):
  File &quot;bad.py&quot;, line 10, in &lt;module&gt;
    p.incx()
TypeError: incx() takes exactly one argument (0 given)
</pre>
<p>Read on to learn about instance methods and see how I fixed this.<br />
<span id="more-121"></span></p>
<p>My first thought was to write a simple wrapper function, using <a href="http://docs.python.org/library/functools.html#functools.wraps">functools.wraps</a> to preserve the docstring and name. This proved to be a clumsy solution.</p>
<p>A better approach turned out to be to use <a href="http://docs.python.org/library/types.html#types.MethodType"><code>types.MethodType</code></a> to convert our built-in function into an (unbound) instance method.  The docstring for <code>MethodType</code> is pretty short:</p>
<blockquote><p>instancemethod(function, instance, class)</p></blockquote>
<p>The first and third arguments are obvious.  For the second argument we&#8217;ll use <code>None</code> since we have no instance of the class yet, making this an <em>unbound</em> instance method.</p>
<p>So to fix our simple example, we need only replace the <code>incx = incx</code> line in the class definition with a short snippet after the class is defined:</p>
<pre>from types import MethodType
Point.incx = MethodType(incx, None, Point)
</pre>
<p>We can give this <a href="https://raw.github.com/gist/1686654/good.py">new version</a> a try and see that it works:<br />
<code>$ python good.py<br />
1<br />
</code></p>
<p><em>As always, the entire example is <a href="https://gist.github.com/1686654">available as a Gist</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>True division in IPython</title>
		<link>http://bfroehle.com/2012/01/true-division-in-ipython/</link>
		<comments>http://bfroehle.com/2012/01/true-division-in-ipython/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 16:54:01 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[division]]></category>
		<category><![CDATA[IPython]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=104</guid>
		<description><![CDATA[As Python transitions from version 2 to version 3, the meaning of the division operator on integers is changing: Python 2.x Python 3.x $ python2.7 Python 2.7.2+ (...) ... &#62;&#62;&#62; 1/2 0 $ python3.2 Python 3.2.2 (...) ... &#62;&#62;&#62; 1/2 0.5 In this post, we&#8217;ll discuss how to configure the behavior of the division operator [...]]]></description>
				<content:encoded><![CDATA[<p>As <a href="http://www.python.org/">Python</a> transitions from version 2 to version 3, the meaning of the <a href="http://www.python.org/dev/peps/pep-0238/">division operator</a> on integers is changing:</p>
<table>
<thead>
<tr>
<td>Python 2.x</td>
<td>Python 3.x</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<pre>$ python2.7
Python 2.7.2+ (...)
...
&gt;&gt;&gt; 1/2
0</pre>
</td>
<td>
<pre>$ python3.2
Python 3.2.2 (...)
...
&gt;&gt;&gt; 1/2
0.5</pre>
</td>
</tr>
</tbody>
</table>
<p>In this post, we&#8217;ll discuss how to configure the behavior of the division operator in Python 2.7 and IPython to behave like the Python 3.x counterpart.</p>
<p><span id="more-104"></span>We&#8217;ll call the division in Python 2.x &#8220;classic&#8221; or &#8220;old.&#8221; It does division in the C sense: an integer divided by an integer yields an integer, rounding down if needed.</p>
<p>The &#8220;new&#8221; division in Python 3.x instead computes the true division result. In this case, an integer divided by an integer yields a float. The floor division can be accessed in a new operator &#8220;//&#8221; as in:<br />
<code></code></p>
<pre>&gt;&gt;&gt; 1 // 2
0</pre>
<p>To allow for a transition period, two compatibility features are provided. First, module developers can add <code></code></p>
<pre>from __future__ import division</pre>
<p>&nbsp;</p>
<p><code></code> to the top of any <code>.py</code> file to indicate that &#8220;/&#8221; should mean true division in that file.</p>
<p>In addition, the Python interpreter can be passed a flag to indicate the desired division behavior:<br />
<code></code></p>
<pre>-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew</pre>
<p>&nbsp;</p>
<p><code></code><br />
So for example, we can run:<br />
<code></code></p>
<pre>$ python2.7 -Qnew
...
&gt;&gt;&gt; 1/2
0.5</pre>
<p>But what about IPython? There isn&#8217;t a corresponding flag on the <code>ipython</code> script, <a href="https://github.com/ipython/ipython/issues/1239">yet</a>. In discussing adding this feature to IPython, Fernando Perez provided <a href="https://github.com/ipython/ipython/issues/1239#issuecomment-3381024">a useful tip</a> for accomplishing this using the IPython configuration files.</p>
<p>To begin, you&#8217;ll need to create an IPython profile by running<br />
<code></code></p>
<pre>$ ipython profile create</pre>
<p>Then edit the configuration file, which for me was located at <code>~/.config/ipython/profile_default/ipython_config.py</code>, and uncomment and add the following:<br />
<code></code></p>
<pre># lines of code to run at IPython startup.                                                                                                                 
c.InteractiveShellApp.exec_lines = [
    &#039;from __future__ import division&#039;
]</pre>
<p>We can test it out and see that it does in fact work as desired:<br />
<code></code></p>
<pre>$ ipython
Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
Type &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.

IPython 0.13.dev -- An enhanced Interactive Python.
?         -&gt; Introduction and overview of IPython&#039;s features.
%quickref -&gt; Quick reference.
help      -&gt; Python&#039;s own help system.
object?   -&gt; Details about &#039;object&#039;, use &#039;object??&#039; for extra details.

In [1]: 1/2
Out[1]: 0.5</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2012/01/true-division-in-ipython/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IPython Qt Console and printf</title>
		<link>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/</link>
		<comments>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 17:52:05 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[IPython]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=94</guid>
		<description><![CDATA[The recent 0.11 release of IPython includes a Qt-based console which offers an improved experience compared to running IPython in a terminal. In particular, the console feels like a terminal but offers multi-line editing, syntax highlighting, graphical tooltips, and inline plot figures. But when I tried to run an existing script in the new IPython [...]]]></description>
				<content:encoded><![CDATA[<p>The recent <a href="http://ipython.org/ipython-doc/stable/whatsnew/version0.11.html">0.11 release</a> of <a href="http://ipython.org/">IPython</a> includes a <a href="http://ipython.org/ipython-doc/stable/interactive/qtconsole.html">Qt-based console</a> which offers an improved experience compared to running IPython in a terminal. In particular, the console feels like a terminal but offers multi-line editing, syntax highlighting, graphical tooltips, and inline plot figures.</p>
<p>But when I tried to run an existing script in the new IPython Qt Console, the usual overly verbose set of diagnostic messages did not appear! The symtoms were:</p>
<ul>
<li>Regular <code>print</code> statements in Python worked fine.</li>
<li><code>printf</code> statements in C-code wrapped with Boost.Python did not appear.</li>
</ul>
<p>Read on to see a solution.<span id="more-94"></span></p>
<p>This seemed quite odd until I read more about the architecture of IPython Qt Console. In particular, IPython Qt Console is a two-process architecture whereby a background IPython process executes code and frontend client handles all user input and output. So our <code>printf</code> statements were being sent to <code>stdout</code> in the background process and therefore never appear in the Qt Console window.</p>
<p>Somebody must have experienced this before, but a few quick Google searched turned up nothing. How would <a href="http://cython.org/">Cython</a> handle this? In particular, we could use Cython to compile a simple Python print statement. So consider the simple <code>printf.pyx</code> file:</p>
<pre class="brush: python; gutter: true">def printf():
    print &quot;Hello&quot;</pre>
<p>which we compile into C using <code>cython printf.pyx</code>. The <a href="https://gist.github.com/1284900">resulting C file</a> is quite lengthy, but the relevant bits are in the <code>__Pyx_PrintOne()</code> function:</p>
<pre class="brush: c; gutter: true">static int __Pyx_PrintOne(PyObject* f, PyObject *o) {
    if (!f) {
        if (!(f = __Pyx_GetStdout()))
            return -1;
    }
    if (PyFile_SoftSpace(f, 0)) {
        if (PyFile_WriteString(&quot; &quot;, f) &lt; 0)
            return -1;
    }
    if (PyFile_WriteObject(o, f, Py_PRINT_RAW) &lt; 0)
        return -1;
    if (PyFile_WriteString(&quot;\n&quot;, f) &lt; 0)
        return -1;
    return 0;
    /* the line below is just to avoid compiler
     * compiler warnings about unused functions */
    return __Pyx_Print(f, NULL, 0);
}</pre>
<p>The <code>__Pyx_GetStdout()</code> function is nothing more than a thin wrapper to <code>PySys_GetObject((char *)"stdout")</code> with a bit of error checking.</p>
<p>Putting this all together, a simple reporting function (without any error checking) becomes:</p>
<pre class="brush: cpp; gutter: true">void report(std::string msg) {
  PyObject *f = PySys_GetObject((char *)&quot;stdout&quot;);
  PyFile_WriteString(msg.c_str(), f);
  PyFile_WriteString(&quot;\n&quot;, f);
}</pre>
<p>For an example module using this code, see <a href="https://gist.github.com/1284927">gist 1284927</a>.</p>
<p><strong>Update:</strong> After writing this, I learned of <a href="http://docs.python.org/c-api/sys.html#PySys_WriteStdout">PySys_WriteStdout()</a> which is a nearly drop-in replacement of printf.  However the above method is still be useful if you need to print more than 1000 bytes at a time.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FILE* and Boost.Python</title>
		<link>http://bfroehle.com/2011/10/file-and-boost-python/</link>
		<comments>http://bfroehle.com/2011/10/file-and-boost-python/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 22:44:09 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[FILE*]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=85</guid>
		<description><![CDATA[One great feature of Boost.Python is the ability to write custom converters from Python types to C++ arguments. Most Boost.Python documentation, including the incredibly helpful post by misspent, show you how to write &#8220;rvalue&#8221; converters (e.g., pass-by-value or pass-by-const-reference). However if you need to wrap a function which takes a FILE* argument the previous approach will [...]]]></description>
				<content:encoded><![CDATA[<p>One great feature of <a href="http://www.boost.org/doc/libs/1_47_0/libs/python/doc/">Boost.Python</a> is the ability to write custom converters from Python types to C++ arguments. Most <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/faq.html#question2">Boost.Python documentation</a>, including the incredibly helpful post by <a href="http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/">misspent</a>, show you how to write &#8220;rvalue&#8221; converters (e.g., pass-by-value or pass-by-const-reference).</p>
<p>However if you need to wrap a function which takes a <code>FILE*</code> argument the previous approach will not prove fruitful. But Boost.Python is clearly capable of handling a similar situation, namely the implicit conversion from a Python string type to a <code>char*</code> type. Since the conversion from the internal <code>PyObject*</code> to <code>char*</code> is likely to be done with the <a href="http://docs.python.org/c-api/string.html">PyString_AsString</a> function, I went off in search of that code.</p>
<p><span id="more-85"></span>There were no references in the installed headers, but it did appear in the source code in <code>converter/builtin_converters.cpp</code> in the <code>convert_to_cstring()</code> function:</p>
<pre class="brush: cpp; gutter: true">// An lvalue conversion function which extracts a char const* from a
// Python String.
void* convert_to_cstring(PyObject* obj)
{
  return PyString_Check(obj) ? PyString_AsString(obj) : 0;
}</pre>
<p>&#8230; which was later called as &#8230;</p>
<pre class="brush: cpp; gutter: true">// Add an lvalue converter for char which gets us char const*
registry::insert
  (convert_to_cstring, type_id(),
   &amp;converter::wrap_pytype&lt;&amp;PyString_Type&gt;::get_pytype);</pre>
<p>Jackpot! We should be able to mimic these lines to create a <a href="http://docs.python.org/library/stdtypes.html#file-objects">Python file</a> to <code>FILE*</code> converter using <a href="http://docs.python.org/c-api/file.html">PyFile_AsFile()</a>:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;

namespace {
  void *convert_to_FILEptr(PyObject* obj) {
    return PyFile_Check(obj) ? PyFile_AsFile(obj) : 0;
  }
}

BOOST_PYTHON_MODULE(file_wrapper) {
  boost::python::converter::registry::insert
    (convert_to_FILEptr,
     boost::python::type_id&lt;FILE&gt;(),
     &amp;boost::python::converter::wrap_pytype&lt;&amp;PyFile_Type&gt;::get_pytype);
}</pre>
<p>For a complete example including test code, see <a href="https://gist.github.com/1265889">gist: 1265889</a>.</p>
<p><strong>Edit:</strong> Of course this also works with <code>boost::python::extract&lt;FILE*&gt;</code>. I&#8217;ve updated the gist to demonstrate the relevant usage.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/10/file-and-boost-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging MPI + Python</title>
		<link>http://bfroehle.com/2011/09/debugging-mpi-python/</link>
		<comments>http://bfroehle.com/2011/09/debugging-mpi-python/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 18:44:55 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[IPython]]></category>
		<category><![CDATA[mpi]]></category>
		<category><![CDATA[mpirun]]></category>
		<category><![CDATA[screen]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=78</guid>
		<description><![CDATA[Python is increasingly becoming a popular language for controlling large numerical simulations due to its scripting abilities and easy bindings with C, C++, and Fortran as provided by ctypes, Boost.Python, SWIG, etc. In addition, there are some nice convenience wrappers for MPI, including mpi4py. However debugging MPI scripts can be challenging. Here are some useful ways [...]]]></description>
				<content:encoded><![CDATA[<p>Python is increasingly becoming a popular language for controlling large numerical simulations due to its scripting abilities and easy bindings with C, C++, and Fortran as provided by <a href="http://docs.python.org/library/ctypes.html">ctypes</a>, <a href="www.boost.org/doc/libs/release/libs/python/doc/">Boost.Python</a>, <a href="http://www.swig.org/">SWIG</a>, etc. In addition, there are some nice convenience wrappers for <a href="http://en.wikipedia.org/wiki/Message_Passing_Interface">MPI</a>, including <a href="http://mpi4py.scipy.org/">mpi4py</a>.</p>
<p>However debugging MPI scripts can be challenging. Here are some useful ways to run your programs for debugging.</p>
<ul>
<li>
Open an xterm window for each MPI process, with the script running in <a href="http://ipython.org/">iPython</a>.</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 xterm -e &quot;ipython script.py&quot;</pre>
</li>
<li>
Open an xterm window for each MPI process, with <a href="http://www.gnu.org/s/gdb/">gdb</a> attached to each python process. The <code>-x</code> flag tells gdb to run the commands given in the specified file. This is often a good place to add additional breakpoints.</p>
<pre class="brush: bash; gutter: true">$ echo &quot;run script.py&quot; &gt; gdb.in
$ mpirun -np 4 xterm -e &quot;gdb -x gdb.in python&quot;</pre>
</li>
<li>
Open each MPI process within <a href="http://www.gnu.org/s/screen/">screen</a>, then open a <a href="http://en.wikipedia.org/wiki/GNOME_Terminal">gnome-terminal</a> with one tab for each screen.</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 screen -L -m -D -S mpi \
    ipython script.py &amp;
$ gnome-terminal --tab -e &quot;screen -RR -p mpi&quot; \
                 --tab -e &quot;screen -RR -p mpi&quot; \
                 --tab -e &quot;screen -RR -p mpi&quot; \
                 --tab -e &quot;screen -RR -p mpi&quot;</pre>
<p>If your program dies unexpectedly, it is probably because LD_LIBRARY_PATH is <a href="http://lists.gnu.org/archive/html/screen-users/2008-01/msg00016.html">stripped by glibc</a> since screen is a setgid/setuid program. You can work around this my modifying the <code>mpirun</code> call as</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 screen -L -m -D -S mpi \
    env LD_LIBRARY_PATH=$LD_LIBRARY_PATH ipython script.py</pre>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/09/debugging-mpi-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
