<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>Blogging about hacking code, life, and music.



  var _gaq = _gaq || [];
  _gaq.push([‘_setAccount’, ‘UA-27220762-1’]);
  _gaq.push([‘_trackPageview’]);

  (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
  })();</description><title>Alex Kehayias's Blog</title><generator>Tumblr (3.0; @alexkehayias)</generator><link>http://alexkehayias.tumblr.com/</link><item><title>Importing Postgres Data Into Hadoop HDFS</title><description>&lt;p&gt;Recently I&amp;#8217;ve been getting a crash course in big data. I ran into an issue where the analytics that used a certain table on out Postgres database was so large it would not run. Like to the point where it would grind a 8gb of memory server to a near halt on a single query. While I had gone through several optimizations, it still was not performant enough at the scale needed. In fact it caused havoc with our host due to IO issues. We&amp;#8217;re talking 50 million rows or more that need to be analyzed in a scalable way. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Enter Hadoop&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m sure Hadoop needs no introduction for most, but the great benefits is a scalable way to take massive amounts of data and answer the questions you have. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How do you get existing data into Hadoop?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I had a ton of data that I needed to get into HDFS that was on a Postgres server. I needed a way to dump the data into a useable format so that I could use it properly with Hadoop. Luckily there is an Apache project called Sqoop (yes Sqoop Hadoop is just an amazing combination of words).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Running Sqoop Jobs&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Sqoop requires that you have Java and Hadoop installed on the machine that is going to run the job. The great news is that it doesn&amp;#8217;t have to be on the same machine as your server. You can run it from any machine, but you typically will run it from a Hadoop cluster. That means it doesn&amp;#8217;t matter where your server lives or who if your host doesn&amp;#8217;t allow you to install your own packages. You also don&amp;#8217;t have to dump the data to the machine that the Sqoop job will be running on. In my case I wanted all my data in S3 as a super portable replacement for HDFS.&lt;/p&gt;
&lt;p&gt;Unfotunately, it took a lot of trial and error to get it working. Make sure that you install the proper &lt;a href="http://jdbc.postgresql.org/download.html" title="JDBC"&gt;JDBC driver&lt;/a&gt; by putting it on your java classpath or put it in the sqoop directory (usually in /usr/bin/sqoop). &lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s a local example using Postgres:&lt;/p&gt;
&lt;pre&gt;    sqoop import --connect jdbc:postgresql://localhost:5432/mydb \
                      --table my_table \ 
                      --username myusername \
                      --password mypassword \
                      --direct

&lt;/pre&gt;
&lt;p&gt;This will dump the table my_table on a local postgres server. The &amp;#8212;direct part is a speedup that&amp;#8217;s unique to Postgres and MySql connectors for sqoop.&lt;/p&gt;
&lt;p&gt;To dump data directly to S3:&lt;/p&gt;
&lt;pre&gt;sqoop import --username myusername --password mypassword --table my_table --target-dir s3n://MYS3APIKEY:MYS3SECRETKEY@bucketname/folder/ --hive-drop-import-delims --escaped-by "\\"&lt;/pre&gt;
&lt;p class="p1"&gt;&lt;span&gt;Some notes to help your blood pressure:&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;span&gt;Make sure your bucket doesn&amp;#8217;t have an underscore in it. &lt;/span&gt;&lt;span&gt;For some reason I wan&amp;#8217;t able to get it to work if there was an underscore in the bucket.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Make sure you use trailing slashes. This should help your blood pressure.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&amp;#8212;direct doesn&amp;#8217;t work with &amp;#8212;escaped-by&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;If you have freeform text fields in your data and there is \n it will fuck up your Hadoop job if you try to read new lines of data by splitting on \n. Use the &amp;#8212;hive-drop-import-delims to parse those out. I don&amp;#8217;t know why it works, this has nothing to do with Hive, it just cleans up your output.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&amp;#8212;escaped-by should always be used if you have freeform text in your data. This will help you parse the data when you run a job because you can ignore important characters (such as a comma) if they are escaped, letting you split data into fields more easily.&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Appending Data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;What happens if we need to get updated data off of our database? HDFS doesn&amp;#8217;t really do an &amp;#8220;update&amp;#8221; to existing data, but we can append all the new rows added past a certain point. To do that we can use the &amp;#8212;incremental argument.&lt;/p&gt;
&lt;pre&gt;sqoop import --connect jdbc:postgresql://localhost:5432/mydb --username myusername --password mypassword --table my_table --incremental append --check-column id  --hive-drop-import-delims --escaped-by "\\"&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Append Data To S3 Using Sqoop &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;I wanted to keep my data independent of the cluster that would run the job. This gives you flexibility to run your jobs wherever, on a cluster or on something like Elastic MapReduce. You have the freedom to build and destroy clusters on a whim because there is no persistant data to lose.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;There&amp;#8217;s no point in appending if you don&amp;#8217;t know the last thing you appended (which row was last to go in the database). Sqoop has a &amp;#8220;job&amp;#8221; command that will store the last id (or date) of the last items dumped. It then queries only the rows after that point. Very cool!&lt;/p&gt;
&lt;p&gt;Unfortunately (again), I couldn&amp;#8217;t get this to work by dumping directly to S3 using the &amp;#8212;incremental argument so I had to use a workaround. First run the command then use distcp to copy the data to S3. For some reason, incremental appends using S3 as the &amp;#8212;warehouse-dir does not work even when specifying a -fs argument.&lt;/p&gt;
&lt;p&gt;Hopefully this saves you as much time as I spent figuring it out.&lt;/p&gt;
&lt;p&gt;First save the job:&lt;/p&gt;
&lt;pre&gt;sqoop job --create myjob -- import --connect jdbc:postgresql://myaddress:12345/&lt;span class="s1"&gt;dbname&lt;/span&gt; --table mytable --hive-drop-import-delims --escaped-by "\\" --username myusername --password mypassword --incremental append --check-column id --split-by id&lt;/pre&gt;
&lt;p class="p1"&gt;Then run it:&lt;/p&gt;
&lt;pre&gt;sqoop job --exec myjob&lt;/pre&gt;
&lt;p class="p1"&gt;Then copy it in a parallelized way to S3:&lt;/p&gt;
&lt;pre&gt;hadoop distcp mytable s3n://MY_S3_KEY:MY_S3_SECRET@mybucket/folder/&lt;/pre&gt;
&lt;p class="p1"&gt;Boom, data on S3 with no dependency on your cluster living another day! I should note that you will want to use a centralized metastore for saving the last rows run by append. See the sqoop docs for more info.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/44153307024</link><guid>http://alexkehayias.tumblr.com/post/44153307024</guid><pubDate>Wed, 27 Feb 2013 13:54:30 -0500</pubDate><category>hadoop</category><category>sqoop</category><category>bigdata</category></item><item><title>Django model creation shortcut with kwargs</title><description>&lt;p&gt;Let&amp;#8217;s say you&amp;#8217;ve got this model in Django that you need to create that has a lot of fields. You&amp;#8217;ve already mapped out the data, but you think you need to write in each argument in the Model.objects.create method. Thankfully, these methods allow **kwargs to be passed in so you can do this: &lt;/p&gt;
&lt;pre&gt;# Remember that kwargs is just a dictionary that's mapping
# arguments to values (in this case model fields to values)
MyModel.objects.create(**some_dict)

# Or if we are updating it
MyModel.objects.update(**some_dict)

# Conveniently we could do something like this,
# assuming your field names are mapped exactly to the model names.
# Sometimes you don't want a model form so this works.
MyModel.objects.create(**request.POST)

# Oh, but I have a foreign key! No prob. 
MyModel.objects.create(
    fk_field = some_object,
    **some_dict
)&lt;/pre&gt;</description><link>http://alexkehayias.tumblr.com/post/35843157838</link><guid>http://alexkehayias.tumblr.com/post/35843157838</guid><pubDate>Fri, 16 Nov 2012 10:26:00 -0500</pubDate><category>django</category><category>python</category></item><item><title>Django Gotcha: Duplicate models when using get_or_create</title><description>&lt;p&gt;When you&amp;#8217;re saving some object to the db, there&amp;#8217;s a gotcha with DateTimeFields that drove me nuts. It took me way too long to figure this out, but if you have a DateTimeField with the option auto_now_add, it will supersede a datetime object in a Model.objects.get_or_create call. This means that if you are tying to prevent duplicates based on date (say you&amp;#8217;re saving some data from an API that has a timestamp) you will still get duplicates. It&amp;#8217;s in the docs, but not the implications when using get_or_create. Check out this example:&lt;/p&gt;
&lt;pre&gt;# Given this simple model
class Foo(models.Model):
    name = models.CharField(max_length=100)
    date_added = models.DateTimeField(auto_now_add=True)

# This will always be true, even if an instance
# with this name and today's date already exists

bar, created = Foo.objects.get_or_create(
    name = 'Alex', 
    date_added = some_datetime_obj
)

print created
# &amp;gt;&amp;gt; True


# The problem is, auto_now_add does some stuff that 
# makes it uneditable, and fucks up my expectations
# when using it with get_or_create

# Here's the solution
class Foo(models.Model):
    name = models.CharField(max_length=100)
    date_added = models.DateTimeField(default=datetime.today())

bar, created = Foo.objects.get_or_create(
    name = 'Alex', 
    date_added = some_datetime_obj
)

print created
# &amp;gt;&amp;gt; False
&lt;/pre&gt;</description><link>http://alexkehayias.tumblr.com/post/33889961953</link><guid>http://alexkehayias.tumblr.com/post/33889961953</guid><pubDate>Fri, 19 Oct 2012 08:24:00 -0400</pubDate><category>django</category><category>python</category></item><item><title>Responsive HTML5 Canvas and Processing.js</title><description>&lt;p&gt;You know what sucks about html5? You have to specify the canvas element with exact width and height. Out of the box that means none of our fancy responsive/liquid grids will  be able to get along well with the canvas. What&amp;#8217;s worse is that when you start using something like Processing for graphics/designs, it too demands a specified width and height. When dealing with &lt;a href="http://alexkehayias.tumblr.com/post/30328452540/drawing-triangles-and-learning-processing-part-1"&gt;patterns&lt;/a&gt;, if you don&amp;#8217;t it&amp;#8217;s not fitting in the right dimensions it&amp;#8217;s just going to look dumb and at that point just use a background image.&lt;/p&gt;
&lt;p&gt;Fuck that. Here&amp;#8217;s what I want to do:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Use a Processing sketch (using &lt;a href="http://www.processingjs.org"&gt;processing.js&lt;/a&gt;) to create a dynamically created background pattern&lt;/li&gt;
&lt;li&gt;Use a liquid layout (in this example a modified Bootstrap responsive grid) that fits the user&amp;#8217;s window size exactly&lt;/li&gt;
&lt;li&gt;When the browser is resized the background pattern should fit precisely in the dimensions of it&amp;#8217;s container&lt;/li&gt;
&lt;/ul&gt;&lt;div&gt;You can see the final result on the homepage of my new personal site &lt;a href="http://www.astronautradio.com"&gt;&lt;a href="http://astronautradio.com"&gt;http://astronautradio.com&lt;/a&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;Note: The rest of the site isn&amp;#8217;t fully responsive yet, but the homepage is&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;img src="http://media.tumblr.com/tumblr_maai5kwTui1r2jghs.png"/&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;&lt;strike&gt;Javascript&lt;/strike&gt; Jquery to the Rescue&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is how we are going to handle it with jquery. When the page loads we are going to resize all of the canvas elements on the page to the width and height of the window (or any percentage based width/height element). We will set a global variable for the width and height which will be used by the Processing sketch when it draws itself on the target canvas. We will either redraw an existing sketch or create a new one if it doesn&amp;#8217;t exist. &lt;/p&gt;
&lt;pre&gt;# CoffeeScript
# Assuming all the dependancies are already loaded
resizeSketches = -&amp;gt;
    canvas = $ 'canvas'
    # We're using backticks here so that these get set globally
    `jswidth = $(window).width()`
    `jsheight = $(window).height()`
    canvas.attr 'width', jswidth
    canvas.attr 'height', jsheight
    sketch = Processing.getInstanceById 'id_of_the_canvas_el'
    if sketch == undefined
        # We need the html element and the sketch to run on it
        # I'm using a compiled processing js sketch called triangles
        new Proocessing $("#id_of_the_canvas_el")[0], triangles
    else
        # This is a function I wrote on the sketch to redraw itself
        # It's different than the builtin processing redraw method 
        sketch.restart()
    
# Somewhere in you code
$(window).on 'resize', resizeSketches
    
&lt;/pre&gt;
&lt;p&gt;Call this when the page loads and it&amp;#8217;s also triggered on the resize event. Lastly we need to update our Processing sketch to set it&amp;#8217;s height and width based on the global javascript variables we specified.&lt;/p&gt;
&lt;p&gt;Processing.js makes it super easy to share values between your other js code and the processing code. This is probably the most understated feature of processing.js, the ability to mash it up with javascript. In your sketch simply change the setup function by adding the following:&lt;/p&gt;
&lt;pre&gt;$p.size(jswidth, jsheight);&lt;/pre&gt;
&lt;p&gt;Easy! Now all we need is a method to restart the sketch which will wipe the existing one and draw it again. Something like&amp;#8230;&lt;/p&gt;
&lt;pre&gt;function restart() {
  $p.background(255);
  // Reset the size of any other shapes that
  // depend on the canvas dimensions then
  $p.loop();
&lt;/pre&gt;
&lt;p&gt;Now when the page is loaded and every time it&amp;#8217;s resized, the canvas containing a processing sketch will set it&amp;#8217;s dimensions and redraw itself. Now go forth and do not fear the fixed dimensions of the html5 canvas. &lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/31459762222</link><guid>http://alexkehayias.tumblr.com/post/31459762222</guid><pubDate>Thu, 13 Sep 2012 09:17:00 -0400</pubDate><category>processing</category><category>processingjs</category><category>html5</category></item><item><title>Another reason why I love Python</title><description>&lt;p&gt;I didn&amp;#8217;t get a chance to go see all of the amazing galleries in Brooklyn participating in &lt;a href="https://www.gobrooklynart.org/"&gt;#gobrooklynart&lt;/a&gt; this weekend. Browsing their list of artists revealed a lot of great pictures of their respective work. Naturally I wrote a script to parse through all of their artist pages to grab over 5000 pictures of awesomeness. I&amp;#8217;m going to put the links I grabbed in a simple infinite scroll to digest the whole thing over this week. &lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s the quick and dirty script I wrote in about 20 minutes:&lt;/p&gt;
&lt;pre&gt;# Get all the artists and all the links from Go! Brookly Art
# and put them in a text file for future use

from BeautifulSoup import BeautifulSoup
import requests
import json

pages = range(1, 115)

storage = open("gobrooklynart.txt", 'a')
for page_number in pages:
    url = "https://www.gobrooklynart.org/explore/artists?page=" + str(page_number) + "&amp;amp;neighborhoods=&amp;amp;media=Painting%2CPhotography%2CPerformance%2CVideo%2FFilm%2FSound%2CSculpture%2CPrint+Making%2FBook+Arts%2CIllustration%2CMixed+Media%2CTextile+Arts%2CDrawing%2CInstallation%2CDesign%2CFashion%2CCraft&amp;amp;accessibility=&amp;amp;order_by=&amp;amp;keyword="
    site = requests.get(url)
    html = BeautifulSoup(site.content)
    artists = list(set(html.find(id="search_results").findAll('a')))
    for artist in artists:
        artist_url = "https://www.gobrooklynart.org" + artist['href']
        artist_page = requests.get(artist_url).content
        artist_html = BeautifulSoup(artist_page)
        data = {}
        data['name'] = artist_html.find('h2', {'class':'display-name'}).text
        images = artist_html.find(id='profile-photos').findAll('img')
        data['pictures'] = [i['src'].replace("thumb", "standard") for i in images]
        try:
            data['homepage'] = artist_html.find(id='studio-website').findAll('a')[0]['href']
        except Exception, e:
            print e
            data['homepage'] = None
        print "Got artist %s" % data['name']
        storage.write(json.dumps(data) + ", ")
    print "On to page next page."
&lt;/pre&gt;
&lt;p&gt;Now I have a txt document with a simple list of artists and pictures of their work. I actually forgot to put the extra &amp;#8220;[ &amp;#8221; and &amp;#8220;]&amp;#8221;, but whatever you get the gist of it. Hooray! &lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/31237877872</link><guid>http://alexkehayias.tumblr.com/post/31237877872</guid><pubDate>Sun, 09 Sep 2012 20:18:12 -0400</pubDate><category>python</category></item><item><title>(via FFFFOUND! | We are intensely aware of man as a machine and...</title><description>&lt;img src="http://25.media.tumblr.com/tumblr_m9tvutB0tz1r6xngro1_500.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;(via &lt;a href="http://ffffound.com/image/b8f9727f61fb25f240a4dc80e266f7a3cbec79f5"&gt;FFFFOUND! | We are intensely aware of man as a machine and the body as a mechanism - but does it float&lt;/a&gt;)&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/30868543941</link><guid>http://alexkehayias.tumblr.com/post/30868543941</guid><pubDate>Tue, 04 Sep 2012 09:52:05 -0400</pubDate></item><item><title>Drawing Triangles and Learning Processing part 1</title><description>&lt;p&gt;I&amp;#8217;ve spent about 20 hours now just drawing triangles using Processing. Processing is a programming language for drawing things with your computer. Recently, I&amp;#8217;ve become more engrossed in the visual side of programming and exploring more of the intersection of the visual arts and technology. &lt;/p&gt;
&lt;p&gt;As with learning anything, the best way for me is to actually do something with it and figure it out as I stumble along. I have a concept for a triangle pattern that inspired me and I want to recreate it in Processing so I can make it interactive (more on that in a future post). &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example (pardon the brutal colors):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_m9ff3wzPv71r2jghs.png"/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How do you describe this pattern?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;What I realized about visual programming is that I spend much more time thinking about how to explain the problem rather than figuring out how to code it. How do we explain this pattern? It&amp;#8217;s a bunch of triangles, but if you just draw the same triangle over and over it won&amp;#8217;t get that nice diamond pattern you see. You could break it down by line and you&amp;#8217;ll find it&amp;#8217;s two patterns that reflect each other. Or you could say that it has zig zags. After much pondering and help from a friend, we came up with an abstraction for explaining. Not as triangles, but as a square. &lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_m9ffdr0yaf1r2jghs.jpg"/&gt;&lt;/p&gt;
&lt;p&gt;Imagine a two dimensional grid with a 3 x 3 dot grid. Each of the rows in the list of numbers represents a triangle. This is actually the pattern we see repeating that creates that diamond effect. I can now abstract the x,y coordinates with zeroes and ones that we will translate to real x and y points on the canvas. &lt;/p&gt;
&lt;p&gt;There&amp;#8217;s probably a mathematical formula here that could do this too, but that&amp;#8217;s beyond my attention span. Instead we have a perfectly good abstraction of a single block that makes up an entire pattern. We can then replicate it on our canvas and achieve our pattern. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Code&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;void setup()
{
  size(800, 600);
  frameRate(1);
  noStroke();
}

boolean over = false;  // If mouse over

void randomFill()
{
  fill(color( random(20, 255), 
              random(0, 255), 
              random(100, 255)));
}

void draw_triangle( int dimension, int x1_coord, 
                    int y1_coord, int x2_coord, int y2_coord, 
                    int x3_coord, int y3_coord)
{
  // Set the points of the triangle
  int x1 = dimension * x1_coord;
  int y1 = dimension * y1_coord;
  int x2 = dimension * x2_coord;
  int y2 = dimension * y2_coord;
  int x3 = dimension * x3_coord;
  int y3 = dimension * y3_coord;
  randomFill();
  triangle(x1, y1, x2, y2, x3, y3);
}

// Draw the 8 triangle pattern
void pattern(int x, int y, int dimension)
{
  pushMatrix();
  translate(x, y);
  // Look familiar? It's our triangle point abstraction
  draw_triangle(dimension, 0, 0, 0, 1, 1, 0);
  draw_triangle(dimension, 0, 1, 1, 0, 1, 1);
  draw_triangle(dimension, 1, 0, 1, 1, 2, 1);
  draw_triangle(dimension, 1, 0, 2, 1, 2, 0);
  draw_triangle(dimension, 0, 1, 0, 2, 1, 2);
  draw_triangle(dimension, 0, 1, 1, 1, 1, 2);
  draw_triangle(dimension, 1, 1, 1, 2, 2, 1);
  draw_triangle(dimension, 1, 2, 2, 1, 2, 2);
  popMatrix();
}

void draw()
{
  background(100);
  fill( 0, 121, 184 );
  int dimension = 100;
  for (int i = 0; i &amp;lt; 800; i = i+200) {
    pattern(0, i, dimension);
    pattern(200, i, dimension);
    pattern(400, i, dimension);
    pattern(600, i, dimension);
  }
}
&lt;/pre&gt;
&lt;p&gt;This is just an early sketch to prove we can make this pattern using the square abstraction (it can be cleaned up a good amount too). It&amp;#8217;s pretty simple when you break a pattern into larger chunks. We basically had to figure it out once, then replicate it a bunch of times to fill the canvas. Eventually, I&amp;#8217;ll add add interactivity and a way to randomly generate the filling of each triangle. I&amp;#8217;m also going to do some math to fit the number of columns and rows and the size of the triangles based on the canvas size. I plan on porting this over to processing.js for use on a web page. Cool stuff!&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/30328452540</link><guid>http://alexkehayias.tumblr.com/post/30328452540</guid><pubDate>Mon, 27 Aug 2012 14:47:00 -0400</pubDate><category>processing</category><category>visual programming</category></item><item><title>Introducing open-source, project based mentorship</title><description>&lt;p&gt;&lt;strong&gt;Spoiler:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Project based mentorship is the future. I built &lt;a href="http://mentorship.p2pu.org"&gt;&lt;a href="http://mentorship.p2pu.org"&gt;http://mentorship.p2pu.org&lt;/a&gt;&lt;/a&gt; to connect people who want to learn (to code, design, whatever) or mentor by working on really cool projects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A Promise&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m a self-taught coder and I&amp;#8217;m proud of it. I now make a living doing what I love: building cool shit. I would not have gotten to this point as fast as I did without the help of amazing mentors. In January I made a promise to help anyone who came to me looking for a mentor to help them learn to code. I&amp;#8217;ve met some amazing people as a result and have tried my best to help make good on that promise. &lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;I haven&amp;#8217;t done enough. So I&amp;#8217;m doing more because I believe in this.&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I teamed up with P2PU, a non-profit, helping people learn from their peers online. I shared my story with them, what I believe in, and they gave me an amazing opportunity to team up with them in Berlin, where I built the &lt;a href="http://mentorship.p2pu.org"&gt;P2PU Mentorship&lt;/a&gt; platform. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Project Based Mentorships is the Future of Learning&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Unfortunately, just matching people with mentors based on what they are learning doesn&amp;#8217;t work. I know this because I did it. By hand. Interviewing everyone, matching people together, sending intro emails, etc. It&amp;#8217;s scary for most people. You agree to work for an indefinite amount of time with someone you don&amp;#8217;t know.&lt;/p&gt;
&lt;p&gt;A better way to do mentorships:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Create a project, something cool you want to work on&lt;/li&gt;
&lt;li&gt;Collaborate with people looking to learn or mentor&lt;/li&gt;
&lt;li&gt;Work on the project and learn along the way&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Here&amp;#8217;s an example:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;I want to learn to build interactive websites&lt;/li&gt;
&lt;li&gt;I create a project on P2PU Mentorship to build a cool site I&amp;#8217;ve been dying to make&lt;/li&gt;
&lt;li&gt;Mentors with the skills I want to learn join my project and help guide me&lt;/li&gt;
&lt;li&gt;I work on the project and learn by doing with awesome mentors&lt;/li&gt;
&lt;/ol&gt;&lt;div&gt;Or if you are a mentor:&lt;/div&gt;
&lt;div&gt;&lt;ol&gt;&lt;li&gt;I&amp;#8217;m working on something really cool, but I need help&lt;/li&gt;
&lt;li&gt;I create a project on P2PU Mentorship to work with people who want to learn and I will help guide them kind of like an academic advisor&lt;/li&gt;
&lt;li&gt;Learners join my project and we work on it together&lt;/li&gt;
&lt;/ol&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Projects are the perfect opportunity to make mentorship happen online.&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;You&amp;#8217;ll know what your getting into (you join project you&amp;#8217;re interested in)&lt;/li&gt;
&lt;li&gt;They are have a logical end (when the project is finished)&lt;/li&gt;
&lt;li&gt;Learners get to produce something they are proud of, work with experienced people, learn new skills&lt;/li&gt;
&lt;li&gt;Mentors benefit from more people working on their project, fresh ideas, and, of course, the joy of helping others&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;If you believe in online learning and helping others please join&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If this sort of thing gets you excited, &lt;a href="http://mentorship.p2pu.org"&gt;please join and help me pay it forward&lt;/a&gt;. Start a cool project and help make a difference.&lt;/p&gt;
&lt;p&gt;Also if you are looking to learn Python and web development, the mentorship site itself is a project you can join led by yours truly. Check it out on &lt;a href="https://github.com/alexkehayias/mentor" title="P2PU Mentorship"&gt;github&lt;/a&gt;.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/29349166671</link><guid>http://alexkehayias.tumblr.com/post/29349166671</guid><pubDate>Mon, 13 Aug 2012 14:31:50 -0400</pubDate><category>mentorship</category><category>p2pu</category><category>opensource</category><category>online education</category></item><item><title>A simple real-time chat server using Clojure and Aleph</title><description>&lt;p&gt;I&amp;#8217;ve been exploring some asynchronous servers and have &lt;a href="http://alexkehayias.tumblr.com/post/28200201770/my-pointless-quest-for-the-perfect-web-stack"&gt;recently been enamored by Clojure&lt;/a&gt;, a modern lisp with brilliant built in concurrency primitives. In the Clojure world, your only real choice for an async server is &lt;a href="https://github.com/ztellman/aleph"&gt;Aleph&lt;/a&gt;. It&amp;#8217;s built on top of an event-driven abstraction library called &lt;a href="https://github.com/ztellman/lamina"&gt;Lamina&lt;/a&gt; (from the same authors) which makes for a handy non-blocking server ready for realtime web apps powered by websockets, UDP, or TCP.&lt;/p&gt;
&lt;p&gt;For this example I was mainly interested in a simple websockets web app with url routes using &lt;a href="https://github.com/weavejester/compojure"&gt;Compojure&lt;/a&gt;, an un-opinionated web framework in Clojure. The premise is simple; a public chatroom around a url (i.e /chat/hello has it&amp;#8217;s own room and messages added there don&amp;#8217;t show up on /chat/another and visa versa). I borrowed some of the code and patterns from another &lt;a href="https://github.com/budu/board"&gt;aleph example app&lt;/a&gt; you also might want to check out.&lt;/p&gt;
&lt;p&gt;You can get the full working(ish) source here: &lt;a href="https://github.com/alexkehayias/clojure-aleph-chat"&gt;&lt;a href="https://github.com/alexkehayias/clojure-aleph-chat"&gt;https://github.com/alexkehayias/clojure-aleph-chat&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class="prettify"&gt;(ns core.main
  (:use lamina.core
        aleph.http
        compojure.core
        (hiccup core page))
        ; This sets the correct file type for js includes used by hiccup 
        (ring.middleware resource file-info)
        core.views
        core.templates)
  (:require [compojure.route :as route])
  (:gen-class))

(defn page []
  "HTML page rendered using Hiccup. Includes the js we need for websockets."
  (html5
   [:head
    (include-css "/static/stylesheets/master.css")]
   [:body
    [:div.container
     [:div.row
      [:div.columns.twelve
        [:p [:h1#headline "Chat"]]
        [:form
          [:input#message {:type "text"}]
          [:input.nice.large.blue.button {:type "submit"}]]
	[:div#messages]]]]
    (include-js "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js")
    (include-js "/static/javascripts/web_socket.js")
    (include-js "/static/javascripts/app.js")]))

(defn sync-app [request]
  "Rendered response of the chat page"
  {:status 200
   :headers {"content-type" "text/html"}
   :body (page)})

(def wrapped-sync-app
  "Wraps the response with static files"
  (-&amp;gt; sync-app
      (wrap-resource "public")
      (wrap-file-info)))

(defn chat-init [ch]
  "Initialize a new chat channel"
  (receive-all ch #(println "message: " %)))

(defn chat-handler [ch room]
  "Relays messages into a chat room. If it doesn't 
  exist create a new channel"
  (let [chat (named-channel room chat-init)]
    (siphon chat ch)
    (siphon ch chat)))

(defn chat [ch request]
  "View handler that handles a chat room. If it's not
  a websocket request then return a rendered html response."
  (let [params (:route-params request)
	room (:room params)]
    (if (:websocket request)
      (chat-handler ch room)
      (enqueue ch (wrapped-sync-app request)))))

(defroutes app-routes
  "Routes requests to their handler function. Captures dynamic variables."
  (GET ["/chat/:room", :room #"[a-zA-Z]+"] {}
       (wrap-aleph-handler chat))
  (GET ["/"] {} "Hello world!")
  ;;Route our public resources like css and js to the static url           
  (route/resources "/static")
  ;;Any url without a route handler will be served this response          
  (route/not-found "Page not found"))

(defn -main [&amp;amp; args]
  "Main thread for the server which starts an async server with 
  all the routes we specified and is websocket ready."
  (start-http-server (wrap-ring-handler app-routes)
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;So what&amp;#8217;s happening here?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We&amp;#8217;re taking a request to the URI /chat/&amp;lt;room&amp;gt; and creating a channel which other visitors to /chat/&amp;lt;room&amp;gt; subscribe to via a websocket. When a message is received to that URI it goes to the chat-handler, realizes it&amp;#8217;s a websocket request, and adds the message to the named-channel that has that chatroom name. The message is pushed to all the subscribers of that channel (everyone on the page /chat/&amp;lt;room&amp;gt;) and the message is rendered on the page using javascript. There is only one channel that is persisted here that everyone is sharing. &lt;/p&gt;
&lt;p&gt;All we need is some javascript to set up the websocket and handle messages. This is in the directory resources/public/javascripts:&lt;/p&gt;
&lt;pre&gt;// Note: this was generated from coffeescript and ƒ stands for function (lol emacs)
(ƒ() {
  $(ƒ() {
    window.socket = new WebSocket(window.location.href.replace("http://", "ws://"));
    socket.onopen = ƒ() {
      return console.log("socket opened");
    };
    socket.onmessage = ƒ(msg) {
      return $("#messages").append("&amp;lt;p&amp;gt;" + msg.data + "&amp;lt;/p&amp;gt;");
    };
    return $("form").on("submit", ƒ(e) {
      e.preventDefault();
      socket.send($("#message").val());
      return $("#message").val("");
    });
  });

}).call(this);
&lt;/pre&gt;
&lt;p&gt;There you have it, a simple, no-frills public chat room based on the page you&amp;#8217;re on. This was just a test, but you can see how easy it is to set up a non-blocking async server with a little help from Aleph. Combined with the concurrency of Clojure itself, you can have an async, concurrent, functional programming love fest. Boners. &lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/28783286946</link><guid>http://alexkehayias.tumblr.com/post/28783286946</guid><pubDate>Sun, 05 Aug 2012 16:07:00 -0400</pubDate><category>clojure</category><category>websockets</category><category>aleph</category><category>compojure</category></item><item><title>My pointless quest for the perfect web stack</title><description>&lt;p&gt;Recently I&amp;#8217;ve been on the blasphemes quest to find my ideal web stack. &lt;/p&gt;
&lt;p&gt;What I Want&lt;/p&gt;
&lt;p&gt;Modern web applications are pushing the envelope of the experiences that can be made over the internets. I use Python/Django/Postgres/Backbone/SASS at the moment and that&amp;#8217;s all well and good. But what I want now is a concurrent language and a non-blocking web server to serve an API. Why? Because most of my web apps now are mostly client-side using lots of javascript and backbone. I want concurrent because I want speed for powerful algorithms I will theoretically write. I want an asnychronous web server because I&amp;#8217;m tired of the Python -&amp;gt; Rabbitmq -&amp;gt; Celery dance I need to do to offload tasks into a queue. &lt;/p&gt;
&lt;p&gt;I realize this list of stuff I want is ridiculous since I don&amp;#8217;t actually know what I want to build with this theoretical stack. So keep that in mind that this is a pointless exercise, but one that I&amp;#8217;ve been thinking about nonetheless. It&amp;#8217;s also extremely narrow minded and not inclusive of all the stuff out there. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;br/&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;WINNER:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;Not necessarily what I use now, but will use next.&lt;/p&gt;
&lt;p class="p2"&gt;Clojure/Aleph -&amp;gt; Mongo -&amp;gt; Backbone -&amp;gt; Handlebars -&amp;gt; SASS&lt;/p&gt;

&lt;p class="p2"&gt;&lt;strong&gt;BACKEND LANGUAGE:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) Clojure&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Concurrent&lt;/li&gt;
&lt;li class="li2"&gt;functional&lt;/li&gt;
&lt;li class="li2"&gt;lispy&lt;/li&gt;
&lt;li class="li2"&gt;fast&lt;/li&gt;
&lt;li class="li2"&gt;Still new, smaller community&lt;/li&gt;
&lt;li class="li2"&gt;Huge learning curve for me&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;2) Python&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;A caveman could write it&lt;/li&gt;
&lt;li class="li2"&gt;Tons of libraries&lt;/li&gt;
&lt;li class="li2"&gt;Proven&lt;/li&gt;
&lt;li class="li2"&gt;GIL sucks :(&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;3) Javascript&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;CoffeeScript makes it awesome&lt;/li&gt;
&lt;li class="li2"&gt;V8 makes it super fast&lt;/li&gt;
&lt;li class="li2"&gt;Possibility of one language for front and back end&lt;/li&gt;
&lt;li class="li2"&gt;single threaded&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;&lt;strong&gt;DB:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) Mongo&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Schema-less&lt;/li&gt;
&lt;li class="li2"&gt;easy to query&lt;/li&gt;
&lt;li class="li2"&gt;restful api (not sure how useful this is out of the box)&lt;/li&gt;
&lt;li class="li2"&gt;possible difficulties in scaling (anecdotal, but frequent)&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;2) Postgres/MySql&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Relational&lt;/li&gt;
&lt;li class="li2"&gt;reliable &lt;/li&gt;
&lt;li class="li2"&gt;scalable&lt;/li&gt;
&lt;li class="li2"&gt;migrations can be a pain&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;&lt;strong&gt;WEB FRAMEWORK/SERVER:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) Aleph (clojure)&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;The only real choice for non-blocking server in clojure&lt;/li&gt;
&lt;li class="li2"&gt;Websocket support&lt;/li&gt;
&lt;li class="li2"&gt;Works with Noir web framework&lt;/li&gt;
&lt;li class="li2"&gt;&lt;span class="s1"&gt;&lt;a href="http://Socket.io/"&gt;&lt;span class="s2"&gt;Socket.io&lt;/span&gt;&lt;/a&gt;&lt;/span&gt; not supported&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;2) Flask (python)&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Super minimal&lt;/li&gt;
&lt;li class="li2"&gt;Simple to set up&lt;/li&gt;
&lt;li class="li2"&gt;It&amp;#8217;s python&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;3) Express (node/javascript)&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Lightweight&lt;/li&gt;
&lt;li class="li2"&gt;Readable&lt;/li&gt;
&lt;li class="li2"&gt;Large community and resources&lt;/li&gt;
&lt;li class="li2"&gt;Non-blocking&lt;/li&gt;
&lt;li class="li2"&gt;Easy &lt;a href="http://Socket.io/"&gt;&lt;span class="s3"&gt;Socket.io&lt;/span&gt;&lt;/a&gt; support&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;4) Django (python)&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Batteries included&lt;/li&gt;
&lt;li class="li2"&gt;So many libraries makes rapid development easy&lt;/li&gt;
&lt;li class="li2"&gt;Get&amp;#8217;s in your way after awhile (restrictive)&lt;/li&gt;
&lt;li class="li2"&gt;Synchronous unless you use Celery as a external task queue&lt;/li&gt;
&lt;li class="li2"&gt;Overkill for the kinds of web apps I write (Backbone, heavy client side)&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;&lt;strong&gt;FRONT END FRAMEWORK:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) Backbone&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Makes front-end feel like backend &amp;#8220;mvc&amp;#8221;&lt;/li&gt;
&lt;li class="li2"&gt;Namespacing keeps views separate &lt;/li&gt;
&lt;li class="li2"&gt;Non-prescriptive, use it how you want&lt;/li&gt;
&lt;li class="li2"&gt;Sometimes confusing because there is no right way to use it&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;&lt;strong&gt;TEMPLATING:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) Handlebars&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Separation of view logic (as much as possible)&lt;/li&gt;
&lt;li class="li2"&gt;Helpers let&amp;#8217;s you write your own template tags&lt;/li&gt;
&lt;li class="li2"&gt;Multiple options for using templates&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;2) Moustache&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;Lacks helpers&lt;/li&gt;
&lt;/ul&gt;&lt;p class="p2"&gt;&lt;strong&gt;CSS:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="p2"&gt;1) SASS&lt;/p&gt;
&lt;ul class="ul1"&gt;&lt;li class="li2"&gt;It&amp;#8217;s just a thousand times better than writing cross-browser pure css&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;And there you have it. My ideal stack that is incredibly flexible and powerful to create awesome shit I haven&amp;#8217;t thought of yet. &lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/28200201770</link><guid>http://alexkehayias.tumblr.com/post/28200201770</guid><pubDate>Sat, 28 Jul 2012 11:37:39 -0400</pubDate><category>python</category><category>nodejs</category><category>clojure</category><category>coffeescript</category><category>javascript</category></item><item><title>Backbone in the wild, lessons learned using backbone.js</title><description>&lt;p&gt;This week I finished up a major redesign of &lt;a href="http://www.edorati.com"&gt;Edorati&lt;/a&gt; which helps people discover articles with their friends. The reason I ended up going with a client-side MVC framework, &lt;a href="http://backbonejs.org/"&gt;Backbonejs&lt;/a&gt;, is because a huge piece of the existing web app was long javascript files with tons of jquery event handling. In short, it was a mess and difficult to build on top of. Although I didn&amp;#8217;t set out to use backbone for everything, I ended up doing just that because it made modular development of client side code that much better. It made it &lt;em&gt;feel &lt;/em&gt;like javascript was as &lt;em&gt;real&lt;/em&gt; as the python/django that powers it. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Getting Your Head Around Client-Side MVC&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Coming from a world of server-side templating, models, and views with Django, I had to start thinking of how that translates to backbone. Your backend will mostly be an API that serves data based on the requested URL and your business logic. Using backbone, my django project only serves one template for the whole app. Everything else is handled by backbone. That should give you an idea of how much heavy lifting backbone is able to do. I ended up stripping 70% of the view code I had written in django. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Oversimplified Explanation of Backbone&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Here is my grossly oversimplified mental model of what backbone is. &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Backbone organizes your front-end javascript code into an MVC style framework. There are 5 primary components to backbone:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Models: serialized data that describes an instance (similar to a django model without the database instructions)&lt;/li&gt;
&lt;li&gt;Collections: a list of models (kind of like a queryset)&lt;/li&gt;
&lt;li&gt;Views: a handler for a section of your app (similar to a django view, but typically more granular)&lt;/li&gt;
&lt;li&gt;Router: routes a url to the appropriate view using a hashbang or pushState&lt;/li&gt;
&lt;li&gt;Templates: Sticks you data into html. Not a part of backbone, but you will almost certainly use them. I personally use handlebars, but you can use whatever you want.&lt;/li&gt;
&lt;/ul&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;Backbone Patterns No One Tells You About&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Going through the tutorials and reading other people&amp;#8217;s code I&amp;#8217;ve picked up on some basic patterns that are used by convention. Some of them were not immediately obvious when I started learning. Others I learned the hard way.&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Granular Views - &lt;/strong&gt;Consider a page that has a list of articles. With django you might create a view that grabs a queryset and outputs a template with a for loop to produce the list. You might then use jquery to handle events like the user editing that instance. With backbone you would set it up like this: A list view creates a collection of articles, for each model in the collection create an article view. Notice that there are two new pieces in there. The collection which is tied to a url which will call your api then automatically create a list of models from the received data and a view for an individual article. It was not obvious to me why in the world you would want a view for an individual article which might be 5 lines of code. The reason is for event handling. You&amp;#8217;re basically setting the scope of events that apply to that code. This will help you avoid large, complicated views that try to handle all sorts of things for individual items. In the long run this leads to better separation of the different parts of your app and makes it much more manageable. Seems like more work up front, but it makes it easier in the end. &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Zombies&lt;/strong&gt; - I wish the documentation was more up front about this. Any non-trivial app typically creates and changes many views within a single session. YOU HAVE TO CLEAN THAT SHIT UP. If you don&amp;#8217;t, your beautiful modular code will exhibit bizarre behavior as soon as you create a new view without first removing the old one. Events are delegated to elements. Even though you may have cleared the html, you have not removed the delegated events. Before you instantiate a new view that replaces another one, remove it and unbind all events from it. (this.remove() this.unbind()). It&amp;#8217;s really hard to debug this, but the symptoms are usually things like the wrong ID being used, wrong model is changing etc. Zombies. For more info read &lt;a href="http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/"&gt;this&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Requirejs -&lt;/strong&gt; Non trivial apps will need to be separated into multiple files. The tutorials out there fail in explaining this. You will almost certainly be needing requirejs. Learn require well. Took me an embarrassing amount of time for me to get this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One view per file -&lt;/strong&gt; Related to the requirejs tip above, you only put 1 view in per file. Coming from django I just thought I would put a whole bunch of views in one file, but that&amp;#8217;s not how it&amp;#8217;s done with backbone using require. One view, model, collection, per file. Why? Because using require you need to return a class and it can&amp;#8217;t handle you returning multiple classes. &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Initializing an app -&lt;/strong&gt; Using require, it&amp;#8217;s not obvious how you &amp;#8220;boot&amp;#8221; the whole app. Create a view that will represent your app and create an initialize function to do what you need to start it up. In your main.js (used by require) create an instance of your app and voila, it will initialize. Typically you would initialize the router and any views that must be there no matter what. For Edorati that means the sidebar and router.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Router is your friend - &lt;/strong&gt;Let your router handle the switching of views. Don&amp;#8217;t try to stick the router logic into your views. Need to send people to a profile detail page? Create a route for it and use that url in the template. Don&amp;#8217;t create an event handler in your view so that when someone clicks on it it creates a new view. Just use the router for what it does, route things. Doing this also means you&amp;#8217;ll have re-usable links that can be used outside of the session. i.e. link that directly takes you to a user&amp;#8217;s profile.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;I&amp;#8217;m sure I&amp;#8217;ll think of more, but that&amp;#8217;s it for now. Most of that list will not make sense until you dive into backbone creating your app. Tweet me if you have any questions &lt;a href="http://www.twitter.com/alexkehayias"&gt;@alexkehayias&lt;/a&gt;.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/26630944947</link><guid>http://alexkehayias.tumblr.com/post/26630944947</guid><pubDate>Fri, 06 Jul 2012 11:14:31 -0400</pubDate><category>backbone</category><category>javascript</category><category>django</category></item><item><title>Write a script for non-trivial things you do more than once</title><description>&lt;p&gt;I just wasted four hours migrating data semi-manually to a new server for a huge update to Edorati only to find that I made a mistake and all my work was rendered useless. What&amp;#8217;s the problem here? The server? The data? No. Shit happens. Mistakes happen.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The moral of the story is&lt;/strong&gt; if you have to do something more than once that involves a non trivial procedure just write a damn script. &lt;/p&gt;
&lt;p&gt;Unfortunately, we have a bias against doing any additional work if we perceive to only need to do something a few times in an ideal scenario. The problem is that reality and ideal scenarios don&amp;#8217;t usually co-exist. I should have been able to brush it off, mutter some choice swear words, and just re-run my script on a new server, but instead, I&amp;#8217;ve been sitting hear bitching and complaining that the world as I know it is a soul-less, horrible, Bieber-filled place. &lt;/p&gt;
&lt;p&gt;I ended up having to write the script anyway. It took me 20 minutes. It will still take a good 30 minutes for the script to run, but my involvement would go from 4 hours to about 5 minutes. &lt;/p&gt;
&lt;p&gt;I&amp;#8217;m going to go lay down on some train tracks for being so dumb.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/26283923780</link><guid>http://alexkehayias.tumblr.com/post/26283923780</guid><pubDate>Sun, 01 Jul 2012 13:20:00 -0400</pubDate></item><item><title>My AngelHack Project, AlertBox, alerts for your social life</title><description>&lt;p&gt;Had a great time with everyone this weekend at AngelHack, a startup hackathon with teams from all over the country. I worked on a little app called &lt;a href="http://www.alertboxapp.com" title="AlertBox"&gt;AlertBox&lt;/a&gt; to notify people of important updates from their social networks as soon as it happens. What if you could get alerted when your friend who just moved half way around the world is having a bad day? What would you do with that timely information?&lt;/p&gt;
&lt;p&gt;&lt;iframe frameborder="0" height="315" src="http://www.youtube.com/embed/Kj9xEUZLXfM" width="420"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;What if we got the right information from our social networks just in time? I think the world could be a better place for it. It&amp;#8217;s just a weekend hack, but the idea is powerful. What do you think?&lt;/p&gt;
&lt;p&gt;Oh and it&amp;#8217;s a python/django/backbone app. Enjoying backbone recently, will make an appearance in my portfolio much more often methinks.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/25849085642</link><guid>http://alexkehayias.tumblr.com/post/25849085642</guid><pubDate>Mon, 25 Jun 2012 08:34:38 -0400</pubDate><category>hackathon</category><category>social media</category></item><item><title>6% Better than Twitter</title><description>&lt;p&gt;The past two weeks I&amp;#8217;ve been doing lots of pitching and am reminded just how important the question &amp;#8220;what makes you unique?&amp;#8221; is so important. If you&amp;#8217;re answer is not a narrative about how you&amp;#8217;re 10 times better than anything else the world has to solve a problem you will lose. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Incremental Improvements vs 10x Game Changers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When I was in DC last week I had a chance to see Dan Yates from opower present. He talked about the power of incremental improvements and how in the macro world they can represent a huge opportunity. For opower that means reducing power consumption for it&amp;#8217;s clients (power companies) by 6%. Very different than a clean tech startup that is trying to replace power plants with solar/wind/whatever. That small change, in aggregate, is a huge improvement and they are able to capture some of the value they are creating (profit).&lt;/p&gt;
&lt;p&gt;Then there are consumer web startups where an incremental improvement of 6% over anything is laughable. Imagine someone pitched their startup to you as &amp;#8220;I&amp;#8217;ve built a product that&amp;#8217;s 6% better than Twitter.&amp;#8221; You just can&amp;#8217;t get excited about an incremental improvement when the web is this crowded. In one of &lt;a href="http://blakemasters.tumblr.com/peter-thiels-cs183-startup"&gt;Peter Thiel&amp;#8217;s class note essays&lt;/a&gt; (go read all of them), Peter talks about dominating markets and becoming the last mover. Competition leads to incremental improvements. Domination comes from 10x game changers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Don&amp;#8217;t Compete, Dominate&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There are plenty examples of incremental improvements leading to big impacts (Edison&amp;#8217;s light bulb is an incremental improvement over what existed), but in the crowded world of web startups I feel that incremental won&amp;#8217;t cut it. If you want to dominate you need to be a 10x improvement. Obviously if you&amp;#8217;re not solving the right problem you can be 10x improvement on something no one cares about, so keep that in mind too. The point is to dominate not compete. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lean Startups and Domination&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m beginning to see how lean startup tactics are indoctrinating us towards incremental improvements. Maybe you have a big idea and vision of how you will change the world. You dissolve that into a testable series of assumptions and set off to prove it. As you go along and test, speak with people, and iterate you increment. You hone in on the actual problem and optimize different parts of your funnel. However, it&amp;#8217;s too easy to fall in love with the tests, data, and incremental improvements. Sometimes the best edit is a rewrite (I think PG said that). Sometimes your pivot is just an incremental improvement. We need to think less about optimization and more about domination. You improved your signup conversion rate by 5%? Cool, but you still only have 100 users because no one cares, you&amp;#8217;re not can&amp;#8217;t miss, not novel, not 10x, just noise.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Where do we go from here&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Maybe it&amp;#8217;s time we &lt;strong&gt;start thinking about intelligent design rather than evolution&lt;/strong&gt; (not in the education/political sense). If we start thinking about domination from day 1, how does that change our approach to product and distribution? There&amp;#8217;s the danger of solving the wrong problem, but there&amp;#8217;s also the problem of not solving the problem hard enough. I already know how to optimize, but I don&amp;#8217;t know how to dominate. I&amp;#8217;m going to work on that.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/24204333280</link><guid>http://alexkehayias.tumblr.com/post/24204333280</guid><pubDate>Fri, 01 Jun 2012 14:06:46 -0400</pubDate><category>startups</category><category>lean startups</category></item><item><title>Advice for submitting Open Graph apps to Facebook</title><description>&lt;p&gt;I recently had to submit an app with two Open Graph actions to Facebook for their blessing. It&amp;#8217;s a clunky process where you need to have it fully working on externally available server (in my case a dev server), post the action to your account successfully, then tell them how to test it so that it meets their guidelines. Turn around time was about 2 days. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;And then they rejected an action&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I recently did a deeper integration with Facebook for &lt;a href="http://www.edorati.com" title="Edorati"&gt;Edorati&lt;/a&gt; to bring some social reader functionality so you can follow what your friends are reading more easily. One of the actions was approved right away, but the &amp;#8220;read&amp;#8221; action was rejected. OMG wut? It&amp;#8217;s so far within their guidelines I could puke and it would still be kosher.&lt;/p&gt;
&lt;p&gt;After thinking it through, I decided that my integration was flawless (I&amp;#8217;m not actually as cocky as my writing presumes) and within guidelines. I resubmitted the same thing, no code changes, nothing. All I did was update my instructions for them to test it to specifically hit every point in their guidelines and it was approved.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lesson&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Avoid wasting time with the approval process by being very specific about your test case when submitting your app. Clearly hit on points such as global settings to turn the action on or off, per item control of the action (in my case, that&amp;#8217;s a button for sharing an article on the article detail page), why it&amp;#8217;s relevant to other people, and make your test case super easy to follow. Oh, it also helps if your code actually works ;-)&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s the Edorati submission (sanitized):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p class="p1"&gt;Log in to DEV_URL with username: USERNAME, password: PASSWORD. Go to ARTICLE_PAGE and click the &amp;#8220;mark as read&amp;#8221; button. This will perform the &amp;#8220;read&amp;#8221; Facebook open graph action. Clicking the button again will delete the post. Go to SETTINGS_PAGE to toggle the &amp;#8220;read&amp;#8221; action globally on or off. The read action is performed when a user reads an article which is a strong indicator that this is a relevant article that other people will want to read in their network. There is global control for this action as well as per article with the Mark as Read/Unread button on the article detail page. &lt;/p&gt;
&lt;/blockquote&gt;</description><link>http://alexkehayias.tumblr.com/post/22651437872</link><guid>http://alexkehayias.tumblr.com/post/22651437872</guid><pubDate>Tue, 08 May 2012 09:57:55 -0400</pubDate><category>facebook</category><category>development</category><category>edorati</category><category>open graph</category></item><item><title>How to make an interactive bookmarklet part 3</title><description>&lt;p&gt;In the last two parts of this series we learned about the framework for building bookmarklets and how to use javascript with django templates for optimal maintainability. Now let&amp;#8217;s look at how to make interactions work without needing any external javascript libraries. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why not include Jquery&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;My guess is that all you really want are event bindings and for that you don&amp;#8217;t need an entire library. Granted, lots of user&amp;#8217;s have jquery cached in their browser already, but if not you have to include that which will make your bookmarklet slower. Every library you add will add more &amp;#8220;weight&amp;#8221; to the overall bookmarklet. Read the next paragraph before you decide you need the whole jquery library or you can make do with 6 lines of pure javascript.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Binding Events to Handlers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;So you want to be fancy and make the bookmarklet change when the user clicks on something? Tough shit. Just kidding. The problem with event handling is that making it work cross-browser is tough. Jquery helps make writing js more cross-browser compatible and that&amp;#8217;s a huge part of it&amp;#8217;s overall value.&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s how we can add event handlers that will work across all browsers without Jquery. I can&amp;#8217;t find where I originally found this from, but when I do I&amp;#8217;ll add an attribution link.&lt;/p&gt;
&lt;pre&gt;    var bindEvent = function(elem, evt, cb) {
        //see if the addEventListener function exists on the element
        if ( elem.addEventListener ) {
            elem.addEventListener(evt,cb,false);
        //if addEventListener is not present, see if this is an IE browser
        } else if ( elem.attachEvent ) {
            //prefix the event type with "on"
            elem.attachEvent('on' + evt, function(){
                //use call to simulate addEventListener
                cb.call(event.srcElement,event);
            });
        }
    };
&lt;/pre&gt;
&lt;p&gt;Now we have a simple way to make interactions happen within the bookmarklet itself. For example:&lt;/p&gt;
&lt;pre&gt;    // Remove the bookmarklet from the document assuming b is body and c is the bookmarklet
    var cancelDialog = function(e){
        b.removeChild(c);
    };
    bindEvent(cancelButton,"click", function(e){
        cancelDialog(this);
    });
&lt;/pre&gt;
&lt;p&gt;All that without including the whole jquery library! That will keep your bookmarklet lightweight and fast. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Submitting a Form&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Using our event binding snippet above we can create a simple handler for submitting a form free from cross-domain errors. Those of you familiar with jsonp will see that this is very similar, but done manually and in a simpler way.&lt;/p&gt;
&lt;pre&gt;    // Assuming we have the following in the script
    var d=document,
    s=d.createElement("scr"+"ipt");
    b.appendChild(s);
    
    // Bind a submit event to a button click
    var submitArticle = function(e){
        // get the values of any form data you need
        // URI encode the variables as GET parameters
        s.src = "http://www.urltoyourservice.com?var1=" + encodeURIComponent(variable1) + "&amp;amp;var2=" + encodeURIComponent(variable2);
    };
    
    bindEvent(submitButton,"click", function(e){
        submitArticle(this);
    });
&lt;/pre&gt;
&lt;p&gt;This will make a GET request to your your server with the parameters of your form. We can now process that request and return a response just like we did to initialize the bookmarklet in the first place. All we need to do is respond back with javascript. You can do this numerous times. All your doing is manipulating the bookmarklet that is already a part of the document. Make sure that you clean up after yourself (see my earlier example of binding a cancel button to removing the bookmarklet from the document). &lt;/p&gt;
&lt;p&gt;There you have it. An interactive bookmarklet that&amp;#8217;s fast, maintainable, and lightweight. You can make changes to it at any time since the initialization happens server-side with familiar templates. You can make cross-domain requests without any errors. You can even bind events and handle them all without needing Jquery. &lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/22191305271</link><guid>http://alexkehayias.tumblr.com/post/22191305271</guid><pubDate>Tue, 01 May 2012 09:41:00 -0400</pubDate><category>javascript</category><category>bookmarklet</category><category>python</category><category>django</category></item><item><title>How to make an interactive bookmarklet part 2</title><description>&lt;p&gt;Let&amp;#8217;s talk about how to generate a bookmarklet using server-side templating and pure javascript (no libraries!). In &lt;a href="http://tmblr.co/ZwrzYwJ7T3TU"&gt;part 1&lt;/a&gt; we discussed the basic framework for making a bookmarklet and performing requests directly from the client&amp;#8217;s page. Now we&amp;#8217;ll see how to set up the foundation for a bookmarklet UI and make it look good.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Building a Bookmarklet Template in Django&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s create a file called bookmarklet.js. In it we are going to add a self executing piece of javascript and leverage django templates to fill in the information we need. In here we are going to build the response using nothing but javascript and send it back to the user who requested the bookmarklet (remember all they did was request it to be initialized, see part 1 for more info). With django templates we can do some pretty handy things so that you don&amp;#8217;t need to manually write out the template as a string in javascript. For example:&lt;/p&gt;
&lt;pre&gt;javascript:(function(){
    var d=document,
    {% comment %}Create the elements we need {% endcomment %}
    c=d.createElement("div"),
    b=d.body,
    l=d.location;
    {% comment %} server_scheme_and_netlog is my own tag which returns the base url of the website{% endcomment %}
    c.id="bookmarkletArticleAlertBox";
    {% comment %}This is where django templates get's awesome{% endcomment %}    
    {% comment %}Make sure the html rendered has no breaks{% endcomment %}    
    c.innerHTML = '{% spaceless %}{% include "bookmarklet_body.html" %}{% endspaceless %}';
    {% comment %}Add the elements to the dom{% endcomment %}
    b.appendChild(t);
    b.appendChild(c);

....snip....
&lt;/pre&gt;
&lt;p&gt;What we did was construct a div that will hold our bookmarklet UI and using django templates (the {%include &amp;#8230; %} part) we can template the html easily, inheriting the context of this view. Please make sure to add the &amp;#8220;spaceless&amp;#8221; tags here because the innerHTML will fail if there are line breaks and I&amp;#8217;ll be damned if I have to add linebreaks to my template. Also be extremely picky with your quotes as that can also lead to disaster.&lt;/p&gt;
&lt;p&gt;Now in our &amp;#8220;bookmarklet_body.html&amp;#8221; we can create our UI just as if it were any other django template (almost). For example:&lt;/p&gt;
&lt;pre&gt;{% load static %}
{% load url_tags %}
{% comment %}NOTE Make sure you ONLY use double quotes!{% endcomment %}    

&amp;lt;div id="bookmarkletAssistant"&amp;gt;
    &amp;lt;img src="{% server_scheme_and_netloc %}{% get_static_prefix %}images/assistant.png" style="border: 2px solid #666666;"/&amp;gt;&amp;lt;br/&amp;gt;    
    &amp;lt;img id="bookmarkletLoadingImage" src="{% server_scheme_and_netloc %}{% get_static_prefix %}images/bookmarklet-ajax-loader.gif" style="display:none;"/&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div id="bookmarkletResponse"&amp;gt;
    &amp;lt;p&amp;gt;Hey Chief, almost ready!&amp;lt;/p&amp;gt;
    &amp;lt;div id="bookmarkletPictureSelector"&amp;gt;
        &amp;lt;p&amp;gt;
            &amp;lt;label&amp;gt;Select Picture:&amp;lt;/label&amp;gt;&amp;lt;br/&amp;gt;
            &amp;lt;div id="bookmarkletImageContainer"&amp;gt;
                &amp;lt;img id="bookmarkletCurrentImage" /&amp;gt;
                &amp;lt;a id="bookmarkletSelectPrev"&amp;gt;&amp;amp;laquo;&amp;lt;/a&amp;gt;&amp;lt;a id="bookmarkletSelectNext" &amp;gt;&amp;amp;raquo;&amp;lt;/a&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;p id="bookmarkletImageCheckboxContainer"&amp;gt;&amp;lt;input id="bookmarkletImageCheckbox" type="checkbox" style="margin-right: 5px;" /&amp;gt;
    &amp;lt;label&amp;gt;No Picture&amp;lt;/label&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;p&amp;gt;
        &amp;lt;label&amp;gt;Editor&amp;amp;rsquo;s Note:&amp;lt;/label&amp;gt;&amp;lt;br/&amp;gt;
        &amp;lt;textarea id="bookmarkletTextArea" placeholder="Add your commentary on the article here. (optional)"&amp;gt;&amp;lt;/textarea&amp;gt;
    &amp;lt;/p&amp;gt;
    &amp;lt;input id="bookmarkletSubmit" type="submit" value="Publish Article" /&amp;gt;
    &amp;lt;a id="bookmarkletCancel"&amp;gt;Cancel&amp;lt;/a&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Notice how all the elements are contained within elements with IDs. This is extremely important so you can clean up after yourself and not pollute the dom. You will also need to do this so that subsequent interactions can find your bookmarklet and update the contents. BTW this is exactly what is used in &lt;a href="http://www.edorati.com" title="Edorati"&gt;Edorati&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;Make sure that you have a view set up so that you know it is from your bookmarklet and can respond with your javascript template. When the user initializes the bookmarklet (see part 1 for reference) they will be requesting a url that you control. All you need to do is map that url to a view function and do the following:&lt;/p&gt;
&lt;pre&gt;    variables = {'some_var': 'blah blah'}
    resp = render_to_string('bookmarklet.js', variables)
    return HttpResponse(resp, mimetype="text/javascript")
&lt;/pre&gt;
&lt;p&gt;This will make sure we are responding with javascript and not html. The javascript will be executed as soon as it is received by the user. It&amp;#8217;s actually very fast and should feel close to instantaneous. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Making it Look Pretty&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Plain unstyled html would be a terrible idea for a bookmarklet. Keep in mind that you are injecting onto another page where their stylesheet is unknown. That means we need to style and reset the css for the bookmarklet or it will not look consistent across sites. Here&amp;#8217;s how:&lt;/p&gt;
&lt;pre&gt;    // in bookmarklet.js
    t=d.createElement("link"), 
    t.rel="stylesheet";
    t.media="screen, projections";
    t.type="text/css";
    t.href="{% server_scheme_and_netloc %}{% get_static_prefix %}stylesheets/bookmarklet.css";
&lt;/pre&gt;
&lt;p&gt;Whoa, dynamically loading css just for our bookmarklet! Nothing fancy going on here, just using plain ol&amp;#8217; css to beautify our bookmarklet. Just make sure that you do not inadvertently style the rest of the elements on the page with your stylesheet. As mentioned before, add an ID for all major elements and when it comes to css, use the ID selector to style the element instead of the element selector or class. If you have to use classes just obfuscate the name so there is little possibility of you impacting the page i.e bookmarklet-textarea-field vs. textarea.  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Next Week&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Next week we&amp;#8217;ll go over how to make the bookmarklet come alive with interaction through event binding and requests using about 15 lines of pure javascript and no libraries.&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/21324220210</link><guid>http://alexkehayias.tumblr.com/post/21324220210</guid><pubDate>Wed, 18 Apr 2012 10:15:00 -0400</pubDate><category>django</category><category>bookmarklet</category><category>javascript</category></item><item><title>Adding a UUID Field to an Existing Django Model</title><description>&lt;p&gt;It&amp;#8217;s not immediately obvious how to add a UUID field to an existing Django model. Let&amp;#8217;s say you have a database with some data in it about certain accounts, but you realize you need a way of obfuscating the pk of a model instance. UUID is a perfect candidate and a pretty popular implementation for Django comes from &lt;a href="https://github.com/dcramer"&gt;dcramer&lt;/a&gt; called &lt;a href="https://github.com/dcramer/django-uuidfield"&gt;django-uuidfield&lt;/a&gt;. Everything is fine and dandy until you try to add that field to an existing model that already has data, then try to auto migrate it using south. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How to add a UUID field to an existing model&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The problem here is that we need to add a UUID value to all existing records, not just new ones. Peaking through the source code you will see what uuid method they are using and what the data should look like.&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Add the UUID field to your model with blank=True, null=True, max_length=32, auto=True in models.py.&lt;/li&gt;
&lt;li&gt;Run the schemamigration command with south and then open up the resulting migration file. &lt;/li&gt;
&lt;li&gt;Edit your migration file with the following:&lt;/li&gt;
&lt;/ol&gt;&lt;pre&gt;# You'll need to import the following
import uuid

# At the end of the forwards() function add the following
def forwards(self, orm):
    ...
    for a in MyModel.objects.all():
        a.uuid = u'' + str(uuid.uuid1().hex)
        a.save()&lt;/pre&gt;
&lt;p&gt;That will loop through all the existing instances of that model in your database and add a uuid to it as part of the migration. Make sure you test it first!&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/20777275125</link><guid>http://alexkehayias.tumblr.com/post/20777275125</guid><pubDate>Mon, 09 Apr 2012 09:47:29 -0400</pubDate><category>django</category><category>uuid</category><category>python</category></item><item><title>How to make an interactive bookmarklet part 1</title><description>&lt;p&gt;Here&amp;#8217;s how to put together a non-trivial interactive bookmarklet. For some reason there are not too many resources on the subject, but it has become a much more popular way of user&amp;#8217;s interacting with a service without having to be on the site. Pinterest, Evernote, etc. all rely heavily on the ease of use of bookmarklets. &lt;/p&gt;
&lt;p&gt;For &lt;a href="http://www.edorati.com" title="Edorati"&gt;Edorati&lt;/a&gt;, I needed to create a simple, fast way for user&amp;#8217;s to publish an article to their online newspaper whenever they came across something they liked. It also had to look nice and allow them to select a picture thumbnail and add an editor&amp;#8217;s note. Oh yeah it also needs to be upgradeable from the server side so that the user doesn&amp;#8217;t have to reinstall it every time you want to add something new. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why is it so hard?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Bookmarklets are especially hard for a couple reasons:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;You don&amp;#8217;t own the page the bookmarklet will deploy on&lt;/li&gt;
&lt;li&gt;Cross-domain requests&lt;/li&gt;
&lt;li&gt;Maintaining some level of security&lt;/li&gt;
&lt;li&gt;Everything needs to be manipulated through javascript&lt;/li&gt;
&lt;li&gt;Avoid using full js libraries like jquery&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;&lt;strong&gt;What&amp;#8217;s the plan?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I ended up building a simple framework for bookmarklets and that uses django to process the request, handle errors, and provide responses. The bookmarklet is actually just a small piece of javascript code that gets executed as soon as it is clicked. It will tell my server that it&amp;#8217;s ready to be initialized for a particular user. Then the server will make a response with ONLY javascript that is contained in a self executing function which will manipulate the target page the user is on. From there any interactions are a matter of building a request on the client side or returning a javascript response from the server-side. Sound simple? Not really&amp;#8230;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How do I make cross-browser requests, do I use Jquery?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;No Jquery! We&amp;#8217;re going to avoid all libraries and roll our own. Adding big libraries will make your bookmarklet slow and you probably only need a couple of things from it. All we need in this case is a small workaround to make cross-browser requests right from the user&amp;#8217;s page. This is the pattern:&lt;/p&gt;
&lt;pre&gt;javascript:(function(){
    var d=document,
    // Create a script element
    s=d.createElement("scr"+"ipt"),
    // Set the src to an endpoint on your server
    s.src = "http://www.urltoyourapi.com/?param1=something&amp;amp;param2=somethingelse";
})()
&lt;/pre&gt;
&lt;p&gt;Now your server can respond with javascript to fill in that script element that was just created on the user&amp;#8217;s page. By adding some GET parameters to the end of the URL you also have a way of communicating information about the user or the page. For example you may want to construct the url in a way that it passes the users obfuscated ID number so you can save information to that user&amp;#8217;s account. This is all a bookmarklet is. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Making it future proof&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To prevent your users from having to install the bookmarklet every time you want to make a change, you should not include any presentation or interactive logic in the bookmarklet. For Edorati, all I need to know from the bookmarklet is who is the user. All the bookmarklet needs to do is essentially tell the server that it wants to be initialized. Everything else should happen on the server side. That way you can make any changes you want to the look or the functionality without ever having to change the user&amp;#8217;s bookmarklet that they installed. &lt;/p&gt;
&lt;p&gt;Next post will discuss constructing templated javascript on the server side to make a bookmarklet interactive, clean, and safe&amp;#8230;&lt;/p&gt;</description><link>http://alexkehayias.tumblr.com/post/20526151518</link><guid>http://alexkehayias.tumblr.com/post/20526151518</guid><pubDate>Thu, 05 Apr 2012 10:11:00 -0400</pubDate><category>bookmarklet</category><category>django</category><category>development</category><category>javascript</category></item><item><title>Add fields to a Django serializer</title><description>&lt;p&gt;Here&amp;#8217;s a quick and dirty way to add fields to a serializer. I wanted to add in the absolute url to the json data that was being sent back during an ajax request. I wouldn&amp;#8217;t recommend it for large querysets since you are essentially adding a json load and another dump, but for a single model instance I think it&amp;#8217;s ok. The alternative would be to use a library like wadofstuff-django-serializer, but I really want to avoid a dependency for just a single purpose.&lt;/p&gt;
&lt;pre class="prettify"&gt;import simplejson as json
from django.core import serialize
&lt;/pre&gt;
&lt;pre class="prettify"&gt;# Somewhere in your view
# Note that I'm only serializing a single instance hence the tup
resp = serializers.serialize("json", (article,))
&lt;/pre&gt;
&lt;pre class="prettify"&gt;# Add absolute url to
resp_obj = json.loads(resp)
resp_obj[0]['fields']['get_absolute_url'] = article.get_absolute_url()
r = json.dumps(resp_obj)
# Then respond back as usual with your updated json object
&lt;/pre&gt;</description><link>http://alexkehayias.tumblr.com/post/19596438315</link><guid>http://alexkehayias.tumblr.com/post/19596438315</guid><pubDate>Mon, 19 Mar 2012 19:23:36 -0400</pubDate><category>django</category></item></channel></rss>
