<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>glib &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/glib/</link>
	<description>Feed of posts on WordPress.com tagged "glib"</description>
	<pubDate>Fri, 24 May 2013 14:41:26 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Using SCTP in GLib]]></title>
<link>http://airtower.wordpress.com/2010/06/30/using-sctp-in-glib/</link>
<pubDate>Wed, 30 Jun 2010 20:53:54 +0000</pubDate>
<dc:creator>Airtower</dc:creator>
<guid>http://airtower.wordpress.com/2010/06/30/using-sctp-in-glib/</guid>
<description><![CDATA[A while ago, I wrote about using a UDP socket as event source in GLib. Now, I&#8217;m migrating my p]]></description>
<content:encoded><![CDATA[<p>A while ago, I wrote about using a <a href="http://airtower.wordpress.com/2010/06/19/using-a-udp-socket-as-event-source-in-glib-main-loop/">UDP socket as event source in GLib</a>. Now, I&#8217;m migrating my program to <a href="http://en.wikipedia.org/wiki/Stream_Control_Transmission_Protocol">SCTP</a>. The main reason is that SCTP provides reliability for sequential messages, but some of the advanced features might become useful later. Surprisingly few changes were necessary in my program:</p>
<ul>
<li>Create the socket with <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html#GSocketType">G_SOCKET_TYPE_SEQPACKET</a></code> and <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html#GSocketProtocol">G_SOCKET_PROTOCOL_SCTP</a></code> instead of <code>G_SOCKET_TYPE_DATAGRAM</code> and <code>G_SOCKET_PROTOCOL_UDP</code>, respectively.</li>
<li>Use <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html#g-socket-listen">g_socket_listen</a>()</code> to start receiving messages.</li>
</ul>
<p>The relevant code parts now look like this:</p>
<pre class="brush: cpp; title: ; notranslate" title="">GSocket *sock;
GError *err = NULL;
sock = g_socket_new(G_SOCKET_FAMILY_IPV6,
                    G_SOCKET_TYPE_SEQPACKET,
                    G_SOCKET_PROTOCOL_SCTP,
                    &#38;err);
g_assert(err == NULL);

g_socket_bind(sock,
              G_SOCKET_ADDRESS(addr),
              TRUE,
              &#38;err);
g_assert(err == NULL);

int fd = g_socket_get_fd(sock);
GIOChannel* channel = g_io_channel_unix_new(fd);
guint source = g_io_add_watch(channel, G_IO_IN,
                              (GIOFunc) callback_function, data);
g_io_channel_unref(channel);

g_socket_listen(sock, &#38;err);
g_assert(err == NULL);</pre>
<p>Sadly, it seems like there are no functions for <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html">GSocket</a></code> to use lower level SCTP features, like getting the list of peer and local IP addresses in the association. I suppose this is possible by using the normal low level functions (e.g. <code>sctp_getpaddrs()</code>) on the file descriptor returned by <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html#g-socket-get-fd">g_socket_get_fd</a>()</code>, but I haven&#8217;t tried yet.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Events and threads: A mutex is not enough!]]></title>
<link>http://airtower.wordpress.com/2010/06/25/events-and-threads-a-mutex-is-not-enough/</link>
<pubDate>Fri, 25 Jun 2010 21:59:05 +0000</pubDate>
<dc:creator>Airtower</dc:creator>
<guid>http://airtower.wordpress.com/2010/06/25/events-and-threads-a-mutex-is-not-enough/</guid>
<description><![CDATA[I wrote a little UDP server that would process messages like this: Incoming data on the UDP socket c]]></description>
<content:encoded><![CDATA[<p>I wrote a little UDP server that would process messages like this:</p>
<ol>
<li>Incoming data on the UDP socket <a href="http://airtower.wordpress.com/2010/06/19/using-a-udp-socket-as-event-source-in-glib-main-loop/">creates an event</a> in the GLib main loop.</li>
<li>The event callback function starts a handler thread from a <code><a href="http://library.gnome.org/devel/glib/stable/glib-Thread-Pools.html">GThreadPool</a></code>.</li>
<li>The thread locks a <a href="http://library.gnome.org/devel/glib/stable/glib-Threads.html#GMutex">mutex</a> for the socket, reads from the socket, maybe sends a reply (depends on the received message), unlocks the mutex and returns.</li>
</ol>
<p>Looks harmless? It isn&#8217;t. The program used a signal callback to stop the main loop on <code>SIGTERM</code>. This would allow any remaining threads to finish their work before the program terminates. When I tested that, I was surprised that the server would not stop. I had to add a lot of debug output until I found the reason.</p>
<p>The problem was that the messages were read from the socket in the threads. The event callback returned after starting the thread, and the main loop continued to run. In the short time between thread start and socket read, the event would fire again and again, because the data was still available on the socket. This was enough to launch all handler threads in my 4 member thread pool.</p>
<p>The result: The first thread gets the mutex, reads the message, does its work, unlocks the mutex and returns. While the first thread reads, there are 3 more threads waiting for the mutex. When the first thread is done, one of the others grabs the mutex and tries to read. I used blocking functions, so it waits until a new message arrives. A new message fires an event, which starts another thread. I suppose you get the idea. All handler threads were trying to process incoming messages simultaneously! By the way, the <code>SIGTERM</code> callback actually worked. After <code>SIGTERM</code>, no new events and therefore no handler threads were created, and after receiving enough messages the server did indeed terminate, because each thread returned after processing its message.</p>
<p>This is why I wrote that <em>a mutex is not enough</em>. Yes, the mutex prevented the threads reading from the socket at the same time, but it did not stop the event. The solution was, of course, to read the message in the event callback and point the handler thread at the data. Lesson learned: Don&#8217;t just think about &#8220;Could these threads try to access something at the same time?&#8221; and throw in a mutex if the answer is yes. Threaded operation can create a lot of unintended connections, and it&#8217;s easy to overlook one of them. Take care, and you can avoid a long debugging session like the one I had today. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Using a UDP socket as event source in GLib main loop]]></title>
<link>http://airtower.wordpress.com/2010/06/19/using-a-udp-socket-as-event-source-in-glib-main-loop/</link>
<pubDate>Sat, 19 Jun 2010 18:14:31 +0000</pubDate>
<dc:creator>Airtower</dc:creator>
<guid>http://airtower.wordpress.com/2010/06/19/using-a-udp-socket-as-event-source-in-glib-main-loop/</guid>
<description><![CDATA[I&#8217;ve been rewriting a small UDP server using GLib. I found it difficult to get started with GL]]></description>
<content:encoded><![CDATA[<p>I&#8217;ve been rewriting a small UDP server using GLib. I found it difficult to get started with GLib, but well worth it &#8211; the code is a lot cleaner now. One thing that took me particularly long to figure out is how to integrate listening on a UDP socket into the GLib main loop. It&#8217;s not really complicated, but the parts are scattered in different parts of the <a href="http://library.gnome.org/devel/glib/stable/">GLib</a> and <a href="http://library.gnome.org/devel/gio/stable/">GIO</a> API documentation.</p>
<p>Obviously, a <code><a href="http://library.gnome.org/devel/gio/stable/GSocket.html">GSocket</a></code> is necessary. I want my socket to listen on IPv6 UDP. I know that assertions are not the best error handling, but they are good enough for an example. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<pre class="brush: cpp; title: ; notranslate" title="">GSocket *sock;
GError *err = NULL;
sock = g_socket_new(G_SOCKET_FAMILY_IPV6,
                    G_SOCKET_TYPE_DATAGRAM,
                    G_SOCKET_PROTOCOL_UDP,
                    &#38;err);
g_assert(err == NULL);</pre>
<p>Bind the socket (<code>addr</code> is the <code><a href="http://library.gnome.org/devel/gio/stable/GInetSocketAddress.html">GInetSocketAddress</a>*</code> to listen on):</p>
<pre class="brush: cpp; title: ; notranslate" title="">g_socket_bind(sock,
              G_SOCKET_ADDRESS(addr),
              TRUE,
              &#38;err);
g_assert(err == NULL);</pre>
<p>Hint: if you want to listen on all interfaces, use <a href="http://library.gnome.org/devel/gio/stable/GInetAddress.html#g-inet-address-new-any">g_inet_address_new_any()</a> to create the <code><a href="http://library.gnome.org/devel/gio/stable/GInetAddress.html">GInetAddress</a></code> part of the socket&#8217;s address. Under Linux &#8220;any IPv6 address&#8221; includes IPv4, I don&#8217;t know if this applies on other platforms as well.</p>
<p>To get an event when the socket receives data, the following steps are necessary:</p>
<ol>
<li>Get a file descriptor for the socket.</li>
<li>Use the file descriptor to create a <code><a href="http://library.gnome.org/devel/glib/stable/glib-IO-Channels.html">GIOChannel</a></code> for the socket.</li>
<li><a href="http://library.gnome.org/devel/glib/stable/glib-IO-Channels.html#g-io-add-watch">Add a watch</a> for the <code><a href="http://library.gnome.org/devel/glib/stable/glib-IO-Channels.html#G-IO-IN:CAPS">G_IO_IN</a></code> condition on the channel.</li>
</ol>
<pre class="brush: cpp; title: ; notranslate" title="">int fd = g_socket_get_fd(sock);
GIOChannel* channel = g_io_channel_unix_new(fd);
guint source = g_io_add_watch(channel, G_IO_IN,
                              (GIOFunc) callback_function, data);
g_io_channel_unref(channel);</pre>
<p>The <code>callback_function</code> has to match the <code><a href="http://library.gnome.org/devel/glib/stable/glib-IO-Channels.html#GIOFunc">GIOFunc</a></code> pattern. It must not block, so I use it to start a thread which will do the real work. The <a href="http://library.gnome.org/devel/glib/stable/glib-The-Main-Event-Loop.html">main loop</a> needs to be initialized before attaching the event. After the event is attached, just run the main loop (if you need more info about that, look <a href="http://w00d5t0ck.info/gnome_tutorial/gnome_tutorial.html#AEN53">here</a>). Cleaning up is pretty simple: Use <code><a href="http://library.gnome.org/devel/glib/stable/glib-The-Main-Event-Loop.html#g-source-remove">g_source_remove</a>(source)</code> to disconnect the event source and <code>g_object_unref()</code> the objects.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Learning GObject basics]]></title>
<link>http://airtower.wordpress.com/2010/06/18/learning-gobject-basics/</link>
<pubDate>Thu, 17 Jun 2010 23:15:16 +0000</pubDate>
<dc:creator>Airtower</dc:creator>
<guid>http://airtower.wordpress.com/2010/06/18/learning-gobject-basics/</guid>
<description><![CDATA[GLib and GObject enable object oriented programming in pure C. I will need a GObject later to build]]></description>
<content:encoded><![CDATA[<p>GLib and GObject enable object oriented programming in pure C. I will need a GObject later to build a <a href="http://www.freedesktop.org/wiki/Software/dbus">D-Bus</a> interface, so I wanted to write a simple class to learn how to use it. After reading <a href="http://diuf.unifr.ch/pai/people/broccoa/gobjecttutorial.html">&#8220;Introduction to GObject&#8221; by Amos Brocco</a> and the <a href="http://library.gnome.org/devel/gobject/stable/pt02.html">tutorial part</a> of the <a href="http://library.gnome.org/devel/gobject/stable/">GObject Reference Manual</a>, I started writing my own class. I could take a large part of the basic code from the examples in the reference manual, but a few things were somewhat confusing:</p>
<ul>
<li>Which functions do I <em>have to</em> implement?</li>
<li>Where should I define what struct?</li>
<li>Do I need to allocate the private memory?</li>
<li>Should the object struct contain a pointer to the private memory?</li>
</ul>
<p>Here are the answers that I found:</p>
<h3>Necessary functions</h3>
<p>Four functions are the absolute minimum: <code>init</code>, <code>class_init</code>, <code>dispose</code> and <code>finalize</code>. For a class named example, you would need the following declarations in the header:</p>
<pre class="brush: cpp; title: ; notranslate" title="">static void example_init(Example *self);
static void example_class_init(ExampleClass *klass);
static void example_dispose(GObject *gobject);
static void example_finalize(GObject *gobject);</pre>
<p>The argument to <code>class_init</code> should be called <code>klass</code> to avoid confusion with the C++ <code>class</code> keyword.</p>
<h3>Structs</h3>
<p>The object und class structs have to be declared and defined in the header (<a href="http://library.gnome.org/devel/gobject/stable/howto-gobject.html#howto-gobject-header">example</a>). You can put the private data struct declaration into the header or source, the definition should definitely be in the source file. I would recommend putting the <code>typedef</code> into the header, because it will allow you to add a pointer to the private memory into the object struct. Put something like this into the header:</p>
<pre class="brush: cpp; title: ; notranslate" title="">typedef struct _Example Example;
typedef struct _ExampleClass ExampleClass;
typedef struct _ExamplePrivate ExamplePrivate;

struct _Example {
	GObject parent_instance;
	/* instance members */
	ExamplePrivate *priv;
};

struct _ExampleClass {
	GObjectClass parent_class;
	/* class members */
};</pre>
<p>The definition of <code>struct _ExamplePrivate</code> goes into the source file. The contents of the private structure is entirely your decision.</p>
<h3>Allocating and accessing private memory</h3>
<p>Register the private memory with the object system using <a href="http://library.gnome.org/devel/gobject/stable/gobject-Type-Information.html#g-type-class-add-private"><code>g_type_class_add_private()</code></a> in your class&#8217; <code>class_init()</code> function. It will be allocated automatically when you use <a href="http://library.gnome.org/devel/gobject/stable/gobject-Type-Information.html#G-TYPE-INSTANCE-GET-PRIVATE:CAPS"><code>G_TYPE_INSTANCE_GET_PRIVATE</code></a> for the first time, and freed automatically as well. However, you have to take care of any dynamically allocated memory in the private data. To quote the manual:</p>
<blockquote><p>&#8220;You don&#8217;t need to free or allocate the private structure, only the objects or pointers that it may contain.&#8221;</p></blockquote>
<p>If you use the source layout recommended in the manual, you will get a useful macro called something like <code>EXAMPLE_GET_PRIVATE</code> which returns a pointer to the private memory. Using a <code>*priv</code> pointer is not necessary (you could use <code>GET_PRIVATE</code> each time you need it), but it is a good idea to improve performance (the macro does a few function calls).</p>
<p>You can see how to register and get private memory in the <a href="http://library.gnome.org/devel/gobject/stable/howto-gobject-destruction.html">example source file</a>, look at the <code>maman_bar_class_init()</code> and <code>maman_bar_init()</code> functions and the <code>MAMAN_BAR_GET_PRIVATE</code> macro.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Installing GTK+ with MPX Support]]></title>
<link>http://totoshi.wordpress.com/2010/06/06/mpx-and-gtk/</link>
<pubDate>Sun, 06 Jun 2010 19:52:13 +0000</pubDate>
<dc:creator>totoshi</dc:creator>
<guid>http://totoshi.wordpress.com/2010/06/06/mpx-and-gtk/</guid>
<description><![CDATA[Update: The GTK+ xi2 branch has been recently merged into the master. I have thus updated the instal]]></description>
<content:encoded><![CDATA[<p><strong>Update</strong>: The GTK+ xi2 branch has been recently merged into the master. I have thus updated the install instructions below.</p>
<p>GTK+ already supports multiple mouse pointers, but only in it&#8217;s git version. The GTK+ page for <a href="http://en.wikipedia.org/wiki/Multi-Pointer_X">MPX</a> is available <a href="http://live.gnome.org/GTK%2B/MPX">here</a>. In this post, I will discuss how to compile and run GTK+ with MPX support. The following has been tested on <a href="http://www.archlinux.org/">Archlinux</a>, but should work for any other Linux distribution.</p>
<p>Before we start, we need to make sure, our system meets the necessary dependencies (see <a href="http://library.gnome.org/devel/gtk-faq/stable/c192.html#FAQ-COMPILE">here</a> for a list). When we are sure the dependencies are met, we need to install <a href="http://en.wikipedia.org/wiki/GLib">GLib</a> from source since GTK+ depends on it. This is how we install GLib and update pkg-config:</p>
<pre class="brush: bash; title: ; notranslate" title="">
$ git clone git://git.gnome.org/glib
$ cd glib
$ ./autogen.sh --prefix=&#60;your path to glib&#62;
$ make
$ make install
$ sudo cp &#60;your path to glib&#62;/pkgconfig/* /usr/lib/pkgconfig/
</pre>
<p>Now we are ready to get the sources of GTK+:</p>
<pre class="brush: bash; title: ; notranslate" title="">
$ git clone git://git.gnome.org/gtk+/
</pre>
<p>You can now switch to the 2.90.2 tag if you want:</p>
<pre class="brush: bash; title: ; notranslate" title="">
$ git checkout 2.90.2
</pre>
<p>Next, we can configure and compile the xi2 branch and update pkgconfig:</p>
<pre class="brush: bash; title: ; notranslate" title="">
$ ./autogen.sh --prefix=&#60;path to gtk&#62;
$ make
$ make install
$ sudo cp &#60;path to gtk&#62;/lib/pkgconfig/* /usr/lib/pkgconfig/
</pre>
<p>GTK+ should now be working with MPX support. To compile files with gtk+-3.0, you can use:</p>
<pre class="brush: bash; title: ; notranslate" title="">

gcc &#60;file&#62; -o &#60;name&#62; `pkg-config --cflags --libs gtk+-3.0`

</pre>
<p>To test the installed GTK+, we need to create a new master in xinput and add a new pointer device:</p>
<pre class="brush: bash; title: ; notranslate" title="">
xinput create-master &#60;name&#62;
xinput list
xinput reattach &#60;device id&#62; &#60;new master pointer id&#62;
</pre>
<p>You can now run the tests in the GTK+ sources  (<strong>Update</strong>: the test has been removed since the branch was merged, but you can find an example of how to use multipointer input in GTK <a href="http://totoshi.wordpress.com/2010/06/14/adding-multipointer-support/">here</a>):</p>
<pre class="brush: bash; title: ; notranslate" title="">
cd &#60;path to gtk+ sources&#62;/tests/multidevice
make
./testcoordinates
</pre>
<p><a href="http://totoshi.files.wordpress.com/2010/06/multi_mpx.jpg"><img class="aligncenter size-medium wp-image-73" title="multi_mpx" src="http://totoshi.files.wordpress.com/2010/06/multi_mpx.jpg?w=300&#038;h=186" alt="" width="300" height="186" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The Gift of Glib]]></title>
<link>http://cadogblog.wordpress.com/2010/05/30/the-gift-of-glib/</link>
<pubDate>Mon, 31 May 2010 03:57:33 +0000</pubDate>
<dc:creator>cadogblog</dc:creator>
<guid>http://cadogblog.wordpress.com/2010/05/30/the-gift-of-glib/</guid>
<description><![CDATA[Mask#9 is one of a series based on a single photo.  This print tries to convey the smooth superficia]]></description>
<content:encoded><![CDATA[<p><a href="http://cadogblog.files.wordpress.com/2010/05/mask9-web.jpg"><img class="aligncenter size-full wp-image-210" title="Mask#9 Web" src="http://cadogblog.files.wordpress.com/2010/05/mask9-web.jpg?w=450&#038;h=299" alt="" width="450" height="299" /></a></p>
<p>Mask#9 is one of a series based on a single photo.  This print tries to convey the smooth superficiality of today&#8217;s public faces. Who or what are they? I can&#8217;t quite make out, they might be&#8230;then again&#8230;. look away, look back. Everything changes.</p>
<p>See more prints and drawings by  Dennis and Susan at our Etsy store  <a title="our Etsy   store" href="http://www.etsy.com/shop/digiprintskishowen">Galerie   Yggdrasil</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[A HUSBAND IS A PITIABLE CREATURE]]></title>
<link>http://waterfriend.wordpress.com/2010/04/19/a-husband-is-a-pitiable-creature/</link>
<pubDate>Mon, 19 Apr 2010 07:27:47 +0000</pubDate>
<dc:creator>waterfriend</dc:creator>
<guid>http://waterfriend.wordpress.com/2010/04/19/a-husband-is-a-pitiable-creature/</guid>
<description><![CDATA[Many men are afraid of marriage. As Bernard Shaw said, if you marry, you will repent immediately. Bu]]></description>
<content:encoded><![CDATA[<p>Many men are afraid of marriage. As Bernard Shaw said, if you marry, you will repent immediately.</p>
<p>But they will not allow you to enjoy your freedom indefinitely. Mother needs an assistant when she gets old. A number of fathers will try to get you entangled for their daughters. In India, an unmarried girl is a curse on her parents. If nothing else, your friends come forward to help you. I think such things are unknown in the West.</p>
<p>Once married, there is no going back. You are tied for seven lives, one after another.</p>
<p>Every day you have to bring vegetables, milk and such things in addition to taking her for shopping, cinema and visiting friends. As soon as you come back from your work place, tired and angry, on account of the bickerings and fights with your colleagues and the irrational Boss, she will be waiting, fully dressed, to go out. Not her fault, as she is kept inside the house, bored to death. Well get fresh, change your dress and go out.</p>
<p>When children are born, at least two, there is no end to your worries. Worries are multiplied, with the children fighting each other, then school, tuition, home work and all that.</p>
<p>Wife falling ill, in-laws coming and all sorts of complications.</p>
<p>If she is beautiful (who will marry an ugly girl?), you are suspicious of that idle fellow, who is always so sweet and glib tongued.</p>
<p>And, when you want to do it, she is not in the mood.</p>
<p>Before you realised it, your daughter has grown too big. Now it is your turn, to hunt for a husband for her.</p>
<p>W-I-F-E means, Worry Invited For Ever !.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[How to get units consistent across all applications?]]></title>
<link>http://overbenny.wordpress.com/2010/03/26/how-to-get-units-consistent-across-all-applications/</link>
<pubDate>Fri, 26 Mar 2010 13:38:14 +0000</pubDate>
<dc:creator>overbenny</dc:creator>
<guid>http://overbenny.wordpress.com/2010/03/26/how-to-get-units-consistent-across-all-applications/</guid>
<description><![CDATA[We have a units policy in Ubuntu, which we have to implement in lucid+1 (Ubuntu 10.10). Correcting a]]></description>
<content:encoded><![CDATA[<p>We have a <a href="https://wiki.ubuntu.com/UnitsPolicy">units policy</a> in Ubuntu, which we have to implement in lucid+1 (Ubuntu 10.10). Correcting all applications to conform to this policy is not an easy task. The first attempt to patch glib, which provides the g_format_size_for_display() function, failed. We need a library that can handle input and output formatted sizes. Take transmission as example: I want to set the bandwidth limit in the same unit as it displays me the limit. We have to introduce a set of new functions.</p>
<p>Should I create a new library (named libbyteunits or similar) or add a bunch of new functions to glib (as replacement for g_format_size_for_display)? Is glib the right place for ten or more functions handling units?</p>
<p>Pros for a separate library:</p>
<ul>
<li>the library can be used by non-glib application without depending on glib</li>
<li>it can be made user configurable (for example by an text file), because some user prefer base-10, others base-2.</li>
</ul>
<p>Cons:</p>
<ul>
<li> one more dependency for glib applications</li>
</ul>
<p>I like to hear as many opinions as possible. Please let me also know, if you are glib developer, a g_format_size_for_display() using developer, a developer, or a user.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Senior Application Engineer - Communications]]></title>
<link>http://mindsourceinc.wordpress.com/2010/02/17/senior-application-engineer-communications/</link>
<pubDate>Wed, 17 Feb 2010 23:33:12 +0000</pubDate>
<dc:creator>Michelle</dc:creator>
<guid>http://mindsourceinc.wordpress.com/2010/02/17/senior-application-engineer-communications/</guid>
<description><![CDATA[Our client is looking for a SENIOR APPLICATION ENGINEER &#8211; COMMUNICATIONS. DESCRIPTION: Design,]]></description>
<content:encoded><![CDATA[<p>Our client is looking for a <strong>SENIOR APPLICATION ENGINEER &#8211; COMMUNICATIONS</strong>.</p>
<p><strong>DESCRIPTION: </strong></p>
<p>Design, implement, and support high quality, high performance consumer-facing software applications for web-connected devices. This role involves hands-on development and oversight of core components of the product, in collaboration with a software team that spans internal and external distributed development teams. Ideal candidates will have prior experience with both designing and leveraging communication (e.g., IM, e-mail, VOIP) frameworks and rich media user interface development.</p>
<ul>
<li>Analyze product definition and define software requirements within your domain. Consult with product management and architects to create an optimal design and plan for user interface and/or service components to meet an aggressive product schedule</li>
<li>Evaluate, integrate, and enhance 3<sup>rd</sup> party APIs and technologies, tailoring the provided functionality to meet the needs</li>
<li>Identify possible pitfalls and provide practical alternatives/solutions.</li>
</ul>
<p><strong>QUALIFICATIONS<br />
</strong></p>
<p><strong>REQUIRED SKILLS AND EXPERIENCES</strong></p>
<ul>
<li>5+ years of experience developing complex Internet-connected communication applications in C/C++.</li>
<li>Deep hands-on development experience with email and messaging technologies (IMAP, POP3, MAPI)</li>
<li>Deep knowledge of Network technologies &#8211; proxy server, load balancers, TCP/IP, UDP</li>
<li>Experience with TCP/IP socket level communication development</li>
<li>Development experience with scripting languages (e.g., Python, Lua, JavaScript, ActionScript)</li>
<li>Hands on development with software libraries and object systems (e.g., GLib, GObject, LibXML, libjpeg)</li>
<li>Experience designing and implementing complex data-driven systems, including optimizations.</li>
<li>Experience with development on Linux platforms and tool chains.</li>
<li>Must be able to work with project stakeholders to analyze, understand and implement user requirements.</li>
<li>Strong desire to work in a dynamic team environment, including oversight of remote development.</li>
<li>Strong desire to get &#8220;outside of the box&#8221; and explore solutions from a variety of perspectives and make appropriate technical tradeoffs.</li>
<li>Must work quickly, creatively &#38; decisively, delivering designs to suit product / project requirements</li>
</ul>
<p><strong>DESIRED SKILLS AND EXPERIENCES</strong></p>
<ul>
<li>Experience with skinning applications on media frameworks and UI toolkits (e.g., XBMC)</li>
<li>Experience with social networking API&#8217;s (e.g., Facebook Connect)</li>
<li>Experience with SOAP/REST style web services</li>
<li>User centric design, user experience design</li>
<li>Excellent communication &#38; presentation skills.</li>
</ul>
<p>If this position interests you, please send your resume, your hourly  rate, and your interview availability to <a href="mailto:raj@mindsource.com?subject=Senior Application Engineer - Communications">raj@mindsource.com</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Senior Software Application Engineer ]]></title>
<link>http://mindsourceinc.wordpress.com/2010/02/17/senior-software-application-engineer/</link>
<pubDate>Wed, 17 Feb 2010 23:19:11 +0000</pubDate>
<dc:creator>Michelle</dc:creator>
<guid>http://mindsourceinc.wordpress.com/2010/02/17/senior-software-application-engineer/</guid>
<description><![CDATA[Our client is looking for a SENIOR SOFTWARE APPLICATION ENGINEER . DESCRIPTION: Design, implement, a]]></description>
<content:encoded><![CDATA[<p>Our client is looking for a <strong>SENIOR SOFTWARE APPLICATION ENGINEER</strong> .</p>
<p><strong>DESCRIPTION:<br />
</strong></p>
<p>Design, implement, and support high quality, high performance consumer-facing software applications for web-connected devices. This role involves hands-on development and oversight of core components of the product, in collaboration with a software team that spans internal and external distributed development teams. Ideal candidates will have prior experience with both designing and implementing media frameworks and rich media user interface development.</p>
<ul>
<li>Analyze product definition and define software requirements within your domain. Consult with product management and architects to create an optimal design and plan for user interface and/or service components to meet an aggressive product schedule</li>
<li>Evaluate, integrate, and enhance 3<sup>rd</sup> party APIs and technologies, tailoring the provided functionality to meet the needs</li>
<li>Identify possible pitfalls and provide practical alternatives/solutions.</li>
</ul>
<p><strong>QUALIFICATIONS:<br />
</strong></p>
<p><strong>REQUIRED SKILLS AND EXPERIENCES</strong></p>
<ul>
<li>5+ years of experience developing complex Internet-connected entertainment applications in C/C++.</li>
<li>Significant, current experience developing consumer-facing UIs and designing and implementing underlying media APIs and frameworks</li>
<li>Development experience with scripting languages (e.g., Python, Lua, JavaScript, ActionScript)</li>
<li>Hands on development with software libraries and object systems (e.g., GLib, GObject, LibXML, libjpeg)</li>
<li>Experience designing and implementing complex data-driven systems, including optimizations.</li>
<li>Experience with development on Linux platforms, tool chains, and associated libraries</li>
<li>Must be able to work with project stakeholders to analyze, understand and implement user requirements.</li>
<li>Strong desire to work in a dynamic team environment, including oversight of remote development.</li>
<li>Strong desire to get &#8220;outside of the box&#8221; and explore solutions from a variety of perspectives and make appropriate technical tradeoffs.</li>
<li>Must work quickly, creatively &#38; decisively, delivering designs to suit product / project requirements</li>
</ul>
<p><strong>DESIRED SKILLS AND EXPERIENCES:</strong></p>
<ul>
<li>Experience with skinning applications on media frameworks and UI toolkits (e.g., XBMC)</li>
<li>Knowledge of email and messaging technologies (IMAP, POP3, MAPI)</li>
<li>Hands-on development experience with social networking APIs</li>
<li>Experience with SOAP/REST style web services</li>
<li>User centric design, user experience design</li>
<li>Excellent communication &#38; presentation skills.</li>
</ul>
<p>If this position interests you, please send your resume, your hourly rate, and your interview availability to <a href="mailto:kathy@mindsource.com?subject=Senior Software Application Engineer">kathy@mindsource.com</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Knight's Tour brute force algorithm example]]></title>
<link>http://sigquit.wordpress.com/2010/01/13/knights-tour-brute-force-algorithm-example/</link>
<pubDate>Tue, 12 Jan 2010 23:50:22 +0000</pubDate>
<dc:creator>aleksander</dc:creator>
<guid>http://sigquit.wordpress.com/2010/01/13/knights-tour-brute-force-algorithm-example/</guid>
<description><![CDATA[(From Wikipedia) The Knight&#8217;s Tour is a mathematical problem involving a knight on a chessboar]]></description>
<content:encoded><![CDATA[<blockquote><p> (From Wikipedia) <a href="http://en.wikipedia.org/wiki/Knight%27s_tour">The Knight&#8217;s Tour</a> is a mathematical problem involving a knight on a chessboard. The knight is placed on the empty board and, moving according to the rules of chess, must visit each square exactly once. A knight&#8217;s tour is called a closed tour if the knight ends on a square attacking the square from which it began (so that it may tour the board again immediately with the same path). Otherwise the tour is open. </p></blockquote>
<p>Just developed my brute-force algorithm implementation, using GLib and based on a simple recursive function.</p>
<p><a href="http://es.gnu.org/~aleksander/glib/knightstour-glib.c">Download and try it here!</a></p>
<p>As an example of result, this is the open Knight&#8217;s Tour found by the algorithm in a <strong>5&#215;5 board</strong>, starting from position [0,0]:<br />
[0,0][1,2][2,4][4,3][3,1][1,0][2,2][0,3][1,1][3,0][4,2][3,4][1,3][0,1][2,0][4,1][3,3][1,4][0,2][2,1][4,0][3,2][4,4][2,3][0,4]</p>
<p>And this one, the first Knight&#8217;s Tour found by the algorithm in a <strong>8&#215;8 board</strong>, starting from position [0,0]:<br />
[0,0][1,2][2,4][3,6][5,7][7,6][6,4][7,2][6,0][4,1][5,3][6,5][7,7][5,6][7,5][6,3][7,1][5,0][6,2][7,4][5,5][6,7][4,6][5,4][6,6][4,5][3,3][5,2][7,3][6,1][4,0][2,1][4,2][3,0][1,1][0,3][2,2][0,1][2,0][3,2][4,4][2,3][0,4][1,6][3,7][2,5][1,7][0,5][1,3][3,4][1,5][0,7][2,6][4,7][3,5][2,7][0,6][1,4][0,2][1,0][3,1][4,3][5,1][7,0]</p>
<p>Both examples above show <em>open</em> Knight&#8217;s Tours.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Single instance applications using D-Bus]]></title>
<link>http://sundaram.wordpress.com/2010/01/08/single-instance-apps-using-d-bus/</link>
<pubDate>Fri, 08 Jan 2010 10:36:55 +0000</pubDate>
<dc:creator>legends2k</dc:creator>
<guid>http://sundaram.wordpress.com/2010/01/08/single-instance-apps-using-d-bus/</guid>
<description><![CDATA[Many applications have a precondition that only one instance should run @ a given time for saner exe]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Many applications have a precondition that only one instance should run @ a given time for saner execution/integrity; any further invocations of the process&#8217; binary should just signal the primary (unique) instance that another new (duplicate) instance got invoked and should die out. This can be achieved using a lot of different techniques. Using D-Bus to do the same is one of the many possible methods. It is to be noted that you can do a lot more with D-Bus; this is just one of the many uses of D-Bus.</p>
<p style="text-align:justify;"><a href="http://www.freedesktop.org/wiki/Software/dbus">D-Bus</a> is a message passing system (IPC) that is light, fast and is now rapidly replacing its predecessors like <a href="http://en.wikipedia.org/wiki/DCOP">DCOP</a>. Messages between different processes travel in buses, the D-Bus daemon routes them. You can think of the system as a wheel with spokes attached; the daemon forms the crux/hub and the each spoke is a bus thru&#8217; which process&#8217; talk. D-Bus, now, is a part of all the Linux distributions I know. Reason is, many primary desktop applications/utilities of desktop environments like Gnome, KDE, Xfce, etc. use it under the hood. Enough theory, let&#8217;s get down to business <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Two parts of the problem are:</p>
<ol>
<li>Detecting if it&#8217;s the primary instance</li>
<li>Passing a message to the primary instance, if duplicate</li>
</ol>
<h2>Deducing the instance</h2>
<p style="text-align:justify;">Each process requests a bus to the D-Bus daemon thru&#8217; which it can pass its messages. This bus can be assigned a unique name. Once a unqiue name is granted, other requests, by different buses, to have the <em>same</em> name fails or is put in queue until the owner bus relinquishes / quits. Using this we can solve part one of the problem.</p>
<blockquote>
<pre><code>
// this header is a part of the dbus dev. headers
#include &#60;dbus/dbus.h&#62;

#define STR_UNIQUE_BUS_NAME		"some.bus_name.unique"

DBusConnection *bus = NULL;
DBusError err = {0};

bool is_primary_instance()
{
	int ret_code = 0;

	bus = dbus_bus_get(DBUS_BUS_SESSION, &#38;err);

	if(dbus_error_is_set(&#38;err))
		goto deal_with_error;

	printf("Bus obtained!\n");

	ret_code = dbus_bus_request_name(bus,
					STR_UNIQUE_BUS_NAME,
					DBUS_NAME_FLAG_DO_NOT_QUEUE,
					&#38;err);
	if(dbus_error_is_set(&#38;err))
		goto deal_with_error;

	if(DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER == ret_code)
		return true;

deal_with_error:
	if(dbus_error_is_set(&#38;err))
	{
		fprint(stderr, "D-Bus Error: %s\n", err.message);
		dbus_error_free(&#38;err);
	}

	return false;
}
</code></pre>
</blockquote>
<h2 style="text-align:justify;">Registering for signals</h2>
<p style="text-align:justify;">Now for part two of the solution: in case of a primary instance, we should register for a possible signal from our potential duplicates, with a set of rules; in case of a duplicate instance, it should send a signal to the D-Bus daemon, abiding by the rules set by the primary, so that the primary instance gets intimated of the signal, by the daemon.</p>
<blockquote>
<pre><code>#define STR_DUPLICATE_OBJECT_PATH	"/some/object/path"
#define STR_INTERFACE_DUPLICATE		"some.interfacename.duplicate"
#define STR_SIGNAL_NAME			"duplicate_instance_invoked"
#define STR_SIGNAL_MATCH_RULE		"type='signal',interface='some.interfacename.duplicate',path='/some/object/path'"

// function that registers with D-Bus for a message of type = signal
// and from interface named some.interfacename.duplicate
bool register_signal()
{
	dbus_bus_add_match(bus, STR_SIGNAL_MATCH_RULE, &#38;err);
	if(dbus_error_is_set(&#38;err))
	{
		fprint(stderr, "Error registering rule: %s\n", err.message);
		dbus_error_free(&#38;err);

		return false;
	}

	printf("Signal match rule added!!\n");

	//signal_sighter is our callback function which is called when a
	// signal comes from our duplicates

	return dbus_connection_add_filter(bus, signal_sighter, NULL, NULL);

}

// actual function that handles the signals from duplicates
DBusHandlerResult signal_sighter(DBusConnection *connection, DBusMessage *message, void *user_data)
{
	if(dbus_message_is_signal(message, STR_INTERFACE_DUPLICATE, STR_SIGNAL_NAME))
	{
		printf("Signal received!\n");
		return DBUS_HANDLER_RESULT_HANDLED;
	}

	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
</code></pre>
</blockquote>
<h2>Sending the signal</h2>
<p>In case of a duplicate instance, it should signal the primary instance that a duplicate was invoked.</p>
<blockquote>
<pre><code>void signal_primary()
{
	DBusMessage *mesg = NULL;

	mesg = dbus_message_new_signal(STR_DUPLICATE_OBJECT_PATH, STR_INTERFACE_DUPLICATE, STR_SIGNAL_NAME);
	dbus_connection_send(bus, mesg, NULL);

	dbus_message_unref(mesg);
	mesg = NULL;
}
</code></pre>
</blockquote>
<p><strong>Note:</strong> If you&#8217;re trying this out using Glib/GTK, that has a main loop like <em>g_main_run()</em> or <em>gtk_main()</em>, you need to add the following too:</p>
<blockquote>
<pre><code>// this header will be part of the dbus-glib dev. headers
#include &#60;dbus/dbus-glib-lowlevel.h&#62;

// add this line after the dbus_bus_get()
dbus_connection_setup_with_g_main(bus, NULL);
</code></pre>
</blockquote>
<p>Hope this helps! Do bug me for your queries. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>P.S.:</strong> One can argue that <a href="http://live.gnome.org/LibUnique">libunique</a> is a better choice for creating single instance apps., but the problem is <a href="http://use.perl.org/comments.pl?sid=42923&#38;cid=68619">libunique works only with GUI programs</a>, while this method works for both CLI and GUI programs. Also, libunique uses D-Bus under the hood <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[g_source_unref() and g_source_destroy() are your friends]]></title>
<link>http://sigquit.wordpress.com/2010/01/05/g_source_unref-and-g_source_destroy-are-your-friends/</link>
<pubDate>Tue, 05 Jan 2010 21:05:31 +0000</pubDate>
<dc:creator>aleksander</dc:creator>
<guid>http://sigquit.wordpress.com/2010/01/05/g_source_unref-and-g_source_destroy-are-your-friends/</guid>
<description><![CDATA[After almost 2 years developing GLib-based applications, I understood the proper way of using GSourc]]></description>
<content:encoded><![CDATA[<p>After almost 2 years developing GLib-based applications, I understood the proper way of using GSource objects. Yes, quite a shame, but better now than never.</p>
<p>Now, after re-reading carefully the <a href="http://library.gnome.org/devel/glib/unstable/">GLib Reference Manual</a>, I see that it is quite clearly explained the difference between <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-destroy">g_source_destroy()</a> and <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-unref">g_source_unref()</a>. So the typical suggestion is still the best one: <a href="http://en.wikipedia.org/wiki/Rtfm">RTFM!!</a></p>
<p>In our applications, we usually need to attach timeout operations to the context of an specific thread, not to the main thread context. Thus, we cannot use <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-timeout-add">g_timeout_add()</a> or the pretty new <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-timeout-add-seconds">g_timeout_add_seconds()</a>.</p>
<p>For example, you could create a GThreadPool, and in the function to be executed in each thread, you could create a specific context for the thread, plus a main loop in the context:</p>
<pre>
    /* Create a GLib Main Context */
    context = g_main_context_new();

    /* Create a Main Loop in the context*/
    main_loop = g_main_loop_new(context,
                                FALSE);
</pre>
<p>Once you have a new context and main loop, you can just create a new GSource, and attach it to the main loop. As soon as you create the GSource, its reference count is 1, and as soon as you attach it to the main loop, its reference count will be 2.</p>
<pre>
    /* Create new timeout source to be called
     * every 5 seconds.
     * Reference count of source is 1 once created */
    source = g_timeout_source_new(TIMEOUT_MSECS);

    /* Set callback to be called in each timeout */
    g_source_set_callback(source,
                          (GSourceFunc)__timeout_func,
                          main_loop,
                          NULL);

    /* Attach the GSource in the GMainContext.
     * Reference count of source is 2 after this call */
    g_source_attach(source,
                    context);
</pre>
<p>Of, course, you will be now running the main loop:</p>
<pre>
    /* Run the main loop, until it is stopped */
    g_main_loop_run(main_loop);
</pre>
<p>The key now is how to destroy the GSource properly. When calling <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-destroy">g_source_destroy()</a>, you are doing 2 things: first, telling the main loop to forget about the GSource; and second, decrementing the reference count of the GSource. Then, you still need to call <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-unref">g_source_unref()</a> to fully decrement the reference counter so that the GSource is disposed.</p>
<pre>
    /* We did an attach() with the GSource, so we need to
     * destroy() it */
    g_source_destroy(source);

    /* We need to unref() the GSource to end the last reference
     * we got */
    g_source_unref(source);
</pre>
<p>To end the example, once the main loop is stopped, you will also need to properly dispose the GMainContext and GMainLoop objects:</p>
<pre>
    /* The main loop should be destroyed before the context */
    g_main_loop_unref(main_loop);

    /* Finally, destroy the context */
    g_main_context_unref(context);
</pre>
<p>This is just one way of keeping the GSource references properly managed:</p>
<ol>
<li>You get one reference when you create the GSource</li>
<li>You get a new reference when you attach it in the context</li>
<li>You release one reference when you destroy it from the context</li>
<li>You release last reference when you unref the final one</li>
</ol>
<p>Of course, you could also choose to avoid storing the &#8220;extra&#8221; reference, and leave alive only the one inside the main context:</p>
<ol>
<li>You get one reference when you create the GSource</li>
<li>You get a new reference when you attach it in the context</li>
<li>You release one reference when you unref the the GSource &#8212;&#62; Now, the only reference is inside the GMainContext</li>
<li>You release last reference when you destroy it from the context</li>
</ol>
<p>You can check this simple example in the following program I prepared, released into public domain:<br />
<a href="http://es.gnu.org/~aleksander/glib/test-gsource.c">http://es.gnu.org/~aleksander/glib/test-gsource.c</a></p>
<p>Hope it helps someone out there to fully understand the difference between <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-destroy">g_source_destroy()</a> and <a href="http://library.gnome.org/devel/glib/unstable/glib-The-Main-Event-Loop.html#g-source-unref">g_source_unref()</a>.</p>
<p>As last comment&#8230; I would really rename the following functions in the library, so that no one else is confused with the &#8220;unref&#8221; and &#8220;destroy&#8221; terms:</p>
<ul>
<li>Rename <strong>g_source_attach()</strong> to <strong>g_source_attach_to_context()</strong></li>
<li>Rename <strong>g_source_destroy()</strong> to <strong>g_source_destroy_from_context()</strong></li>
</ul>
<p>The main reason is that these two operations actually act on the GMainContext, while the name of the functions do not suggest that fact.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The Frog, The Scorpion and The Philippines]]></title>
<link>http://edebreo.wordpress.com/2009/12/11/the-frog-the-scorpion-and-the-philippines/</link>
<pubDate>Fri, 11 Dec 2009 05:19:02 +0000</pubDate>
<dc:creator>edebreo</dc:creator>
<guid>http://edebreo.wordpress.com/2009/12/11/the-frog-the-scorpion-and-the-philippines/</guid>
<description><![CDATA[Have you heard the story? A scorpion wanted to cross a river but couldn&#8217;t because he can]]></description>
<content:encoded><![CDATA[Have you heard the story? A scorpion wanted to cross a river but couldn&#8217;t because he can]]></content:encoded>
</item>
<item>
<title><![CDATA[I stuck around St. Petersburg/When I saw it was time for a change]]></title>
<link>http://intheflatworld.wordpress.com/2009/11/01/i-stuck-around-st-petersburgwhen-i-saw-it-was-time-for-a-change/</link>
<pubDate>Sun, 01 Nov 2009 05:24:45 +0000</pubDate>
<dc:creator>intheflatworld</dc:creator>
<guid>http://intheflatworld.wordpress.com/2009/11/01/i-stuck-around-st-petersburgwhen-i-saw-it-was-time-for-a-change/</guid>
<description><![CDATA[Certain of the things that have happened to me in my thirtysomething years seem, when I look back on]]></description>
<content:encoded><![CDATA[<p>Certain of the things that have happened to me in my thirtysomething years seem, when I look back on them, impossibly fortunate. Not &#8220;almost impossibly fortunate,&#8221; as I almost wrote, but, literally, impossibly fortunate. I shake my head, and suppose they can only be explained in religious terms: I received a special blessing from God.</p>
<p>Then, when I finish shaking my head, I suppose I am not the only person who has thoughts like this. And I wonder how it came to pass that God, who didn&#8217;t stop this or that genocide, that God, who didn&#8217;t stop Lenin on his way to the Finland Station<em>,</em> decided to perform such and such miracle for me that night in Montana in July of 2000.</p>
<p>Caveat lector: I am, at least to a modest degree, inclined to be philosophical, but I am not inclined to read or study philosophy. And thus I do not have any idea how this question has played out in great minds through the ages. I can only give the conclusions I inevitably come to when my mind wanders this way. On the question of God, I conceive the following possibilities:</p>
<p>1. There is no God.<br />
2. God is not good.<br />
3. God is not competent.<br />
4. God&#8217;s principles are similar to those of the Chicago economists.</p>
<p>And that thing that happened in Montana? Was it just good luck?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[pygtk - Atualizar Barras de Progresso no meio da função (sem threads)]]></title>
<link>http://pythonlog.wordpress.com/?p=25</link>
<pubDate>Mon, 19 Oct 2009 23:49:47 +0000</pubDate>
<dc:creator>nosklo</dc:creator>
<guid>http://pythonlog.wordpress.com/?p=25</guid>
<description><![CDATA[&lt;kbum&gt; como eu poderia fazer uma barra de progresso que atualize de acordo com a execuçao de d]]></description>
<content:encoded><![CDATA[<pre>&#60;kbum&#62; como eu poderia fazer uma barra de progresso que atualize
de acordo com a execuçao de determinado trecho do codigo?
&#60;kbum&#62; nosklo, conhece alguma soluçao pra esse caso?
&#60;nosklo&#62; kbum: a barra de progresso nao atualiza sozinha.
vc precisa atualiza-la.
&#60;kbum&#62; certo
&#60;kbum&#62; eu to pensando numa forma de "atualiza-la"
&#60;kbum&#62; pq se fosse um laço eu atualizaria facil facil
&#60;kbum&#62; mas sao metodos que estao executando
&#60;epx&#62; é, atualizar andamento sempre eh chato
&#60;nosklo&#62; kbum: tem um jeito de facilitar usando geradores
&#60;nosklo&#62; kbum: xo fazer um exemplo
&#60;kbum&#62; nosklo, desculpa, mas tenho que sair agora, agradeço pela ajuda,
mas tenho que ir, se nao perco carona pra voltar pra cidade!
</pre>
<p>Bom, foi feito um exemplo e aqui está:</p>
<p><!--more-->Primeiro criei uma classe <span style="color:#0000FF;font-weight:bold;">GlibYield</span>. Ela simplesmente pega um iterável e agenda seu próximo passo usando glib.idle_add(). Criei três funções que servem de ganchos para subclasses desta classe.</p>
<p>A idéia aqui é que a função que está sendo monitorada será escrita com uma série de yields que a tornarão um gerador. Este gerador então será consumido a cada passo, e pode-se fazer qualquer coisa entre estes passos.</p>
<p>Na listagem abaixo, eu usei glib.timeout_add(1000, &#8230;) ao invés de glib.idle_add(&#8230;), para que demore mesmo um tempo entre cada passo. Ao usar em um caso real, <strong>troque pela linha glib.idle_add() comentada</strong>.</p>
<pre><span style="color:#008000;font-weight:bold;">import</span> <span style="color:#0000FF;font-weight:bold;">pygtk</span>
pygtk<span style="color:#666666;">.</span>require(<span style="color:#BA2121;">'2.0'</span>)
<span style="color:#008000;font-weight:bold;">import</span> <span style="color:#0000FF;font-weight:bold;">gtk</span>
<span style="color:#008000;font-weight:bold;">import</span> <span style="color:#0000FF;font-weight:bold;">glib</span>

<span style="color:#008000;font-weight:bold;">class</span> <span style="color:#0000FF;font-weight:bold;">GlibYield</span>(<span style="color:#008000;">object</span>):
    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">__call__</span>(<span style="color:#008000;">self</span>, iterable, <span style="color:#666666;">*</span>args, <span style="color:#666666;">**</span>kwds):
        obj <span style="color:#666666;">=</span> <span style="color:#008000;">self</span><span style="color:#666666;">.</span>before_start(<span style="color:#666666;">*</span>args, <span style="color:#666666;">**</span>kwds)
        glib<span style="color:#666666;">.</span>timeout_add(<span style="color:#666666;">1000</span>, <span style="color:#008000;">self</span><span style="color:#666666;">.</span>step, <span style="color:#008000;">iter</span>(iterable), obj)
<span style="color:#408080;font-style:italic;">#        glib.idle_add(self.step, iter(iterator), obj)</span>

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">step</span>(<span style="color:#008000;">self</span>, iterator, obj):
        <span style="color:#008000;font-weight:bold;">try</span>:
            data <span style="color:#666666;">=</span> <span style="color:#008000;">next</span>(iterator)
        <span style="color:#008000;font-weight:bold;">except</span> <span style="color:#D2413A;font-weight:bold;">StopIteration</span>:
            <span style="color:#008000;">self</span><span style="color:#666666;">.</span>on_end(obj)
        <span style="color:#008000;font-weight:bold;">else</span>:
            obj <span style="color:#666666;">=</span> <span style="color:#008000;">self</span><span style="color:#666666;">.</span>on_step(data, obj)
            glib<span style="color:#666666;">.</span>timeout_add(<span style="color:#666666;">1000</span>, <span style="color:#008000;">self</span><span style="color:#666666;">.</span>step, iterator, obj)
<span style="color:#408080;font-style:italic;">#            glib.idle_add(self.step, iterator, obj)</span>
        <span style="color:#008000;font-weight:bold;">return</span> <span style="color:#008000;">False</span>

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">before_start</span>(<span style="color:#008000;">self</span>, <span style="color:#666666;">*</span>args, <span style="color:#666666;">**</span>kwds): <span style="color:#008000;font-weight:bold;">pass</span>
    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">on_step</span>(<span style="color:#008000;">self</span>, data, monitor_obj): <span style="color:#008000;font-weight:bold;">pass</span>
    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">on_end</span>(<span style="color:#008000;">self</span>, monitor_obj):  <span style="color:#008000;font-weight:bold;">pass</span>
</pre>
<p>Criei então uma subclasse de GlibYield que cria uma barra de progresso em um certo container (que você passa como parâmetro) e a atualiza com os valores que vem da função sendo executada:</p>
<pre><span style="color:#008000;font-weight:bold;">class</span> <span style="color:#0000FF;font-weight:bold;">GtkProgressCreator</span>(GlibYield):
    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">__init__</span>(<span style="color:#008000;">self</span>, container):
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>_container <span style="color:#666666;">=</span> container

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">before_start</span>(<span style="color:#008000;">self</span>, title<span style="color:#666666;">=</span><span style="color:#BA2121;">'Aguarde...'</span>):
        pb <span style="color:#666666;">=</span> gtk<span style="color:#666666;">.</span>ProgressBar()
        <span style="color:#008000;font-weight:bold;">if</span> title:
            pb<span style="color:#666666;">.</span>set_text(title)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>_container<span style="color:#666666;">.</span>pack_start(pb, <span style="color:#008000;">True</span>, <span style="color:#008000;">True</span>, <span style="color:#666666;">0</span>) <span style="color:#408080;font-style:italic;"># TODO: incluir formas de customizar isso</span>
        pb<span style="color:#666666;">.</span>show()
        <span style="color:#008000;font-weight:bold;">return</span> pb

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">on_step</span>(<span style="color:#008000;">self</span>, data, pb):
        pb<span style="color:#666666;">.</span>set_fraction(data)
        <span style="color:#008000;font-weight:bold;">return</span> pb

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">on_end</span>(<span style="color:#008000;">self</span>, pb):
        pb<span style="color:#666666;">.</span>destroy()
</pre>
<p>Aqui temos um exemplo da utilização da classe. O método calcula() é uma função geradora. Ao clicar no botão, ele é executado, criando um objeto gerador, que é passado para o GtkProgressCreator. Este então cria uma barra de progresso, e a atualiza toda vez que o gerador dá um yield, reagendando o próximo passo pela glib.</p>
<pre><span style="color:#008000;font-weight:bold;">class</span> <span style="color:#0000FF;font-weight:bold;">TestStep</span>(<span style="color:#008000;">object</span>):
    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">clicou</span>(<span style="color:#008000;">self</span>, widget, data):
        <span style="color:#008000;font-weight:bold;">print</span> <span style="color:#BA2121;">"Calculando..."</span>
        <span style="color:#408080;font-style:italic;"># Executa a funcao no GtkProgressCreator</span>
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>pc(<span style="color:#008000;">self</span><span style="color:#666666;">.</span>calcula(<span style="color:#666666;">15</span>, <span style="color:#666666;">14</span>, <span style="color:#666666;">5</span>))

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">calcula</span>(<span style="color:#008000;">self</span>, n1, n2, n3):
        r <span style="color:#666666;">=</span> n1 <span style="color:#666666;">+</span> n2
        <span style="color:#008000;font-weight:bold;">yield</span> <span style="color:#666666;">0.25</span> <span style="color:#408080;font-style:italic;">#cada yield atualiza a barra de progresso e libera a GUI</span>

        r <span style="color:#666666;">=</span> r <span style="color:#666666;">*</span> n3
        <span style="color:#008000;font-weight:bold;">print</span> <span style="color:#BA2121;">'Estamos na metade...'</span>
        <span style="color:#008000;font-weight:bold;">yield</span> <span style="color:#666666;">0.5</span>

        r <span style="color:#666666;">=</span> r <span style="color:#666666;">/</span> n1
        <span style="color:#008000;font-weight:bold;">yield</span> <span style="color:#666666;">0.75</span>

        r <span style="color:#666666;">=</span> r <span style="color:#666666;">^</span> n2
        <span style="color:#008000;font-weight:bold;">yield</span> <span style="color:#666666;">1</span>

        <span style="color:#008000;font-weight:bold;">print</span> <span style="color:#BA2121;">'RESULTADO ENCONTRADO: '</span>, r

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">delete_event</span>(<span style="color:#008000;">self</span>, widget, event, data<span style="color:#666666;">=</span><span style="color:#008000;">None</span>):
        gtk<span style="color:#666666;">.</span>main_quit()
        <span style="color:#008000;font-weight:bold;">return</span> <span style="color:#008000;">False</span>

    <span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">__init__</span>(<span style="color:#008000;">self</span>):
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window <span style="color:#666666;">=</span> gtk<span style="color:#666666;">.</span>Window(gtk<span style="color:#666666;">.</span>WINDOW_TOPLEVEL)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window<span style="color:#666666;">.</span>set_title(<span style="color:#BA2121;">"Teste de Step!"</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window<span style="color:#666666;">.</span>connect(<span style="color:#BA2121;">"delete_event"</span>, <span style="color:#008000;">self</span><span style="color:#666666;">.</span>delete_event)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window<span style="color:#666666;">.</span>set_border_width(<span style="color:#666666;">10</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>box1 <span style="color:#666666;">=</span> gtk<span style="color:#666666;">.</span>VBox(<span style="color:#008000;">False</span>, <span style="color:#666666;">0</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window<span style="color:#666666;">.</span>add(<span style="color:#008000;">self</span><span style="color:#666666;">.</span>box1)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>button1 <span style="color:#666666;">=</span> gtk<span style="color:#666666;">.</span>Button(<span style="color:#BA2121;">"Calcular"</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>button1<span style="color:#666666;">.</span>connect(<span style="color:#BA2121;">"clicked"</span>, <span style="color:#008000;">self</span><span style="color:#666666;">.</span>clicou, <span style="color:#666666;">1</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>box1<span style="color:#666666;">.</span>pack_start(<span style="color:#008000;">self</span><span style="color:#666666;">.</span>button1, <span style="color:#008000;">True</span>, <span style="color:#008000;">True</span>, <span style="color:#666666;">0</span>)
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>button1<span style="color:#666666;">.</span>show()
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>box1<span style="color:#666666;">.</span>show()
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>window<span style="color:#666666;">.</span>show()

        <span style="color:#408080;font-style:italic;"># Cria um progresscreator que criara barras de progresso em box1</span>
        <span style="color:#008000;">self</span><span style="color:#666666;">.</span>pc <span style="color:#666666;">=</span> GtkProgressCreator(<span style="color:#008000;">self</span><span style="color:#666666;">.</span>box1)

<span style="color:#008000;font-weight:bold;">def</span> <span style="color:#0000FF;">main</span>():
    gtk<span style="color:#666666;">.</span>main()

<span style="color:#008000;font-weight:bold;">if</span> __name__ <span style="color:#666666;">==</span> <span style="color:#BA2121;">"__main__"</span>:
    s <span style="color:#666666;">=</span> TestStep()
    main()
</pre>
<p>Existem alguns problemas com esta implementação &#8211; A principal é que ela não é boa com operações que duram muito tempo entre os yields, pois a GUI ficará travada nestes pontos. Nestes casos demorados, a operação geralmente depende de fatores externos &#8211; leitura de arquivos, acesso de rede &#8211; e aí o melhor seria utilizar as funções corretas da glib para eses casos (glib.io_add_watch). O gerador então poderia até injetar os resultados de cada chamada destas de volta na função através do <a href="http://docs.python.org/reference/expressions.html#generator.send" rel="nofollow">http://docs.python.org/reference/expressions.html#generator.send</a> ; Até pensei em escrever algo assim e atualizar depois o post.</p>
<p>Porém eu desisti. Porque melhor que tudo isso é usar twisted com um reactor GTK. Twisted possui deferreds &#8211; na verdade este código acima foi inspirado no <a href="http://twistedmatrix.com/documents/current/api/twisted.internet.defer.html#inlineCallbacks" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.internet.defer.html#inlineCallbacks</a> e é uma &#8220;versão pobre&#8221; deste esquema.</p>
<p>Mesmo assim foi divertido escrevê-la, e funciona! Veja como ficou ao clicar 4 vezes no botão rapidamente:</p>
<div id="attachment_29" class="wp-caption aligncenter" style="width: 180px"><img class="size-full wp-image-29" title="Janela do TesteStep" src="http://pythonlog.files.wordpress.com/2009/10/testestep.jpg?w=170&#038;h=151" alt="4 barras de progresso atualizadas independentemente" width="170" height="151" /><p class="wp-caption-text">4 barras de progresso atualizadas independentemente</p></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Barneys, Bergdorf and Armani]]></title>
<link>http://intheflatworld.wordpress.com/2009/09/21/barneys-bergdorf-and-armani/</link>
<pubDate>Mon, 21 Sep 2009 12:58:44 +0000</pubDate>
<dc:creator>intheflatworld</dc:creator>
<guid>http://intheflatworld.wordpress.com/2009/09/21/barneys-bergdorf-and-armani/</guid>
<description><![CDATA[In yesterday&#8217;s Fashion and Style in the New York Times there was a touching and interesting st]]></description>
<content:encoded><![CDATA[<p>In yesterday&#8217;s Fashion and Style in the New York Times there was a <a href="http://www.nytimes.com/2009/09/20/fashion/20genb.html?ref=fashion&#38;pagewanted=print">touching and interesting story</a> about a designer of cosmetics packaging who lost the job he had had with Estée Lauder for twenty years, and then found and lost two other jobs, and finally, in March, died from an overdose of antidepressants.</p>
<p>From the article:</p>
<blockquote><p>He loved museums, architecture, reading, first edition books, the theater, seeing four movies in one day with his friend Annette Williams; the clothes at Barneys, Bergdorf and Armani; cosmetics counters, face creams, spas, manicures and pedicures; travel; five-star hotels; Swiss Style design; Helvetica typeface; the simple beauty of a straight, clean line&#8230;</p>
<p>As his first lover and lifelong best friend, Wesley Mancini, a fabric designer, said, “His 40s were definitely the best decade of his life.” He was making a (low) six-figure salary at Lauder, and in 2001, moved from an Upper East Side studio to a one-bedroom in the heart of Chelsea’s gay community. He supported the <a title="More articles about Gay Men's Health Crisis" href="http://topics.nytimes.com/top/reference/timestopics/organizations/g/gay_mens_health_crisis/index.html?inline=nyt-org">Gay Men’s Health Crisis</a>, marched yearly in the AIDS walks and volunteered to deliver food to a senior center in the West Village.</p>
<p>People lose jobs all the time and don’t kill themselves. Why Steven Schnipper? Scott [his brother], who’s now 51 and an editor at Bloomberg News, said he knew that Steven was depressed and was seeing a therapist, but didn’t understand he suffered major depression. “I think it was masked by his work and income and the prestige of the jobs at the cosmetics companies. This stripped away his protective layer. Steven couldn’t think straight.”</p></blockquote>
<p>And then, at the end of the article:</p>
<blockquote><p>For a while they worried how to explain the suicide to Adam [the nephew of the deceased], but then they decided the easiest way was to tell him the truth: Uncle Steven died of a disease called depression.</p></blockquote>
<p>Is this true? Did he die of depression? He certainly had a lot to be depressed about! I can imagine Samuel Johnson declaring that he died from vanity and love of luxury, and even if I&#8217;m not inclined to make such a harsh judgment myself, still I think it&#8217;s strange to say he died from depression.</p>
<p>Would depression have killed him if he hadn&#8217;t gotten laid off? If not, then wouldn&#8217;t it be better to say that he died because he lost his job? The article says, &#8220;people lose jobs all the time and don&#8217;t kill themselves,&#8221; and of course that&#8217;s true, but it&#8217;s also true that while most people who are struck by lightning—or bitten by a black widow spider—live, we still say that those who die, die from lightning strike or spider bite.</p>
<p>Layoffs, lightning strikes, spider bites—all of these things can be fatal, if the circumstances are right. As every twelve-year-old boy obsessed with venomous creatures knows, black widow venom can kill children and the elderly, but not healthy adults.</p>
<p>With layoffs the situation is reversed: it&#8217;s healthy adults who are most vulnerable, especially those with no dependents, those whose sense of worth is connected to professional achievments, those for whom luxury has become necessity, and those who are, to put it bluntly, post-Christian.</p>
<p>It is very possible that, far from being unable to &#8220;think straight,&#8221; Uncle Steven knew just what he was doing.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Bush and Obama]]></title>
<link>http://intheflatworld.wordpress.com/2009/08/28/bush-and-obama/</link>
<pubDate>Fri, 28 Aug 2009 12:41:25 +0000</pubDate>
<dc:creator>intheflatworld</dc:creator>
<guid>http://intheflatworld.wordpress.com/2009/08/28/bush-and-obama/</guid>
<description><![CDATA[Before the world turned upside down, George W. Bush was mostly interested in domestic issues. And he]]></description>
<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-310" title="gwbyale" src="http://intheflatworld.files.wordpress.com/2009/08/gwbyale2.jpg?w=300&#038;h=300" alt="gwbyale" width="300" height="300" /><br />
Before the world turned upside down, George W. Bush was mostly interested in domestic issues. And he wasn&#8217;t even very interested in those. He saw his duty as President as similar to the cheerleading he had done at Andover and Yale. He gave people nicknames, told them, &#8220;Way to go, Kenny Boy,&#8221; and encouraged Americans to go about their business, business. And, of course, he was in favor of education.</p>
<p>An agenda of no-agenda is singularly easy for a president to enact. Any other kind of agenda is going to be much more difficult. Bush was set for four, or possibly even eight, comfortable years of steady hand on the tiller.</p>
<p>But then the world turned upside down, and Bush discovered his real vocation. And however one may view the agenda he subsequently developed, it so happened that he was able to accomplish a good deal of it.</p>
<p>How did he do it? How can a president do anything?</p>
<p>The answer to that is: for the last fifty years or so the  president hasn&#8217;t been able to do much at all, at least not at home.  He is like Gulliver in Lilliput (and Lilliput, of course, is Congress).</p>
<p>What presidents accomplish, what presidents are remembered for, is what they do abroad. A president tries to enact a domestic agenda at his own peril. The USA belongs to the Senators and Representatives. Basically, it belongs to the lobbies.</p>
<p>I&#8217;m not trying to make a conspiracy theory. A lot of lobbies work against one another, and a lot of them represent not the interests of a few but the interests of many (for example, the largest lobby of all, which is not the AARP or the NRA or even the AFL-CIA &#8212; that&#8217;s a joke; see Whit Stillman&#8217;s <a href="http://en.wikipedia.org/wiki/Barcelona_(film)">Barcelona</a>  &#8212; is the lobby of drivers, so strong it needn&#8217;t even be organized).</p>
<p>Compared to what he&#8217;s up against at home, abroad the president practically has a free hand, and how much more true is this in a time of crisis. Congress still has to approve the budget, but when the Gulliver in the White House has a flag wrapped around him, toga-like, all of the Lilliputians scurry off to look for their own little togas.</p>
<p>The lesson for Obama? You shouldn&#8217;t have bothered. One way or another we seem to be coming out of our recession. Whether or not you are responsible for this, your reward will be no reward at all.</p>
<p>Abroad, you&#8217;re doing your best to fulfill Bush&#8217;s goals in Iraq and Afghanistan. (Of course this is the right thing to do!) And since his goals require the full capacity of our armed forces, you&#8217;re not exactly in a position to develop any geopolitical goals of your own.</p>
<p>At home, well, you&#8217;ll always have Ms. Sotomayor.</p>
]]></content:encoded>
</item>

</channel>
</rss>
