<?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>Kellbot! &#187; Programming</title>
	<atom:link href="http://www.kellbot.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kellbot.com</link>
	<description>Tinysaurs and Hacking and Nonsense</description>
	<lastBuildDate>Sat, 07 Jan 2012 19:49:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Bit Depth Problems with RMagick / ImageMagick</title>
		<link>http://www.kellbot.com/2011/02/bit-depth-problems-with-rmagick-imagemagick/</link>
		<comments>http://www.kellbot.com/2011/02/bit-depth-problems-with-rmagick-imagemagick/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 23:44:15 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[black]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[imagemagick]]></category>
		<category><![CDATA[rmagick]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=816</guid>
		<description><![CDATA[I just spent the entire afternoon debugging a problem I couldn't find elsewhere, so I'm documenting it in the off chance someone else runs into the evil thing.

I'm composing some images on the fly using ImageMagick via RMagic. It grabs one file, floods the image with a given color, and layers another on top ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>I just spent the entire afternoon debugging a problem I couldn&#8217;t find elsewhere, so I&#8217;m documenting it in the off chance someone else runs into the evil thing.</p>
<p>I&#8217;m composing some images on the fly using ImageMagick via RMagic. It grabs one file, floods the image with a given color, and layers another on top of it. Locally, it works great, and gives me &#8220;body parts&#8221; like this one:</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/hair.png"><img class="aligncenter size-full wp-image-817" title="hair" src="http://www.kellbot.com/wp-content/uploads/hair.png" alt="" width="130" height="91" /></a>Unfortunately, when I push the code to Heroku, it starts going through a goth phase and filling everything in with BLACK LIKE SOUL:<br />
<a href="http://www.kellbot.com/wp-content/uploads/black_hair.png"><img class="aligncenter size-full wp-image-818" title="black_hair" src="http://www.kellbot.com/wp-content/uploads/black_hair.png" alt="" width="130" height="91" /></a>I spent a very, very long time trying to suss this one out, checking out everything from opacity to gem versions. Finally, I checked the ImageMagick version (Magick::Magick_version).<br />
Local: &#8220;ImageMagick 6.6.7-1 2011-02-08 Q8 http://www.imagemagick.org&#8221;<br />
Heroku: &#8220;ImageMagick 6.6.0-4 2010-06-01 Q16 http://www.imagemagick.org&#8221;</p>
<p>Ok, so Heroku&#8217;s is a bit older. But that&#8217;s not the critical issue. The bigger problem is the Q16, which is reporting the quantum depth. I don&#8217;t understand nearly enough about image processing to talk about what that really means. But long story short, it means my images had different default bit depths and it was causing everything to blow up. Or something.</p>
<p>I was able to fix it by changing how I instantiated the Pixel for the fill. Before, I was using</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">fill_image.<span style="color:#9900CC;">colorize</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">1</span>,<span style="color:#6666ff; font-weight:bold;">Magick::Pixel</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>r,g,b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>where r, g, and b are integers between 0 and 255.</p>
<p>Conveniently, RMagick has added a from_color method to Pixel, which lets you define a pixel based on a color name. I passed in a hex value, and everything magic(k)ally works normally again:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">color = <span style="color:#996600;">'#ababab'</span>
fill_color = <span style="color:#6666ff; font-weight:bold;">Magick::Pixel</span>.<span style="color:#9900CC;">from_color</span><span style="color:#006600; font-weight:bold;">&#40;</span>color.<span style="color:#9900CC;">upcase</span><span style="color:#006600; font-weight:bold;">&#41;</span>
fill_image = fill_image.<span style="color:#9900CC;">colorize</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">1</span>,fill_color<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>I wish I understood a few more of the particulars about what is really going on here. But for the time being I need to move on to finishing this up. Any insight is welcome in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2011/02/bit-depth-problems-with-rmagick-imagemagick/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>LEGO plans, now with better rendering</title>
		<link>http://www.kellbot.com/2010/11/lego-plans-now-with-better-rendering/</link>
		<comments>http://www.kellbot.com/2010/11/lego-plans-now-with-better-rendering/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 14:19:49 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[LEGO]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=776</guid>
		<description><![CDATA[You may remember the "Legoizer" script I've been working on for Blender. It uses an existing script and one I've created to generate "layers" of LEGO patterns for building.

I got a lot of great suggestions on my last entry for how to automate the process of taking a screenshot, but sadly when it came ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>You may remember the <a href="http://www.kellbot.com/2010/06/more-legos-from-3d-meshes/">&#8220;Legoizer&#8221; script I&#8217;ve been working on for Blender</a>. It uses an existing script and one I&#8217;ve created to generate &#8220;layers&#8221; of LEGO patterns for building.</p>
<p>I got a lot of great suggestions on my last entry for how to automate the process of taking a screenshot, but sadly when it came down to implementing them things didn&#8217;t go so well. Luckily Angelo from <a href="http://abandonhopegames.com/">Abandon Hope Games</a> was kind enough to take the time to help me get the environmentals in Blender set up just right for rendering a &#8220;pattern slice.&#8221;</p>
<p><strong>Step 0: Start with an object made of objects</strong><br />
The AddCells script uses DupliVerts to create an object made of references to another object. We&#8217;ll get to that in a minute, but first, let&#8217;s assume you have an object:<br />
<a href="http://www.kellbot.com/wp-content/uploads/step0.jpg"><img class="aligncenter size-medium wp-image-777" title="step0" src="http://www.kellbot.com/wp-content/uploads/step0-300x200.jpg" alt="" width="300" height="200" /></a></p>
<p><strong>Step 1: Set up the camera</strong><br />
We want the camera to be facing down and rendering orthographic(all lines parallel) rather than perspective.</p>
<p>Make sure you&#8217;re in Object Mode and select the camera.<br />
Press Alt+G and then Alt+R (confirming the dialogs) to return it to the origin.<br />
Hit F9 to get into the Editing panel<br />
Click the button labeled Orthographic in the Camera tab</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/Step1.jpg"><img class="aligncenter size-medium wp-image-778" title="Step1" src="http://www.kellbot.com/wp-content/uploads/Step1-300x64.jpg" alt="" width="300" height="64" /></a></p>
<p>Press 1 on your number pad to get a side view of the scene. Click the blue transform handle of your camera and move it up along the Z axis so it is well above your object.<br />
Press 0 on your number pad and you should see a rectangular bounding box around your object (or perhaps around nothing) which represents the are which the camera sees.<br />
Scroll the &#8220;lens&#8221; option right above the Orthographic button to zoom in/out so your</p>
<p>If you do a test render now with F12, you&#8217;ll probably see a badly lit (perhaps almost all black) render of your object from the top down.</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/Step1test.jpg"><img class="aligncenter size-medium wp-image-779" title="Step1test" src="http://www.kellbot.com/wp-content/uploads/Step1test-300x225.jpg" alt="" width="300" height="225" /></a><strong>Step 2: Set up the lighting</strong></p>
<p>Select the existing light in your scene and press x on your keyboard to delete it.<br />
Press space bar to bring up a dialog, and go to Add &gt; Lamp &gt; Sun<br />
It doesn&#8217;t matter where the lamp is, as long as it&#8217;s facing down (which it is by default).</p>
<p><strong>Step 3: Configure your materials</strong></p>
<p>I mentioned earlier that our object was made up of DupliVerts.<br />
These aren&#8217;t &#8220;real&#8221; objects, which is why I had such trouble applying materials to them. You need to apply the material to the reference object, which is generally somewhere in the middle of it. I usually do this by switching to the Outliner menu and finding the source cube manually.</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/Step3.jpg"><img class="aligncenter size-medium wp-image-780" title="Step3" src="http://www.kellbot.com/wp-content/uploads/Step3-300x48.jpg" alt="" width="300" height="48" /></a>Once we have our source object selected, hit F5 to bring up the Shading panel and click Add New under Links and Pipeline.<br />
Pick a new color for your object. This will be the color of the lines in your final rendered image, so pick something that contrasts with your background color (which defaults to blue).<br />
Click the Wire button under Links and Pipeline</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/Step4.jpg"><img class="aligncenter size-medium wp-image-781" title="Step4" src="http://www.kellbot.com/wp-content/uploads/Step4-300x64.jpg" alt="" width="300" height="64" /></a>Your object in the viewport should take on the color you&#8217;ve selected. If if doesn&#8217;t, you probably didn&#8217;t select the correct source object.</p>
<p>Hit F12 to render. Viola!</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/StepGrid.jpg"><img class="aligncenter size-medium wp-image-782" title="StepGrid" src="http://www.kellbot.com/wp-content/uploads/StepGrid-300x225.jpg" alt="" width="300" height="225" /></a>Now that we have our environment set up the way we want, rendering via script is easy. I&#8217;ve updated the <a href="https://gist.github.com/720578">script source</a> (now on gist) to call Render when it&#8217;s done slicing and save the file to my hard drive.</p>
<p>This all works great, but of course there&#8217;s a new problem. Since we want to iterate over the entire object, I need to &#8220;reset&#8221; it back to being whole again. While I&#8217;ve saved an undo point I don&#8217;t think you can call that point via the API. In the current iteration of the script I save the vectors of each vertex before deleting it and then call verts.extend to add them back. This works great except&#8230;</p>
<p>The vectors for the verticies are transformed to be in the selected object&#8217;s local space, which is necessary for &#8220;layer 1&#8243; to be the first layer of the object and so forth. Unfortunately I<strong> haven&#8217;t yet figured out how to transform those verticies back.</strong> So when I run the script it dutifully reassembles my sphere originating from the center of the object. So there&#8217;s still some work to be done there.</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/Oops.jpg"><img class="aligncenter size-medium wp-image-783" title="Oops" src="http://www.kellbot.com/wp-content/uploads/Oops-300x132.jpg" alt="Yaaaay... oh." width="300" height="132" /></a></p>
<p><script src="https://gist.github.com/720578.js"> </script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/11/lego-plans-now-with-better-rendering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Faking Blog Integration With XMLRPC and Ruby</title>
		<link>http://www.kellbot.com/2010/11/faking-blog-integration-with-xmlrpc-and-ruby/</link>
		<comments>http://www.kellbot.com/2010/11/faking-blog-integration-with-xmlrpc-and-ruby/#comments</comments>
		<pubDate>Tue, 02 Nov 2010 02:24:18 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tech]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=763</guid>
		<description><![CDATA[I'm rebuilding indiecraftshows.com in RoR, but the blog will stay on Wordpress. The rails app will be hosted on Heroku, and the blog will stay where it is at NearlyFreeSpeech.net. There's one catch: I want the latest blog post to appear on the home page, which is part of the rails app.



To do this ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>I&#8217;m rebuilding <a href="http://www.indiecraftshows.com">indiecraftshows.com</a> in RoR, but the blog will stay on WordPress. The rails app will be hosted on <a href="http://www.heroku.com">Heroku</a>, and the blog will stay where it is at <a href="http://www.nearlyfreespeech.net">NearlyFreeSpeech.net</a>. There&#8217;s one catch: I want the latest blog post to appear on the home page, which is part of the rails app.</p>
<p><a href="http://www.kellbot.com/wp-content/uploads/mega.jpg"><img src="http://www.kellbot.com/wp-content/uploads/mega-300x264.jpg" alt="" title="mega" width="300" height="264" class="aligncenter size-medium wp-image-765" /></a></p>
<p>To do this I&#8217;m using ruby&#8217;s included XMLRPC library to grab the latest post from WordPress and shove it into a YAML file named with the date and post ID. This happens in a cron job run daily. Since I only care about showing the most recent post, I don&#8217;t bother to check to see if there are other posts I don&#8217;t have.</p>
<p>I created a really simple object called (creatively) BlogPost, and chucked it in with the rest of my models in app/models. Note that BlogPost doesn&#8217;t inherit from ActiveRecord.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'xmlrpc/client'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> BlogPost
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">latest</span>
    <span style="color:#CC00FF; font-weight:bold;">Dir</span>.<span style="color:#9900CC;">chdir</span><span style="color:#006600; font-weight:bold;">&#40;</span>Rails.<span style="color:#9900CC;">root</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'blog'</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    post_files = <span style="color:#CC00FF; font-weight:bold;">Dir</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;*.yaml&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
    most_recent_file = post_files.<span style="color:#9900CC;">sort</span>.<span style="color:#9900CC;">last</span>
    <span style="color:#CC00FF; font-weight:bold;">YAML</span>::<span style="color:#CC0066; font-weight:bold;">load</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span>most_recent_file<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">fetch</span>
    server = <span style="color:#6666ff; font-weight:bold;">XMLRPC::Client</span>.<span style="color:#9900CC;">new2</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'http://www.kellbot.com/xmlrpc.php'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
&nbsp;
    blog_post = result = server.<span style="color:#9900CC;">call</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;metaWeblog.getRecentPosts&quot;</span>,<span style="color:#006666;">1</span>,YOUR USERNAME HERE,YOUR PASSWORD HERE,<span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span>Rails.<span style="color:#9900CC;">root</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'blog'</span>,<span style="color:#996600;">&quot;#{blog_post[0][&quot;</span>dateCreated<span style="color:#996600;">&quot;].to_time.to_i}-#{blog_post[0][&quot;</span>postid<span style="color:#996600;">&quot;]}.yaml&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>,<span style="color:#996600;">'w'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>io<span style="color:#006600; font-weight:bold;">|</span>
      <span style="color:#008000; font-style:italic;">#we only want the published ones</span>
      <span style="color:#CC00FF; font-weight:bold;">YAML</span>.<span style="color:#9900CC;">dump</span><span style="color:#006600; font-weight:bold;">&#40;</span>blog_post<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span>, io<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">if</span> blog_post<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;post_status&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span> == <span style="color:#996600;">&quot;publish&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>When the home page is called, the controller grabs the most recent yaml file (by name, not by time of creation, since WordPress allows you to lie about time). I just use the XMLRPC object as-is, but if I wanted to I could get fancy and do some post-processing to make it a little more friendly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/11/faking-blog-integration-with-xmlrpc-and-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fixed: WordPress MU Uploaded Image Display Issues</title>
		<link>http://www.kellbot.com/2010/06/fixed-wordpress-mu-uploaded-image-display-issues/</link>
		<comments>http://www.kellbot.com/2010/06/fixed-wordpress-mu-uploaded-image-display-issues/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 18:20:22 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[incorrect path]]></category>
		<category><![CDATA[missing images]]></category>
		<category><![CDATA[safe mode]]></category>
		<category><![CDATA[safe_mode]]></category>
		<category><![CDATA[wordpress mu]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=629</guid>
		<description><![CDATA[Just a quick fix for something I couldn't find earlier:

If you're on shared hosting which has PHP's safe_mode enabled, you may run into problems with uploading images. Specifically, you can upload images just fine (assuming you've configured uploads correctly) but can't see uploaded files. This is the case on NearlyFreeSpeech.Net (where my sites are ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>Just a quick fix for something I couldn&#8217;t find earlier:</p>
<p>If you&#8217;re on shared hosting which has PHP&#8217;s safe_mode enabled, you may run into problems with uploading images. Specifically, you can upload images just fine (assuming you&#8217;ve configured uploads correctly) but can&#8217;t see uploaded files. This is the case on NearlyFreeSpeech.Net (where my sites are hosted), and probably a few other hosts as well.</p>
<p>WordPress MU uses some .htaccess &#038; PHP tomfoolery to obfuscate the real file path (among other things). Because safe_mode checks to see if the UID/GUIDs match on file_exists(), the script that fetches the images will fail and return a 404. Which is to say, the owner/group of the uploaded file is web/web (or whatever your server&#8217;s web user is), but since I manually uploaded the WPMU files originally, those are me/me. Since me != web, it failed. WordPress took this to mean the file was absent and returned 404.</p>
<p>On NearlyFreeSpeech, adding wp-content/blogs.php to the &#8216;web&#8217; group was all it needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/06/fixed-wordpress-mu-uploaded-image-display-issues/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extracting + Graphing Wii Fit data</title>
		<link>http://www.kellbot.com/2010/05/extracting-graphing-wii-fit-data/</link>
		<comments>http://www.kellbot.com/2010/05/extracting-graphing-wii-fit-data/#comments</comments>
		<pubDate>Thu, 13 May 2010 20:31:35 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[wii]]></category>
		<category><![CDATA[WiiFit]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=609</guid>
		<description><![CDATA[

In preparation to tinker with the miCoach data, I started with some better-travelled exercise bits: WiiFit body test data. Starting with Jansen Price's excellent blog post on the subject, I slowly worked through the data and wrote a python script to interpret the binaries and save them to a CSV. By using the excellent ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p><a href="http://www.kellbot.com/wp-content/uploads/WiiFitdata.jpg"><img class="aligncenter size-full wp-image-610" title="WiiFitdata" src="http://www.kellbot.com/wp-content/uploads/WiiFitdata.jpg" alt="" width="616" height="329" /></a></p>
<p>In preparation to tinker with the miCoach data, I started with some better-travelled exercise bits: WiiFit body test data. Starting with Jansen Price&#8217;s <a href="http://jansenprice.com/blog?id=9-Extracting-Data-from-Wii-Fit-Plus-Savegame-Files">excellent blog post on the subject</a>, I slowly worked through the data and wrote a python script to interpret the binaries and save them to a CSV. By using the excellent flot javascript library, I was able to generate the nice graph above. There was a lot of trial and error, but here&#8217;s an overview of the process:</p>
<ol>
<li>Copy Wii save game data to the SD card. This is done from <strong>Wii Options</strong> &gt; <strong>Data              Management</strong> &gt; <strong>Save Data</strong> &gt; <strong>Wii</strong></li>
<li>Find the save game data on the card. It&#8217;s in something like &#8216;private/wii/title/RFPE&#8217;, although different regions may have slightly different codes. RFPE is the code for WiiFit Plus. Copy the WiiFit data.bin file from the SD card to your local machine.</li>
<li>Decrypt data.bin. This is explained pretty well <a href="http://jansenprice.com/blog?id=9-Extracting-Data-from-Wii-Fit-Plus-Savegame-Files">here</a>. To create the keys I ended up creating text files with the hex string for each and then using &#8220;xxd -r -p sd_iv_hex sd_iv&#8221; et al to save a binary version. If you&#8217;re getting &#8220;MD5 mismatch&#8221; errors, you probably saved the keys incorrectly. If you aren&#8217;t sure, check the file size. They should be 16 bytes each.</li>
<li>Run the decrypted RPHealth.dat through a parser (I wrote one in Python for this)</li>
<li>Run the CSV through your favorite graph generation library. I use <a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;ved=0CBYQFjAA&amp;url=http%3A%2F%2Fcode.google.com%2Fp%2Fflot%2F&amp;ei=i17sS76fNoL-8AaY8Z2EBQ&amp;usg=AFQjCNHH828GR4jYTW24KE8RKUO0IqllvQ&amp;sig2=ZBXS47RapZbG2kNvbNZw8A">flot</a> because Google Charts don&#8217;t handle dates very well.</li>
</ol>
<p>Thanks to Jansen&#8217;s handy chart of which bits are where, writing the parser was pretty easy. This isn&#8217;t the most elegant code I&#8217;ve ever written, but it gets the job done:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">struct</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">string</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">csv</span>
&nbsp;
&nbsp;
mii = <span style="color: #ff4500;">0</span>
<span style="color: #808080; font-style: italic;">#we know that each record is 0x9271 bytes long</span>
record_length = 0x9281
&nbsp;
record_start = <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#path to WiiFit data file</span>
infile = <span style="color: #483d8b;">'RPHealth.dat'</span>
&nbsp;
FH = <span style="color: #008000;">open</span><span style="color: black;">&#40;</span>infile, <span style="color: #483d8b;">'rb'</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">;</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">## It loops through 7 profiles, because I happen to know I have 7.</span>
<span style="color: #808080; font-style: italic;">## A better approach would be to go to the end of the file, of course.</span>
<span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: black;">&#40;</span>mii <span style="color: #66cc66;">&lt;</span> <span style="color: #ff4500;">7</span><span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #808080; font-style: italic;">#go to the start of the current record</span>
    FH.<span style="color: black;">seek</span><span style="color: black;">&#40;</span>record_start<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#read the first 30 bytes (header + name)</span>
    line = FH.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">30</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#for some reason names are stored as N a m e instead of Name.</span>
    <span style="color: #808080; font-style: italic;">#Throw away the header any extranous spaces</span>
    data = <span style="color: #dc143c;">struct</span>.<span style="color: black;">unpack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&lt;9xcxcxcxcxcxcxcxcxcxcxc&quot;</span>,line<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#Condense our unpacked characters into a string</span>
    wf_name = <span style="color: #dc143c;">string</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>data,<span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#open a new CSV file for this person.</span>
    <span style="color: #808080; font-style: italic;">#If the name is shorter than 4 characters or has whitespace, the script</span>
    <span style="color: #808080; font-style: italic;">#will exit. This should probably be fixed.</span>
    FW = <span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'WiiFit_'</span>+wf_name<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span>:<span style="color: #ff4500;">4</span><span style="color: black;">&#93;</span>+<span style="color: #483d8b;">'.csv'</span>, <span style="color: #483d8b;">'w'</span><span style="color: black;">&#41;</span>
    recordWriter = <span style="color: #dc143c;">csv</span>.<span style="color: black;">writer</span><span style="color: black;">&#40;</span>FW, delimiter=<span style="color: #483d8b;">&quot;,&quot;</span>, quotechar=<span style="color: #483d8b;">&quot;'&quot;</span>, quoting=<span style="color: #dc143c;">csv</span>.<span style="color: black;">QUOTE_MINIMAL</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#Weigh-in data starts 0x38a1 bytes into the record</span>
    FH.<span style="color: black;">seek</span><span style="color: black;">&#40;</span>record_start + 0x38a1<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#we'll loop through the record data until it starts coming up blank</span>
    <span style="color: #ff7700;font-weight:bold;">while</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;">#4 byte date </span>
        line = FH.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span>
        data = <span style="color: #dc143c;">struct</span>.<span style="color: black;">unpack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&gt;i&quot;</span>,line<span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;">#bit shift to get the month, day, and year. Could also get time if you wanted.</span>
        year = data<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">&gt;&gt;</span> <span style="color: #ff4500;">20</span> <span style="color: #66cc66;">&amp;</span> 0x7ff
        month = data<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">&gt;&gt;</span> <span style="color: #ff4500;">16</span> <span style="color: #66cc66;">&amp;</span> 0xf
        day = data<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">&gt;&gt;</span> <span style="color: #ff4500;">11</span> <span style="color: #66cc66;">&amp;</span> 0x1f
&nbsp;
        <span style="color: #808080; font-style: italic;">#break the loop if the date comes back 0</span>
        <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span>year == <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>: <span style="color: #ff7700;font-weight:bold;">break</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">#format the date into something humans like to read</span>
        date = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span>year<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> + <span style="color: #483d8b;">'-'</span> + <span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span>month<span style="color: black;">&#41;</span>+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> + <span style="color: #483d8b;">'-'</span> + <span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span>day<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">#the next three sets of 2 byte data represent weight, BMI, and balance</span>
        line = FH.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">17</span><span style="color: black;">&#41;</span>
        data = <span style="color: #dc143c;">struct</span>.<span style="color: black;">unpack</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&gt;3H&quot;</span>,line<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span>:<span style="color: #ff4500;">6</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
        recordWriter.<span style="color: black;">writerow</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>date<span style="color: black;">&#93;</span> + <span style="color: black;">&#91;</span>data<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span> + <span style="color: black;">&#91;</span>data<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span> + <span style="color: black;">&#91;</span>data<span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
    <span style="color: #808080; font-style: italic;">#now that we're done with the record, advance to the start of the next one</span>
    record_start = record_start + record_length
&nbsp;
    mii = mii+<span style="color: #ff4500;">1</span></pre></div></div>

<p>You can download a copy of it <a href="http://www.kellbot.com/code/WiiFit/wiiFitParser.txt">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/05/extracting-graphing-wii-fit-data/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Importing Data from Magento to PrestaShop</title>
		<link>http://www.kellbot.com/2010/04/importing-data-from-magento-to-prestashop/</link>
		<comments>http://www.kellbot.com/2010/04/importing-data-from-magento-to-prestashop/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 23:48:17 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=588</guid>
		<description><![CDATA[Today I gave up on Magento. It's a powerful piece of software but it's still pretty rough around the edges, and the UI and architecture makes it a pain to dive in and debug if something goes wrong. It's built on Zend, so someone who has spent more time with Zend than I have ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>Today I gave up on Magento. It&#8217;s a powerful piece of software but it&#8217;s still pretty rough around the edges, and the UI and architecture makes it a pain to dive in and debug if something goes wrong. It&#8217;s built on Zend, so someone who has spent more time with Zend than I have would probably have an easier go of it.</p>
<p>Anyway, I&#8217;m moving over to PrestaShop, and don&#8217;t want to lose all my customer and order information. Since I managed to trash my Magento installation, I&#8217;m migrating the data over manually via an exciting series of MySQL queries. I&#8217;m posting them here in case anyone else needs them.</p>
<p>This data is then imported into PrestaShop using the built in import tool. They have a fairly easy to use interface for assigning columns in the CSV to various PrestaShop information (name, address, etc).</p>
<p>Getting the customer&#8217;s ID, name, and email address:</p>

<div class="wp_syntax"><div class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">DISTINCT</span> ce.entity_id <span style="color: #990099; font-weight: bold;">AS</span> b<span style="color: #000033;">,</span> email<span style="color: #000033;">,</span> <span style="color: #008000;">'default<span style="color: #008080; font-weight: bold;">_</span>password'</span><span style="color: #000033;">,</span> <span style="color: #FF00FF;">&#40;</span>
&nbsp;
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_entity_varchar
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">7</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> customer_entity_varchar.entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> l_name<span style="color: #000033;">,</span> <span style="color: #FF00FF;">&#40;</span>
&nbsp;
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_entity_varchar
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">5</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> customer_entity_varchar.entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> f_name<span style="color: #000033;">,</span> <span style="color: #008080;">1</span>
<span style="color: #990099; font-weight: bold;">FROM</span> <span style="color: #008000;">`customer<span style="color: #008080; font-weight: bold;">_</span>entity`</span> <span style="color: #990099; font-weight: bold;">AS</span> ce
<span style="color: #990099; font-weight: bold;">JOIN</span> customer_entity_varchar <span style="color: #990099; font-weight: bold;">AS</span> cev <span style="color: #990099; font-weight: bold;">ON</span> ce.entity_id <span style="color: #CC0099;">=</span> cev.entity_id
<span style="color: #990099; font-weight: bold;">WHERE</span> <span style="color: #008080;">1</span></pre></div></div>

<p>You&#8217;ll notice I select the string &#8216;default_password&#8217;. This is just to generate a column of dummy password data. I haven&#8217;t thought of any creative ways to migrate the password data, and instead am just resetting it. The downside is that users will have to request a new password in order to log in. You should not use default_password as the actual string, for reasons I hope are obvious.</p>
<p>Get the address books:</p>

<div class="wp_syntax"><div class="code"><pre class="mysql" style="font-family:monospace;"> <span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">DISTINCT</span> <span style="color: #008000;">'Home'</span><span style="color: #000033;">,</span> cae.entity_id <span style="color: #990099; font-weight: bold;">AS</span> b<span style="color: #000033;">,</span> 
&nbsp;
<span style="color: #FF00FF;">&#40;</span><span style="color: #990099; font-weight: bold;">select</span> email <span style="color: #990099; font-weight: bold;">from</span> customer_entity <span style="color: #990099; font-weight: bold;">where</span> entity_id <span style="color: #CC0099;">=</span> parent_id<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">as</span> email<span style="color: #000033;">,</span>
&nbsp;
 <span style="color: #FF00FF;">&#40;</span>
<span style="color: #990099; font-weight: bold;">SELECT</span> code
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_int <span style="color: #990099; font-weight: bold;">as</span> mm1 <span style="color: #990099; font-weight: bold;">join</span> directory_country_region <span style="color: #990099; font-weight: bold;">as</span> mm2 <span style="color: #990099; font-weight: bold;">on</span> mm1.<span style="color: #990099; font-weight: bold;">value</span> <span style="color: #CC0099;">=</span> mm2.region_id
<span style="color: #990099; font-weight: bold;">WHERE</span> mm1.attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">27</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> mm1.entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> state<span style="color: #000033;">,</span>
<span style="color: #FF00FF;">&#40;</span>
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_varchar 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">25</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> country<span style="color: #000033;">,</span> 
<span style="color: #FF00FF;">&#40;</span>
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_varchar 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">24</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> city<span style="color: #000033;">,</span>
<span style="color: #FF00FF;">&#40;</span>
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_varchar 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">18</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> f_name<span style="color: #000033;">,</span>
<span style="color: #FF00FF;">&#40;</span>
<span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_varchar 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">20</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> l_name<span style="color: #000033;">,</span>
<span style="color: #FF00FF;">&#40;</span><span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_text 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">23</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> addre1<span style="color: #000033;">,</span>
<span style="color: #FF00FF;">&#40;</span><span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #990099; font-weight: bold;">value</span>
<span style="color: #990099; font-weight: bold;">FROM</span> customer_address_entity_varchar 
<span style="color: #990099; font-weight: bold;">WHERE</span> attribute_id <span style="color: #CC0099;">=</span><span style="color: #008080;">28</span>
<span style="color: #CC0099; font-weight: bold;">AND</span> entity_id <span style="color: #CC0099;">=</span> b
<span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">AS</span> postcode
&nbsp;
<span style="color: #990099; font-weight: bold;">FROM</span> <span style="color: #008000;">`customer<span style="color: #008080; font-weight: bold;">_</span>address<span style="color: #008080; font-weight: bold;">_</span>entity`</span> <span style="color: #990099; font-weight: bold;">AS</span> cae
<span style="color: #990099; font-weight: bold;">JOIN</span> customer_address_entity_varchar <span style="color: #990099; font-weight: bold;">AS</span> caev <span style="color: #990099; font-weight: bold;">ON</span> cae.entity_id <span style="color: #CC0099;">=</span> caev.entity_id
<span style="color: #990099; font-weight: bold;">WHERE</span> <span style="color: #008080;">1</span></pre></div></div>

<p>Getting the order data over is another beast, one which I&#8217;ll tackle another day. There&#8217;s a convenient importer for products, but unfortunately the individual order data will have to be migrated painfully via SQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/04/importing-data-from-magento-to-prestashop/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tutorial: Writing a TCP server in Python</title>
		<link>http://www.kellbot.com/2010/02/tutorial-writing-a-tcp-server-in-python/</link>
		<comments>http://www.kellbot.com/2010/02/tutorial-writing-a-tcp-server-in-python/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 23:10:18 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[socket programming]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=532</guid>
		<description><![CDATA[During the last 12 hours of the hackathon I decided to write a TCP server for an old project I want to finally finish. I decided to write it in Python, mostly because my friend Adam likes Python and Adam would inevitably be the one answering my questions when I got stuck. I should ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>During the last 12 hours of the hackathon I decided to write a TCP server for an old project I want to finally finish. I decided to write it in Python, mostly because my friend Adam likes Python and Adam would inevitably be the one answering my questions when I got stuck. I should mention that prior to yesterday evening I knew nothing about socket programing. And I only had a vague idea of what threading was.</p>
<p>Since not everyone has friends like Adam, I&#8217;m writing up my findings in a tutorial.</p>
<p><em>Note: A bug in my CSS is causing the code blocks to show up extra wide. I&#8217;ll fix it once I&#8217;m back home from the hackathon</em></p>
<p><strong>Understanding Sockets</strong></p>
<p>First, I&#8217;m going to assume you understand that this is not a tutorial about writing an HTTP server. Instead this server will take connections from clients and keep them open to pass data back and forth until one side decides to close the connection. By keeping the connection open we eliminate the need to constantly poll the server for updates.</p>
<p><a href="http://www.amk.ca/python/howto/sockets/">Socket Programming HOWTO</a> provides a broad overview of sockets and is a good starting place.</p>
<p><strong>Python&#8217;s Socket Library</strong></p>
<p>Luckily python has an easy to use library. Like other libraries, we import it with thusly:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">socket</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span></pre></div></div>

<p>Many of the socket methods you&#8217;ll use are pretty self explanatory:<br />
<code>socket.listen()</code> &#8211; listens for incoming connections<br />
<code>socket.accept()</code> &#8211; accepts an incoming connection<br />
<code>socket.recv()</code> &#8211; returns incoming data as a string<br />
<code>socket.send()</code> &#8211; sends data to client socket*<br />
<code>socket.close()</code> &#8211; closes the socket</p>
<p>*in this context the &#8216;client socket&#8217; can be on either the server or client side. When a client connects to a server, the server creates a new client socket on its end. The two clients, one on each end, communicate with each other while the server socket remains open for incoming connections. This becomes more clear as you work with socket connections.</p>
<p><strong>Writing the server</strong><br />
First thing&#8217;s first, we need to establish our server socket:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">##server.py</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">socket</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>      <span style="color: #808080; font-style: italic;">#import the socket library</span>
&nbsp;
<span style="color: #808080; font-style: italic;">##let's set up some constants</span>
HOST = <span style="color: #483d8b;">''</span>    <span style="color: #808080; font-style: italic;">#we are the host</span>
PORT = <span style="color: #ff4500;">29876</span>    <span style="color: #808080; font-style: italic;">#arbitrary port not currently in use</span>
ADDR = <span style="color: black;">&#40;</span>HOST,PORT<span style="color: black;">&#41;</span>    <span style="color: #808080; font-style: italic;">#we need a tuple for the address</span>
BUFSIZE = <span style="color: #ff4500;">4096</span>    <span style="color: #808080; font-style: italic;">#reasonably sized buffer for data</span>
&nbsp;
<span style="color: #808080; font-style: italic;">## now we create a new socket object (serv)</span>
<span style="color: #808080; font-style: italic;">## see the python docs for more information on the socket types/flags</span>
serv = <span style="color: #dc143c;">socket</span><span style="color: black;">&#40;</span> AF_INET,SOCK_STREAM<span style="color: black;">&#41;</span>    
&nbsp;
<span style="color: #808080; font-style: italic;">##bind our socket to the address</span>
serv.<span style="color: black;">bind</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>ADDR<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>    <span style="color: #808080; font-style: italic;">#the double parens are to create a tuple with one element</span>
serv.<span style="color: black;">listen</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>    <span style="color: #808080; font-style: italic;">#5 is the maximum number of queued connections we'll allow</span></pre></td></tr></table></div>

<p>So now we have a server that&#8217;s listening for a connection. Or at least we did until the script reached the end and terminated, but we&#8217;ll get to that in a bit. Let&#8217;s leave our server hanging and jump to our client software. </p>
<p><strong>Creating the client</strong><br />
 Start a new python script for the client. We&#8217;ll need many of the same constants from the server, but our host will be &#8216;localhost&#8217;. For now we&#8217;ll be running both the server and the client on the same machine.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">##client.py</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">socket</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
HOST = <span style="color: #483d8b;">'localhost'</span>
PORT = <span style="color: #ff4500;">29876</span>    <span style="color: #808080; font-style: italic;">#our port from before</span>
ADDR = <span style="color: black;">&#40;</span>HOST,PORT<span style="color: black;">&#41;</span>
BUFSIZE = <span style="color: #ff4500;">4096</span>
&nbsp;
cli = <span style="color: #dc143c;">socket</span><span style="color: black;">&#40;</span> AF_INET,SOCK_STREAM<span style="color: black;">&#41;</span>
cli.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>ADDR<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Notice that we&#8217;re creating another socket object on this end but instead of binding and listening, we&#8217;re using the <code>connect()</code> method to connect to our server.</p>
<p>So what happens if we run our server and then run our client? Well, not much. While our server starts to listen, it then hits the end of the script. We need it to instead wait until it accepts a connection and then do something with that connection.<br />
<code>socket.accept()</code> does just that, and returns two things: a new client socket and the address bound to the socket on the other end. Once we have that, we can send data!</p>
<p>Continuing on server.py:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="python" style="font-family:monospace;">serv = <span style="color: #dc143c;">socket</span><span style="color: black;">&#40;</span> AF_INET,SOCK_STREAM<span style="color: black;">&#41;</span>    
&nbsp;
<span style="color: #808080; font-style: italic;">##bind our socket to the address</span>
serv.<span style="color: black;">bind</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>ADDR<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>    <span style="color: #808080; font-style: italic;">#the double parens are to create a tuple with one element</span>
serv.<span style="color: black;">listen</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>    <span style="color: #808080; font-style: italic;">#5 is the maximum number of queued connections we'll allow</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'listening...'</span>
&nbsp;
conn,addr = serv.<span style="color: black;">accept</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;">#accept the connection</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'...connected!'</span>
conn.<span style="color: black;">send</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'TEST'</span><span style="color: black;">&#41;</span>
&nbsp;
conn.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>The last step is to jump back over to our client and tell our client to expect to receive data:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="python" style="font-family:monospace;">cli = <span style="color: #dc143c;">socket</span><span style="color: black;">&#40;</span> AF_INET,SOCK_STREAM<span style="color: black;">&#41;</span>
cli.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>ADDR<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
data = cli.<span style="color: black;">recv</span><span style="color: black;">&#40;</span>BUFSIZE<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> data
&nbsp;
cli.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Now when you run your server it will wait until a client connects. Once you run your client it will connect and receive a short message (the word &#8220;TEST&#8221; in this case) and print it to the screen. If you wanted to you could have the client send a response, using the same <code>send()</code> and <code>recv()</code> methods (but reversed).</p>
<p>Make sure you <code>close()</code> your connections when you&#8217;re done using them. If you don&#8217;t close things nicely they have a nasty habit of staying bound/connected until you forcibly kill the python process. This can be a real pain when you&#8217;re debugging.</p>
<p>By itself this isn&#8217;t particularly useful, especially considering we can only handle one connection at a time and exit once it&#8217;s closed. By adding a few while loops and some threading we can make this into something much more valuable. As it is, I&#8217;m pretty wiped from the hackathon, so the threading tutorial will have to wait until another day. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2010/02/tutorial-writing-a-tcp-server-in-python/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Etsy API Fail &#8211; Well, Ok maybe not.</title>
		<link>http://www.kellbot.com/2009/11/api-fail/</link>
		<comments>http://www.kellbot.com/2009/11/api-fail/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 05:53:27 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[Etsy]]></category>
		<category><![CDATA[fail]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=446</guid>
		<description><![CDATA[I'm working on a new project which uses Etsy's API. As far as APIs go, theirs is pretty neutered. There's no user authentication whatsoever so the only data you can get from it is what's available to the general public. Since you can't authenticate, you certainly can't write any data, so things like allowing ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>I&#8217;m working on a new project which uses <a href="http://developer.etsy.com">Etsy&#8217;s API</a>. As far as APIs go, theirs is pretty neutered. There&#8217;s no user authentication whatsoever so the only data you can get from it is what&#8217;s available to the general public. Since you can&#8217;t authenticate, you certainly can&#8217;t write any data, so things like allowing users to add Etsy items to their favorites aren&#8217;t possible.</p>
<p>Working with their API I found another &#8220;quirk.&#8221; If you try to getUserDetails on a username which doesn&#8217;t exist it won&#8217;t return null or false or an empty object. Instead, it responds with HTTP status code 404.</p>
<p>Wait, what?</p>
<p>This means I have no way of differentiating between an error in my URI and a simple case of a defunct username. In fact, this behavior is contrary to what Etsy&#8217;s own documentation suggests. Their sample code dies on any status besides 200, which makes sense although you&#8217;d probably want to handle the error more gracefully. Now I have to look up the status code and try to guess whether I got the 404 because of a malformed URI or because the username was wrong. That will make debugging super fun!</p>
<p>404 is an HTTP error. A correctly formed API query with a null result should not return a 404. Argh. In english terms, a 404 means &#8220;I don&#8217;t have the information you&#8217;re looking for.&#8221;</p>
<p>You could argue that Etsy simply doesn&#8217;t have the userinfo for that user, because it doesn&#8217;t exist, and therefore 404 is appropriate. But that&#8217;s a cop out. Etsy DOES know that user&#8217;s info: it&#8217;s empty. If I&#8217;m querying a database of all known users, and getting back a subset of said users based on my input, Etsy&#8217;s response should be &#8220;there aren&#8217;t any matching users&#8221; not &#8220;I don&#8217;t have that information.&#8221; A 204 error would be more appropriate.</p>
<p>Edit: Apparently this is becoming a common thing.  Although I haven&#8217;t seen it with any other APIs I&#8217;ve worked with. And let me state for the record that just because other people do it doesn&#8217;t make me think it&#8217;s any less of a dumb idea.</p>
<p>Edit again: Someone who is less sleep deprived than myself pointed out that the body of the 404 responses does contain useful information, which I had missed earlier. So in this case I will concede to being wrong, although I am still not a fan of this approach because it means my script relies on the exact English wording of their error messages. Carry on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2009/11/api-fail/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Most Useful CS Classes?</title>
		<link>http://www.kellbot.com/2009/11/most-useful-cs-classes/</link>
		<comments>http://www.kellbot.com/2009/11/most-useful-cs-classes/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 22:51:29 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=409</guid>
		<description><![CDATA[One thing that's clear about my quest for higher education is that I'm going to need some undergraduate level classes to fill in the holes of my self-taught education. I've been looking through course catalogs for various programs to get an idea of what I'm missing, but it's hard to tell what would be ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p>One thing that&#8217;s clear about my quest for higher education is that I&#8217;m going to need some undergraduate level classes to fill in the holes of my self-taught education. I&#8217;ve been looking through course catalogs for various programs to get an idea of what I&#8217;m missing, but it&#8217;s hard to tell what would be valuable and what&#8217;s just filler.</p>
<p>For folks who got an undergraduate degree in computer science, what classes / topics did you actually find useful? I know I need to brush up on my math, I haven&#8217;t done anything resembling a proof in about a decade. Most of the programming I&#8217;ve done has been for the web. Lots of figuring out when to access and how to store various bits of data, but not much recursion. I&#8217;m used to speed being a factor of how often you hit the database, not how you&#8217;re manipulating the data.</p>
<p>I&#8217;ve found a community college locally where I can pick up some classes on the cheap, including one called &#8220;Language Independent Design Tools&#8221; which covers problem solving techniques, modular design, how to perform a proper trace, subroutines, etc. It could be either really useful or entirely too general, it&#8217;s hard to tell from the course description. It requires &#8220;Intro to C#&#8221; as a co requisite, which sounds like a lot of &#8220;this is a variable, this is a function.&#8221; Bleh.</p>
<p>Speaking of classes!</p>
<p>I&#8217;m teaching <a href="http://beginning-php.eventbrite.com/">Intro to PHP</a> at NYC Resistor in December. It covers the basics of the language, and doesn&#8217;t require any previous programming experience. Working knowledge of HTML is a big help, but not strictly required. You can <a href="http://beginning-php.eventbrite.com/">sign up online</a>, the class is taught at the NYCR Hackerspace in Brooklyn.</p>
<p>I&#8217;m thinking of teaching the GD image class again, because it&#8217;s fun to draw graphs and calculate resizing, shifts, etc. But the last one wasn&#8217;t very well attended so I&#8217;m not sure.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2009/11/most-useful-cs-classes/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Android: Hello Circle</title>
		<link>http://www.kellbot.com/2009/06/android-hello-circle/</link>
		<comments>http://www.kellbot.com/2009/06/android-hello-circle/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 20:36:54 +0000</pubDate>
		<dc:creator>Kellbot</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[circle]]></category>
		<category><![CDATA[draw]]></category>
		<category><![CDATA[hello world]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.kellbot.com/?p=347</guid>
		<description><![CDATA[Note: This article is pretty long in the tooth, and refers to a version of Android that is at least two versions old, and likely many more. I haven't gone back to update things to see what works and what doesn't. A few people have posted solutions in the comments so if you're running ...]]></description>
			<content:encoded><![CDATA[<p class="wp-flattr-button"></p><p><strong>Note: This article is pretty long in the tooth, and refers to a version of Android that is at least two versions old, and likely many more. I haven&#8217;t gone back to update things to see what works and what doesn&#8217;t. A few people have posted solutions in the comments so if you&#8217;re running into issues try skimming those first.</strong></p>
<p>I&#8217;ve been a little frustrated by the lack of Android tutorials. I got a <a href="http://developer.android.com/guide/tutorials/hello-world.html">Hello world</a> going, and found that most of the few tutorials I could find were WAY more complicated than what I want to start with. GPS, map overlays, to-do lists, etc, which is great and all but I want to start simple and work up from that. So I set out to build &#8220;Hello Circle,&#8221; a program which drew a dot on the screen wherever you touched it.</p>
<p>After about 12 hours of beating my head against Eclipse, the <a href="http://developer.android.com/sdk/1.5_r2/installing.html">Android SDK</a>, and the frequently incorrect Android documentation I got it working. So here&#8217;s a tutorial.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-7712738862644990";
/* BloggityBlog */
google_ad_slot = "5984804773";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p><strong>Setting up the environment</strong></p>
<p>I&#8217;m going to assume you already successfully completed the Hello World tutorial. Which means you&#8217;ve got yourself an IDE (probably Eclipse), the Android SDK, and the ADK (Android Development Kit) which is a plugin for Eclipse to help keep things in order. If  you haven&#8217;t done that yet follow <a href="http://developer.android.com/sdk/1.5_r2/installing.html">these instructions</a> and pray everything works as planned. I&#8217;ll see you in a few hours.</p>
<p>Create a project just like you did for Hello World.</p>
<p><strong>Creating the ViewGroup</strong></p>
<p>In order for anything to display on the screen you need to create a view. In the Hello World tutorial you created a TextView. We&#8217;re going to use the XML setup for creating our view, and rather than creating a TextView we&#8217;re going to use a FrameLayout, which is acutlaly a view group.</p>
<p>Open up /res/layout/main.xml and plop in this fine code (obliterating anything that may be there):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;FrameLayout</span> <span style="color: #000066;">android:id</span>=<span style="color: #ff0000;">&quot;@+id/main_view&quot;</span></span>
<span style="color: #009900;">  <span style="color: #000066;">xmlns:android</span>=<span style="color: #ff0000;">&quot;http://schemas.android.com/apk/res/android&quot;</span></span>
<span style="color: #009900;">  <span style="color: #000066;">android:layout_width</span>=<span style="color: #ff0000;">&quot;fill_parent&quot;</span></span>
<span style="color: #009900;">  <span style="color: #000066;">android:layout_height</span>=<span style="color: #ff0000;">&quot;fill_parent&quot;</span></span>
<span style="color: #009900;">  <span style="color: #000066;">android:background</span>=<span style="color: #ff0000;">&quot;#FF66FF33&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></td></tr></table></div>

<p>This, when it&#8217;s called in our code, will create a FrameLayout view with an id of &#8220;main view,&#8221; a width/height that fills the screen, and a neon green background. The hex color code for the background includes the alpha channel (the first to FFs).</p>
<p><strong>Setting the contentView to our XML</strong></p>
<p>Head over to your main class and call setContentView on your layout. Your code should look something vaguely like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.app.Activity</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.os.Bundle</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> RoboTown <span style="color: #000000; font-weight: bold;">extends</span> Activity <span style="color: #009900;">&#123;</span>
    <span style="color: #008000; font-style: italic; font-weight: bold;">/** Called when the activity is first created. */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> onCreate<span style="color: #009900;">&#40;</span>Bundle savedInstanceState<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">onCreate</span><span style="color: #009900;">&#40;</span>savedInstanceState<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setContentView<span style="color: #009900;">&#40;</span>R.<span style="color: #006633;">layout</span>.<span style="color: #006633;">main</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>If you run your code at this point you should get a big green background which does nothing. Hooray!</p>
<p><strong>Creating the Ball class</strong></p>
<p>Now we want to create a circle. Actually we want to create a lot of circles. So the first step is to create a new class called Ball. Right click on your project&#8217;s main class in the Package Explorer (on the left) and click New &gt; Class. Give it the name Ball and click Finish.</p>
<p>Our ball is actually going to be another view. What? Yeah. It&#8217;s a view. All of our Ball views will eventually go into our FrameLayout, but we&#8217;ll worry about that later.</p>
<p>So first, modify your Ball class so that it extends View, since it&#8217;s a new type of View, and while you&#8217;re at it go ahead and import some of the things we&#8217;ll need for drawing:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.content.Context</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.graphics.Canvas</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.graphics.Paint</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">android.view.View</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Ball <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">View</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In order to draw a ball we need a handful of things: a Canvas to draw them on, x and y coordinates to place the center of the ball, the radius, and Paint to give it color. So we&#8217;ll start by establishing those (I hid the imports for the sake of clarity, you should leave yours there):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>6
7
8
9
10
11
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Ball <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">View</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">float</span> x<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">float</span> y<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> r<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Paint</span> mPaint <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Paint</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Paint</span>.<span style="color: #006633;">ANTI_ALIAS_FLAG</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In the last line we create a new Paint object, creatively called mPaint. A Paint contains information like colors, text sizes, etc, which affect the appearance of the drawing. So far we haven&#8217;t assigned any of those things to the Paint, we&#8217;ve just created it.</p>
<p>Now we need to write the Ball constructor, which is the method to be called whenever we create a new ball:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> r<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Paint</span> mPaint <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span>    <span style="color: #003399;">Paint</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Paint</span>.<span style="color: #006633;">ANTI_ALIAS_FLAG</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #003399;">Context</span> context, <span style="color: #000066; font-weight: bold;">float</span> x, <span style="color: #000066; font-weight: bold;">float</span> y, <span style="color: #000066; font-weight: bold;">int</span> r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        mPaint.<span style="color: #006633;">setColor</span><span style="color: #009900;">&#40;</span>0xFFFF0000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">x</span> <span style="color: #339933;">=</span> x<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">y</span> <span style="color: #339933;">=</span> y<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">r</span> <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Our constructor takes a Context, x, y, and radius r. We pass these arguments in when we instantiate the object and assign them to the object properties.</p>
<p>And lastly, the method which actually draws the circle, onDraw:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #003399;">Context</span> context, <span style="color: #000066; font-weight: bold;">float</span> x, <span style="color: #000066; font-weight: bold;">float</span> y, <span style="color: #000066; font-weight: bold;">int</span> r<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    mPaint.<span style="color: #006633;">setColor</span><span style="color: #009900;">&#40;</span>0xFFFF0000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">x</span> <span style="color: #339933;">=</span> x<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">y</span> <span style="color: #339933;">=</span> y<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">r</span> <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
 @Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> onDraw<span style="color: #009900;">&#40;</span><span style="color: #003399;">Canvas</span> canvas<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">onDraw</span><span style="color: #009900;">&#40;</span>canvas<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    canvas.<span style="color: #006633;">drawCircle</span><span style="color: #009900;">&#40;</span>x, y, r, mPaint<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Ok, our Ball class is done. Save it and head back over to the main class.</p>
<p><strong>Drawing a Ball on the screen</strong></p>
<p>At this point we haven&#8217;t actually drawn anything. We&#8217;ve just created  Ball which we *could* draw if we so desired. In order to draw it on the screen we first have to get a hold of our FrameLayout. Since we created it via XML we&#8217;ll need to find it again using findViewById():</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>9
10
11
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">  setContentView<span style="color: #009900;">&#40;</span>R.<span style="color: #006633;">layout</span>.<span style="color: #006633;">main</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   FrameLayout main <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>FrameLayout<span style="color: #009900;">&#41;</span> findViewById<span style="color: #009900;">&#40;</span>R.<span style="color: #006633;">id</span>.<span style="color: #006633;">main_view</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Now we can use the addView method to attach a new Ball to our main view:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>11
12
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">    FrameLayout main <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>FrameLayout<span style="color: #009900;">&#41;</span> findViewById<span style="color: #009900;">&#40;</span>R.<span style="color: #006633;">id</span>.<span style="color: #006633;">main_view</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    main.<span style="color: #006633;">addView</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">25</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Run your code now and, if all goes well, you&#8217;ll have a circle with a radius of 25 pixels in the upper left corner of the screen. Yay! Take some time to play around with Paint options, positioning, etc with the various methods outlined in the documentation.</p>
<p>Now all we have to do is add a touch listener to react when the screen is touched. Which is thankfully pretty easy.<br />
We&#8217;re going to create a new touch listener and attach it to our main view all in one fell swoop:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">main.<span style="color: #006633;">addView</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">25</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
main.<span style="color: #006633;">setOnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">View</span>.<span style="color: #006633;">OnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> onTouch<span style="color: #009900;">&#40;</span><span style="color: #003399;">View</span> v, MotionEvent e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The onTouch() method is a callback function which will be hit whenever you touch the screen. Android will send it a View (v) and a MotionEvent (e). We already know what a view is, and a MotionEvent is an object containing information about the touch. All we care about are the X and Y coordinates, which are accessible via the getX() and getY() methods.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">main.<span style="color: #006633;">addView</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">25</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
main.<span style="color: #006633;">setOnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">View</span>.<span style="color: #006633;">OnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> onTouch<span style="color: #009900;">&#40;</span><span style="color: #003399;">View</span> v, MotionEvent e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">float</span> x <span style="color: #339933;">=</span> e.<span style="color: #006633;">getX</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">float</span> y <span style="color: #339933;">=</span> e.<span style="color: #006633;">getY</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The last thing we have to do before we can start drawing is to cast the view we were sent as a FrameLayout, so we can use the addView() method with it. Then we can instantiate a new Ball at the coordinates sent in the Motion Event:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">main.<span style="color: #006633;">addView</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">50</span>,<span style="color: #cc66cc;">25</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
main.<span style="color: #006633;">setOnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">View</span>.<span style="color: #006633;">OnTouchListener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> onTouch<span style="color: #009900;">&#40;</span><span style="color: #003399;">View</span> v, MotionEvent e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">float</span> x <span style="color: #339933;">=</span> e.<span style="color: #006633;">getX</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">float</span> y <span style="color: #339933;">=</span> e.<span style="color: #006633;">getY</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        FrameLayout flView <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>FrameLayout<span style="color: #009900;">&#41;</span> v<span style="color: #339933;">;</span>
	flView.<span style="color: #006633;">addView</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Ball<span style="color: #009900;">&#40;</span>getParent<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, x,y,<span style="color: #cc66cc;">25</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The getParent() call sets the context for the Ball to the main Activity. I only vaguely understand why it has to be done this way.</p>
<p>So now, the moment of truth! You should have all the code you need to run the app in your emulator or even on a real phone. Touching the screen will place a dot where you touched. Amazing!</p>
<p>Hopefully you now have enough of an idea of how all this stuff plays together that you can forge your way to making something vaguely useful (which this isn&#8217;t). </p>
 <p><a href="http://www.kellbot.com/?flattrss_redirect&amp;id=347&amp;md5=cd83d4071904f7cf36761269e3fbb872" title="Flattr" target="_blank"><img src="http://www.kellbot.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kellbot.com/2009/06/android-hello-circle/feed/</wfw:commentRss>
		<slash:comments>84</slash:comments>
		</item>
	</channel>
</rss>

