<?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>emson...</title>
	<atom:link href="http://blog.emson.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.emson.co.uk</link>
	<description></description>
	<lastBuildDate>Thu, 24 Jun 2010 08:27:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ruby Quine Example</title>
		<link>http://blog.emson.co.uk/2010/06/ruby-quine-example/</link>
		<comments>http://blog.emson.co.uk/2010/06/ruby-quine-example/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 08:27:48 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=108</guid>
		<description><![CDATA[I was recently challenged to write a quine in the language of my choice.
If you are unsure what a quine is you can find out from http://en.wikipedia.org/wiki/Quine_(computing).  However basically in our case it is a piece of code that when executed creates a copy of itself. This copy can then be executed and ad [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently challenged to write a <strong>quine</strong> in the language of my choice.
If you are unsure what a <strong>quine</strong> is you can find out from http://en.wikipedia.org/wiki/Quine_(computing).  However basically in our case it is a piece of code that when executed creates a copy of itself. This copy can then be executed and ad infinitum.</p>

<p>There are some official rules about how a <strong>quine</strong> should be implemented:</p>

<ul>
<li>A <strong>quine</strong> must not take any input, as this would allow the source code to be fed in from the keyboard.</li>
<li>Following on from the previous rule a <strong>quine</strong>, should not open it&#8217;s own file and display it&#8217;s contents.</li>
</ul>

<p>Anyway here is my solution in Ruby&#8230;</p>

<pre><code>    lambda{|x| puts x + x.inspect}.call "lambda{|x| puts x + x.inspect}.call"
</code></pre>

<p>Here is a brief description of what is happening. The lambda creates an anonymous function that takes one parameter and outputs it&#8217;s value</p>

<p>Officially I think passing a value into the lambda <code>x</code> attribute violates one of the rules &#8211; but non-the-less it is quite a clear example and may be useful to get an idea of how a <strong>quine</strong> works.</p>

<h3>Links</h3>

<p>Here is a list of interesting links that might help, good luck:</p>

<ul>
<li>An excellent overview of <strong>quine&#8217;s</strong> with a Ruby slant: <a href="http://blog.onideas.ws/ruby_quine">http://blog.onideas.ws/ruby_quine</a></li>
<li>Understanding the concepts of a <strong>quine</strong>: <a href="http://research.swtch.com/2010/03/zip-files-all-way-down.html">http://research.swtch.com/2010/03/zip-files-all-way-down.html</a></li>
<li>Using a <strong>quine</strong> as an interview question: <a href="http://www.skorks.com/2010/03/an-interview-question-that-prints-out-its-own-source-code-in-ruby/">http://www.skorks.com/2010/03/an-interview-question-that-prints-out-its-own-source-code-in-ruby/</a></li>
<li>Shortest Ruby <strong>quine</strong>: <a href="http://stackoverflow.com/questions/2474861/shortest-ruby-quine">http://stackoverflow.com/questions/2474861/shortest-ruby-quine</a></li>
<li>More <strong>quine</strong> links: <a href="http://www.nyx.net/~gthompso/quine.htm">http://www.nyx.net/~gthompso/quine.htm</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/06/ruby-quine-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is the Difference Between a Proc and a Lambda in Ruby?</title>
		<link>http://blog.emson.co.uk/2010/05/what-is-the-difference-between-a-proc-and-a-lambda-in-ruby/</link>
		<comments>http://blog.emson.co.uk/2010/05/what-is-the-difference-between-a-proc-and-a-lambda-in-ruby/#comments</comments>
		<pubDate>Tue, 11 May 2010 11:43:12 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=104</guid>
		<description><![CDATA[The concepts of a Proc and a lambda in Ruby are subtly different and this post aims to try and explain the differences.

Procs and Lambdas

Firstly why do we need Procs and lambdas? In order to answer this you need to understand what a block is in Ruby.

Understanding what a block is?

A block is simply a [...]]]></description>
			<content:encoded><![CDATA[<p>The concepts of a <strong>Proc</strong> and a <strong>lambda</strong> in Ruby are subtly different and this post aims to try and explain the differences.</p>

<h2>Procs and Lambdas</h2>

<p>Firstly why do we need Procs and lambdas? In order to answer this you need to understand what a <strong>block</strong> is in Ruby.</p>

<h3>Understanding what a block is?</h3>

<p>A <strong>block</strong> is simply a piece of code, which is usually attached to a method, Proc or lambda. It is important to note that this block of code is NOT an object (yet&#8230;), it is code that is defined either within braces {} or within a <code>do end</code> container.</p>

<p>The code in a <strong>block</strong> is just logic that hasn&#8217;t been wrapped into an object yet. When this <strong>block</strong> is passed to a method and that method has a <strong>yield</strong> statement then Ruby will wrap that <strong>block</strong> into a special type of object. That type of object is a <strong>Proc</strong> object. Once the <strong>block</strong> becomes a <strong>Proc</strong> Ruby can use it and the <strong>block</strong> code &#8216;comes alive&#8217;.</p>

<p>Therefore we need a <strong>Proc</strong> object in order to handle <strong>blocks</strong>. The next question is how does a <strong>lambda</strong> fit in.</p>

<p>A <strong>lambda</strong> is a type of <strong>Proc</strong> object, it is almost completely identical to a Proc apart from two differences. This little code snippet shows that a <strong>Proc</strong> and a <strong>lambda</strong> are derived from the same superclass, <strong>Proc</strong>.</p>

<pre><code>  def what_are_lambdas_and_procs
    puts "--- #{__method__} ---"
    lam = lambda { puts 'lam variable assigned a lambda' }
    lam.call
    puts "lam is a class of: #{lam.class.name}"
    puts "lam method count: #{lam.methods.size}"
    puts
    prc = Proc.new { puts 'prc variable assigned a Proc' }
    prc.call
    puts "prc is a class of: #{prc.class.name}"
    puts "prc method count: #{prc.methods.size}"
    ""
  end
</code></pre>

<p>This will output:</p>

<pre><code>  --- what_are_lambdas_and_procs ---
  lam variable assigned a lambda
  lam is a class of: Proc
  lam method count: 55

  prc variable assigned a Proc
  prc is a class of: Proc
  prc method count: 55
</code></pre>

<h2>So what are the subtle differences between Proc and lambda?</h2>

<p>As mentioned there are two differences, and these differences are :</p>

<ol>
<li>in how a Proc/lambda assigns arguments, and</li>
<li>in what happens, when a Proc/lambda calls return within a caller method.</li>
</ol>

<h3>Proc, lambda argument assignment</h3>

<p>When a <strong>lambda</strong> is called with more or less than the required number of arguments Ruby will throw an ArgumentError.</p>

<p>However when a <strong>Proc</strong> is called with more arguments, no error is thrown and the extra values are simply thrown away.  When it is called with less arguments these parameters are simply assigned a value of <strong>nil</strong>.</p>

<p>These two code snippets demonstrate this:</p>

<pre><code>  def lambda_args
    puts "--- #{__method__} ---"
    lam = lambda { |a, b| puts "lambda with 2 arguments a:#{a}, b:#{b}" }
    lam.call( "first", "second")
    puts "lambda called with three arguments..."
    begin
      lam.call("first", "second", "third")
    rescue
      puts "   ArgumentError: wrong number of arguments (3 for 2)"
    end
    puts "lambda called with no arguments..."
    begin
      lam.call()
    rescue
      puts "   ArgumentError: wrong number of arguments (0 for 2)"
    end
  end

  def proc_args
    puts "--- #{__method__} ---"
    prc = Proc.new { |a, b| puts "Proc with 2 arguments a:#{(a.nil?) ? "nil" : a }, b:#{(b.nil?) ? "nil" : b }" }
    prc.call( "first", "second")
    puts "Proc called with three arguments..."
    prc.call("first", "second", "third")
    puts "Proc called with no arguments..."
    prc.call()
  end
</code></pre>

<p>This will output:</p>

<pre><code>  --- lambda_args ---
  lambda with 2 arguments a:first, b:second
  lambda called with three arguments...
     ArgumentError: wrong number of arguments (3 for 2)
  lambda called with no arguments...
     ArgumentError: wrong number of arguments (0 for 2)

  --- proc_args ---
  Proc with 2 arguments a:first, b:second
  Proc called with three arguments...
  Proc with 2 arguments a:first, b:second
  Proc called with no arguments...
  Proc with 2 arguments a:nil, b:nil
</code></pre>

<h3>Proc and lambda return behaviour</h3>

<p>When a <strong>lambda</strong> returns a value and this <strong>lambda</strong> is called within a method then method will simply continue it&#8217;s execution until it itself returns a value.</p>

<p>However when a <strong>Proc</strong> returns a value and this <strong>Proc</strong> is called within a method this containing method will be exited WITHOUT any further execution. This is slightly surprising behaviour, and consequently a <strong>Proc</strong> should be handled with care.</p>

<p>These two code snippets demonstrate this behaviour:</p>

<pre><code>  def lam_return
    puts "--- #{__method__} ---"
    puts "simple function that calls a lambda and then returns it's own string."
    my_lam = lambda { return 'Lambda has returned' }
    my_lam.call 
    return 'lam_return method string returned'
  end

  def proc_return
    puts "--- #{__method__} ---"
    puts "simple function that calls a Proc, \nBUT instead of returning it's own string returns the Proc's string."
    my_proc = Proc.new { return 'Proc string returned' }
    my_proc.call # this function returns and finishes here
    return 'proc_return method string returned' # the return is never called
  end
</code></pre>

<p>This will output the following:</p>

<pre><code>  --- lam_return ---
  simple function that calls a lambda and then returns it's own string.
  lam_return method string returned

  --- proc_return ---
  simple function that calls a Proc, 
  BUT instead of returning it's own string returns the Proc's string.
  Proc string returned
</code></pre>

<h4>Proc return work around</h4>

<p>There is however a very simple work around to avoid a Proc from returning out of it&#8217;s caller method. Simply removed the return statement, because Ruby always returns the last line this last line will be returned automatically.</p>

<pre><code>  def proc_return_work_around
    puts "--- #{__method__} ---"
    puts "simple function that calls a Proc, \nhowever the method string still returns."
    my_proc = Proc.new { 'Proc string returned' }
    my_proc.call # this function returns and finishes here
    return "#{__method__} method string returned" # the return is never called
  end
</code></pre>

<p>This will output:</p>

<pre><code>  --- proc_return_work_around ---
  simple function that calls a Proc, 
  however the method string still returns.
  proc_return_work_around method string returned
</code></pre>

<h2>Conclusion</h2>

<p>As you have seen there are only two small differences between a <strong>Proc</strong> and a <strong>lambda</strong> but these differences have quite surprising behaviours.  Therefore following the Ruby principle of <em>&#8220;&#8230;least surprise&#8221;</em>, it is best practice to use <strong>lambdas</strong> over <strong>Procs</strong> unless you absolutely need the <strong>Proc</strong> behaviour.</p>

<p>For more information please see this article: <a href="http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls">http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/05/what-is-the-difference-between-a-proc-and-a-lambda-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Kata Four Exercise &#8211; A Ruby Solution</title>
		<link>http://blog.emson.co.uk/2010/05/code-kata-four-exercise-a-ruby-solution/</link>
		<comments>http://blog.emson.co.uk/2010/05/code-kata-four-exercise-a-ruby-solution/#comments</comments>
		<pubDate>Sun, 09 May 2010 15:41:04 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=101</guid>
		<description><![CDATA[I recently did code kata 4 (data munging), and here is my solution to the problem. Like anything it can be improved but I think it is relatively simple to understand and yet flexible enough to work for a number of different formatted .dat files.

The premiss is to write a program that will work out [...]]]></description>
			<content:encoded><![CDATA[<p>I recently did <a href="http://codekata.pragprog.com/2007/01/kata_four_data_.html">code kata 4 (data munging)</a>, and here is my solution to the problem. Like anything it can be improved but I think it is relatively simple to understand and yet flexible enough to work for a number of different formatted <strong>.dat</strong> files.</p>

<p>The premiss is to write a program that will work out the deltas ( difference ) between two columns in <strong>.dat</strong> files and return the lowest values.</p>

<p>These <strong>.dat</strong> files have different numbers of columns and these columns can be in different order. The two <strong>.dat</strong> files used for this program supplied weather temperature ranges and football (soccer) result scores.</p>

<p>Anyway here is my solution in the Ruby language and a description of how it works:</p>

<pre><code># data_processor.rb

module DataProcessor

  def process_dat(filename, regex=/^\s*\d+\.?\s+/)
    items = []
    IO.foreach(filename) do |line|
      if line =~ regex
        num, max, min = yield line
        delta = max.to_i - min.to_i
        items &lt;&lt; [num, delta] if items.size == 0
        current_items = items[0][1]
        if delta &lt;= current_items
          items.clear if delta &lt; current_items
          items &lt;&lt; [num, delta]
        end
      end
    end  
    items
  end

end

if __FILE__ == $0

  include DataProcessor

  puts "-------- Weather  --------"
  list = process_dat('weather.dat') { |line| tokens = line.split(' ') }
  list.each { |item| puts "Lowest Day:#{item[0]} Delta:#{item[1]}"}

  puts "\n-------- Football --------"
  list = process_dat('football.dat') { |line| tokens = line.split(' ');[tokens[1], tokens[6], tokens[8]] }
  list.each { |item| puts "Team:#{item[0]} Delta:#{item[1]}"}
end
</code></pre>

<p>The code above was created as a <strong>module</strong> as this will allow the <strong>process_dat</strong> method to be mixed-in to other objects, allowing these objects to execute the code without having to instantiate another class to get this functionality.</p>

<p>The <strong>process_dat</strong> method takes a filename and an optional regular expression. The regular expression (regex) is used to find the data in the text file for processing. In this case any line that starts with 0 or more spaces followed by at least one number and then an optional &#8216;.&#8217; after that number followed by at least one space.  This regular expression could have been used to extract the data from each row as well &#8211; but it actually became much easier to simply split each row and tokenise it around a space, as we are processing space separated files.</p>

<p>Using the <strong>IO.foreach</strong> method will iterate over each line of the <strong>.dat</strong> file allowing the logic to process that line. This is much more memory efficient, as only one line is loaded into memory at each iteration of the loop &#8211; thus allowing this method to process very large data files.</p>

<p>Next the method checks to see if the line matches the regex (<code>if line =~ regex</code>) if it does it can be processed.</p>

<p>Processing each line is handled by a Ruby block, (as a <strong>yield</strong> statement is used), in the &#8220;weather.dat&#8221; case the block simply splits the line around a white space. In the &#8220;football.dat&#8221; case the block splits the line around the white space but re orders the returned columns. Incidentally it is useful to know that if the number of tokens in the array exceeds the number of possible assignments (<code>num, max, min = yield line</code>, where <code>yield line</code> returns a 10 item array for instance) Ruby conveniently ignores the other values after assigning the first lot.</p>

<p>The next couple of lines simply calculate the delta and assigns it to a temporary array (<code>items</code>) if items is empty. The items array simply holds the lowest values as a collection of lowest values with the same value.
Note that the items array is an array of arrays. The item in the items array consists of a number and a delta.</p>

<p>Finally we get the lowest item from the items array and check to see if the current line delta is lower if it is, clear the items array and add this new item.  If it equals the same value simply add this item to the items array.
Thus the items array will contain the same lowest values.</p>

<p>I hope you find this helpful &#8211; if you have an alternative solution, why don&#8217;t you add it to the comments at the bottom.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/05/code-kata-four-exercise-a-ruby-solution/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript The Good Parts Best Practices</title>
		<link>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/</link>
		<comments>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 18:05:47 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[bestpractice]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=88</guid>
		<description><![CDATA[Part I

The best practice suggestions listed here are summaries from Douglas Crockford&#8217;s book: JavaScript: The Good Parts

By following these principles you will write better JavaScript code.

JavaScript Best Practices

1. Commenting

Avoid using /* */ for commenting out your code instead use the // method.  The reason being that */ can occur in regular expressions and if [...]]]></description>
			<content:encoded><![CDATA[<h2>Part I</h2>

<p>The best practice suggestions listed here are summaries from <a href="http://www.crockford.com/">Douglas Crockford&#8217;s</a> book: <a href="http://www.amazon.com/gp/product/0596517742?ie=UTF8&amp;tag=emson-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596517742">JavaScript: The Good Parts</a></p>

<p>By following these principles you will write better JavaScript code.</p>

<h2>JavaScript Best Practices</h2>

<h3>1. Commenting</h3>

<p>Avoid using <code>/* */</code> for commenting out your code instead use the <code>//</code> method.  The reason being that <code>*/</code> can occur in regular expressions and if you were to comment out a regular expression containing this, you would get a syntax error.</p>

<h3>2. Object Value Retrieval</h3>

<p>For an object such as <code>var myObj = {key:"value"};</code> An object value can retrieved in two ways:</p>

<ol>
<li>myObj["key"]; // &#8220;value&#8221;</li>
<li>myObj.key; // &#8220;value&#8221;</li>
</ol>

<p>However the second version using &#8216;.&#8217; notation is preferred as it reads better.</p>

<h3>3. Avoid Global Variables</h3>

<p>Global variables will reduce the resiliency of your JavaScript programs so try to keep these to a minimum.  A best practice strategy for this is to use a single global variable for your program and simply assign objects to it. e.g.</p>

<pre><code>var MYAPP = {};

MYAPP.myObj = {
  key:"value"
};
</code></pre>

<h3>4. Capitalize Constructor Functions</h3>

<p>Functions that are created as <em>constructor functions</em> should be capitalized. Think of a <em>constructor functions</em> as a factory creating cloned functions.  Strictly this is not classical inheritance but <strong>prototypical inheritance</strong>. This is essentially where a function is cloned and contains all the properties of it&#8217;s parent.</p>

<pre><code>var Shape = function (name) {
  this.name = name;
};

var square = new Shape("square");
</code></pre>

<p>This style of constructor functions is not recommended as if you forget to use <code>new</code> then the <code>this</code> object gets bound to the global variable.</p>

<h3>5. Avoid Recursion</h3>

<p>JavaScript does not offer <em>tail recursion optimization</em>, therefore functions that recurse too deeply will eventually fail.</p>

<h3>6. Use Function Scope To Protect Against Namespace Collisions</h3>

<p>JavaScript does not have block scope, i.e. variables declared in a block statement (e.g. with in curly braces) are accessible from outside of that block.  However functions do have function scope, variables declared within a function cannot be accessed from outside of that function.</p>

<p>Best practice is to declare the variables used in a function at the top of the function.</p>

<h3>7. Use Functions To Create Modules</h3>

<p>A Module is a function or object that presents an interface but hides its state and implementation. This therefore avoids the use of global variables.</p>

<pre><code>var myModule = function() {
  var call = '';

  return {
    setCall: function(myCall) {
      call = String(myCall);
    },
    doCall: function() {
      return 'Hello ' + call;
    }
  };
}();  // the () will immediately invoke this function

var myCaller = myModule();
myCaller.setCall = 'Ben';
alert( myCaller.doCall() );
</code></pre>

<h3>8. Use Cascades</h3>

<p>If you have a method that changes state, be sure to return <code>this</code> as opposed to <code>undefined</code>. The reason is that you can then chain these methods together.  This is how JQuery works.</p>

<pre><code>getElement('myDiv').changeColour('red').setFont('Times').setStyle('italic');
</code></pre>

<h3>9. For Constructor That Take Many Parameters Use Object Specifiers</h3>

<p>If an object takes many parameters it can be tricky ensuring that these parameters are in the correct order. Therefore create a single object instead that holds all the parameters as properties:</p>

<pre><code>// Tricky
var myObj = someObject(a, b, c, d);

// Better
var myObj = someObject({ first: a, second: b, third: c, fourth: d});
</code></pre>

<h2>General JavaScript Notes</h2>

<p>Strings are immutable, in that once a string has been created that string object cannot be changed. However note that you can easily append and modify a string, the outcome just generates a new string.</p>

<p>JavaScript provides a prototype linkage function, which when used allows one object to &#8216;inherit&#8217; the properties of the linked object.</p>

<p>A <code>try catch</code> statement only allows a single catch block, to catch all exceptions. If you need to differentiate between exceptions then add code to inspect the name of the exception and handle it appropriately.</p>

<h3>Objects</h3>

<p>Object creation methods:</p>

<ol>
<li><code>var myObj = {};</code></li>
</ol>

<p>Set a default value if an object property doesn&#8217;t exist:</p>

<pre><code>var myObj = {one:"1"};
myObj.two || "2" // returns "2"
</code></pre>

<p>Assigning a value to an object property that is undefined will simply augment (or create) that property in that object and assign it.</p>

<p>Objects are passed by reference, they are never copied.</p>

<p>Every object is linked to a prototype object from which it can inherit properties. This object is <code>Object.prototype</code></p>

<p>The prototype link is only used in the retrieval of properties from objects, if the first object does not have the property then JavaScript will use this prototype link to get the next object up the chain and try and retrieve the property from this object. If no property exists then <code>undefined</code> is returned.</p>

<p>When using <code>for in</code> for enumerating over properties in an object, be aware that it will also enumerate the properties of objects further up the prototype chain.  If you don&#8217;t want this simply just use <code>for</code>,</p>

<h3>Functions</h3>

<p>As Douglas Crockford says:</p>

<blockquote>
  <p>Functions are the fundamental modular unit of JavaScript. Use functions for code reuse, information hiding and composition. Functions are used to specify the behaviour of objects.</p>
</blockquote>

<p>Functions are objects, but they have a prototype link to <code>Function.prototype</code>, and then this root function object in turn links to <code>Object.prototype</code>.</p>

<p>A function can take 0 or more specified parameters, however functions get two extra hidden parameters <code>this</code> and <code>arguments</code>.</p>

<p>A <strong>method</strong> is simply a function assigned (bound) to an objects property. e.g.</p>

<pre><code>var myObj = {
  myMethod: function (name) {
    alert("Hello " + name);
  };
};
</code></pre>

<p>A function always returns a value. If no return value is defined then the function will return <code>undefined</code>. However if a function is constructed with the <code>new</code> prefix and the return value is not an object the new object is returned.</p>

<h2>JavaScript Gotcha&#8217;s</h2>

<h3>typeof Returns incorrect types</h3>

<p>Using the <code>typeof</code> method will return six results:</p>

<ol>
<li>number</li>
<li>string</li>
<li>boolean</li>
<li>undefined</li>
<li>function</li>
<li>object</li>
</ol>

<p>The problem occurs with <code>typeof ['1']</code> or <code>typeof null</code> which both return <em>object</em> which is incorrect.</p>

<h3>Function Invocation Binds &#8216;this&#8217; To The Global Object</h3>

<p>When a function is created by assigning it to a global variable, and the contents of that function contains a <code>this</code> statement then the <code>this</code> is bound to the Global Object</p>

<p>When a function, contains an internal function the <code>this</code> of the internal function is bound to the Global Object and not the <code>this</code> of the parent function. To fix this simply assign <code>this</code> to a <code>that</code> variable and use <code>that</code> within your internal function.</p>

<pre><code>var myObj = {
  value: 0;

  double: function() {
    var that = this;
    var helper = function() {
      that.value = that.value + that.value;
    };
    helper();
  };
};
</code></pre>

<h3>arguments Is An Array Like Object Not An Array</h3>

<p>All functions have a parameter <code>arguments</code> which gives a function access to all the arguments supplied with it&#8217;s invocation &#8211; including excess arguments that are not assigned to a parameter.
However note that <code>arguments</code> is in fact a special object with a length method and not an Array object. So <code>arguments</code> will lack methods that an Array object will have.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How To Set Up and Build a Django Web Site</title>
		<link>http://blog.emson.co.uk/2010/04/how-to-set-up-and-build-a-django-web-site/</link>
		<comments>http://blog.emson.co.uk/2010/04/how-to-set-up-and-build-a-django-web-site/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 16:38:04 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=84</guid>
		<description><![CDATA[This article outlines how to set up your new Django site from scratch. I tend to use Dreamhost Web Site Hosting so there will be a few notes specific to them.

If you are unsure how to set up Python and Django using Dreamhost then checkout my previous article.

I hope you find it useful and drop [...]]]></description>
			<content:encoded><![CDATA[<p>This article outlines how to set up your new Django site from scratch. I tend to use <a href="http://www.dreamhost.com/r.cgi?105422">Dreamhost Web Site Hosting</a> so there will be a few notes specific to them.</p>

<p>If you are unsure how to set up Python and Django using <a href="http://www.dreamhost.com/r.cgi?105422">Dreamhost</a> then checkout my previous article.</p>

<p>I hope you find it useful and drop me a comment if you have any questions.</p>

<h2>Create the new site</h2>

<p>Create a project directory</p>

<pre><code>$ mkdir -p mysite-project/mysite.com
$ cd mysite-project/mysite.com
</code></pre>

<p>Create you new site:</p>

<pre><code>$ django-admin.py startproject mysite
</code></pre>

<p>Now create the following directories:</p>

<pre><code>$ mkdir -p mysite-project/settings
$ mkdir -p mysite-project/mysite.com/tmp/
$ mkdir -p mysite-project/mysite.com/public/appmedia
$ mkdir -p mysite-project/mysite.com/mysite/scripts
$ mkdir -p mysite-project/mysite.com/mysite/templates
</code></pre>

<h2>Initialise git</h2>

<pre><code>$ cd mysite-project/mysite.com
$ git init
$ touch .gitignore

Add the following:

.DS_Store
*.pyc
packages/
work/
</code></pre>

<h2>Add WSGI file</h2>

<p>The following should be carried out from this directory:</p>

<pre><code>$ cd mysite-project/mysite.com
</code></pre>

<p>Add the <strong>passenger_wsgi.py</strong> file to mysite-project/mysite.com directory:</p>

<pre><code>import sys, os
if sys.hexversion &lt; 0x2060000: os.execl("/home/myuser/opt/python261/bin/python2.6", "python2.6", *sys.argv)

sys.path.append(os.getcwd())
# START
# required if you are using VirtualEnv, to get Passenger to use local Python environment.
# see: http://wiki.dreamhost.com/Passenger_WSGI
INTERP = "/home/myuser/virtual/bin/python2.6"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
# END
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>

<p>Create the public/appmedia directory in this directory to.
Create tmp/restart.txt</p>

<h2>Set up the VirtualEnv Environment</h2>

<p>Move to the mysite-project directory.
Ensure that you have virtualenv installed on your local system:</p>

<pre><code>$ cd mysite-project
$ pip install virtualenv
</code></pre>

<p>Create the <strong>virtual/</strong> directories using virtualenv:</p>

<pre><code>$ virtualenv ./virtual
</code></pre>

<p>Create a symbolic link to the <strong>activate</strong> executable.</p>

<pre><code>$ ln -s ./virtual/bin/activate ./activate
</code></pre>

<p>NB: if you rename your mysite-project directory you may well need to delete the virtual directory and activate symbolic link and recreate them using the previous virtualenv steps.</p>

<p>You can check which Python site packages being used with this command:</p>

<pre><code>$ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
</code></pre>

<h2>Create Local Dev Database</h2>

<p>Change directory to the scripts directory in mysite-project/mysite.com/mysite:</p>

<pre><code>$ cd mysite-project/mysite.com/mysite/scripts
$ touch scripts/create-db.sql
$ touch scripts/drop-db.sql
</code></pre>

<p>create-db.sql</p>

<pre><code>create database mysite_com_dev;
grant all on mysite_com_dev.* to 'root'@'localhost';
</code></pre>

<p>drop-db.sql</p>

<pre><code>drop database mysite_com_dev;
</code></pre>

<p>Now create the database</p>

<pre><code>$ mysql -u root &lt; scripts/create-db.sql
</code></pre>

<h2>Set up the Django Project Files</h2>

<p>Make the following changes to the <strong>settings.py</strong> file.</p>

<pre><code>import sys
import os
import os.path
import socket

PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(PROJECT_ROOT)) # needed because of shared hosting PYTHONPATH problems

# MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public/appmedia/')
MEDIA_ROOT = '/full/local/path/to/appmedia/'
# MEDIA_URL = '/appmedia/'
MEDIA_URL = 'http://media.mysite.com/appmedia/'
ADMIN_MEDIA_PREFIX = 'http://media.mysite.com/media/'

TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates').replace('\\','/'), )

INSTALLED_APPS = (
    'django.contrib.admin', # add this
    'django.contrib.admindocs', # and this
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)

# Add this to the bottom to import your local settings
try:
    from settings_local import *
except ImportError:
    pass
</code></pre>

<p>Now we need to create a settings_local.py file in the same directory as the main settings.py file:</p>

<pre><code>$ touch settings_local.py
</code></pre>

<p>Then add your default settings (most probably your dev settings):</p>

<pre><code>DATABASE_ENGINE = 'mysql'     
DATABASE_NAME = 'mysite_com_dev'
DATABASE_USER = 'root'         
DATABASE_PASSWORD = ''         
DATABASE_HOST = 'localhost'    
DATABASE_PORT = ''
</code></pre>

<p>As we will be using multiple environments we need to have different configurations for each environment.  There are a number of ways to do this, however the DRYist and easiest is to have a main settings file that imports different settings according to the environment.</p>

<p>Change directory to the mysite-project/settings directory, and create the appropriate settings files &#8211; we will have a dev, staging and production file as well as the main one:</p>

<pre><code>$ cd mysite-project/settings
$ touch settings_dev.py; touch settings_staging.py; touch settings_production.py
</code></pre>

<p>Now add the appropriate settings to these files database settings. Note that these settings will overwrite the settings in the main settings file.</p>

<h2>Adding South to Your Application</h2>

<p>For detailed installation instructions see <a href="http://south.aeracode.org/wiki/Download">http://south.aeracode.org/wiki/Download</a>.</p>

<p>Note, for MySQL databases, you should install South to a new instance of your MySQL database and not an existing or legacy database. This is because South won&#8217;t update it&#8217;s self when you run: <code>python manage.py migrate</code></p>

<p>Quick installation.</p>

<p>Add <strong>South</strong> (Note the capital &#8216;S&#8217;) to your pip requirements.txt file, and pip install it:</p>

<pre><code>  pip install -r requirements.txt
</code></pre>

<p>Or just run:</p>

<pre><code>  pip install South
</code></pre>

<p>Install the <strong>south</strong> (Note lowercase &#8217;s&#8217;) into your project settings.py file. e.g.:</p>

<pre><code>  INSTALLED_APPS = (
      'django.contrib.admin',
      'django.contrib.admindocs',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.sites',
      'south',
  )
</code></pre>

<p>Now <strong>syncdb</strong> with your database so that your App knows about South.</p>

<pre><code>  $ python manage.py syncdb
</code></pre>

<p>You should get an output similar to this:</p>

<pre><code>      Syncing...
      Creating table south_migrationhistory

      Synced:
       &gt; django.contrib.admin
       &gt; django.contrib.auth
       &gt; django.contrib.contenttypes
       &gt; django.contrib.sessions
       &gt; django.contrib.sites
       &gt; django.contrib.markup
       &gt; south
       &gt; tagging

      Not synced (use migrations):
       - 
      (use ./manage.py migrate to migrate these)
</code></pre>

<p>Finally you need to tell South what Apps you want it to manage (in terms of migrations). So for example say you have an App called &#8216;firepages&#8217;, then run:</p>

<pre><code>  python manage.py startmigration firepages --initial
</code></pre>

<p>This will create a migrations directory and will allow South to manage all the models in that App:</p>

<pre><code>  Creating migrations directory at '/mypath/mysite-project/mysite.com/mysite/firepages/migrations'...
  Creating __init__.py in '/mypath/mysite-project/mysite.com/mysite/firepages/migrations'...
   + Added model 'firepages.Group'
   + Added model 'firepages.Category'
   + Added model 'firepages.Page'
  Created 0001_initial.py.
</code></pre>

<p>Note that because you will be uploading this new migrations directory you shouldn&#8217;t need to run this command on the server.</p>

<p>You will now need to execute the following command to migrate forward:</p>

<pre><code>  python manage.py migrate
</code></pre>

<p>Now if you want to change your database do the following:</p>

<ol>
<li>Modify your model. e.g. add / remove fields</li>
<li>Tell South to create a migration: <code>python manage.py startmigration myapp name-of-my-migration --auto</code></li>
<li>Execute the migration: <code>python manage.py migrate</code></li>
</ol>

<h2>Change urls.py</h2>

<p>Use the following imports:</p>

<pre><code>from django.conf import settings
from django.contrib import admin

admin.autodiscover()
</code></pre>

<p>At the bottom add a new URL path so that the site can get access to the appmedia, NB don&#8217;t forget to add a staging and production version to:</p>

<pre><code># simple trick to use local css files for development.
# (Just make sure DEBUG=False in production!!!)
if settings.DEBUG:
    urlpatterns += patterns('', 
        url(r'^appmedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 
            'document_root': settings.MEDIA_ROOT }),
        )
</code></pre>

<p>Now add the following URLs:</p>

<pre><code>urlpatterns = patterns('',
    #Admin URLS
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),

    #Home URL
    (r'^$', include('mysite.foo.urls'),
)
</code></pre>

<p>You may want to change the <strong>admin</strong> URL pattern to be something else. This will make the admin area more obscure thus helping to prevent hacking. e.g. <strong>mylogin</strong></p>

<h2>Add a views.py file</h2>

<p>In the mysite-production/mysite.com/mysite/ directory add a views.py file with the following:</p>

<pre><code>from django.http import HttpResponse

import settings

def hello(request, path='none'):
    """quick hello test"""
    return HttpResponse("Quick test, PROJECT_ROOT: %s&lt;br/&gt;URL path: %s" % (settings.PROJECT_ROOT, path))
</code></pre>

<h2>Sync the DB and Start the Server</h2>

<p>Navigate to the mysite-project/mysite.com/mysite directory</p>

<p>Start the virtual environment:</p>

<pre><code>$ . ../../activate
(virtual)$ python manage.py syncdb
** create a user **
(virtual)$ python manage.py runserver
</code></pre>

<p>Now open a browser and point it at this URL:</p>

<pre><code>$ open http://localhost:8000
</code></pre>

<p>It should display your <strong>hello</strong> view results.</p>

<h2>Requirements</h2>

<p>Add a requirements.txt file to the following directory:</p>

<pre><code>$ touch mysite-project/mysite/requirements.txt
</code></pre>

<p>Add in any requirements e.g. django-tagging</p>

<pre><code>echo mysite-project/mysite/requirements.txt &lt;&lt; django-tagging
</code></pre>

<p>Execute and add requirements:</p>

<pre><code>pip install -r requirements.txt 
</code></pre>

<h2>Local Apps Directory</h2>

<p>Create an <strong>apps</strong> directory in the root of your project folder. Then tell your settings.py file about it:</p>

<pre><code>  sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))
</code></pre>

<p>Now any apps that you want in here and not in your &#8220;pip install&#8221; directory just add them and they will be found.</p>

<h2>RequestContext on All Views</h2>

<p>All your views should implement a RequestContext variable, but first you will need to add the following CONTEXT_PROCESSORS to the settings.py file:</p>

<pre><code>TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug', # passes the DEBUG variable to the template
    'django.core.context_processors.i18n',
    'django.core.context_processors.media', # passes the MEDIA_URL to the template
    'django.core.context_processors.request', # passes the request object to the template
)
</code></pre>

<p>Now Make sure that you pass the RequestContext to the render.</p>

<pre><code>def home_page(request):
    """display home page"""
    template = "page_home.html" 
    return render_to_response(template, { 'foo':'bar' }, context_instance=RequestContext(request))
</code></pre>

<p>This will allow you to use generic templates, and also get a handle on certain variables in the template.</p>

<h2>Page Specific Menus</h2>

<p>See this article for more information:  <a href="http://gnuvince.wordpress.com/2007/09/14/a-django-template-tag-for-the-current-active-page/">http://gnuvince.wordpress.com/2007/09/14/a-django-template-tag-for-the-current-active-page/</a></p>

<p>Django doesn&#8217;t out of the box provide a <strong>current_page</strong> variable like Ruby on Rails &#8211; but it is easy enough to implement.</p>

<p>You will need to have the <strong>&#8216;django.core.context_processors.request&#8217;,</strong> setting set in the template context processors as specified above.</p>

<p>You will also need to create a module called <strong>templatetags</strong> with a <strong>init</strong>.py file in it.
Now add a file called <strong>active_menus.py</strong></p>

<pre><code>    from django import template

    register = template.Library()

    @register.simple_tag
    def link_to(request, pattern, url, name):
        import re
        if re.search(pattern, request.path):
            return '&lt;span class="active"&gt;%s&lt;/span&gt;' % name
        return '&lt;a href="%s"&gt;%s&lt;/a&gt;' % (url, name)
</code></pre>

<p>Now in your template <em>load</em> this template tag and call it like this:</p>

<pre><code>    {% load active_menus %}
    &lt;li&gt;{% link_to request "^/$" "/" "home" %}&lt;/li&gt;
    &lt;li&gt;{% link_to request "^/software/$" "/software/" "software" %}&lt;/li&gt;
    &lt;li&gt;{% link_to request "^/books/$" "/books/" "books" %}&lt;/li&gt;
</code></pre>

<h2>Template Includes</h2>

<p>When creating an include template file give it a name starting with an underscore e.g. <code>_nav.html</code></p>

<h2>Add a Sitemap to Your Site</h2>

<p>Add the following to your settings.py file in the INSTALLED_APPS section:</p>

<pre><code>    django.contrib.sitemaps
</code></pre>

<p>Now check that you have the following installed also.</p>

<p>This should be in the TEMPLATE_LOADERS:</p>

<pre><code>  'django.template.loaders.app_directories.load_template_source',
</code></pre>

<p>Make sure you’ve installed the sites framework. Also make sure that you have set the site domain name and description correctly in the <strong>sites</strong> project in the <strong>Admin Panel</strong>.  It should not be <strong>example.com</strong>, but something like: <strong>myproject.com</strong></p>

<p>Create a <strong>sitemaps.py</strong> file in your project. This file should contain something like:</p>

<pre><code>from django.contrib.sitemaps import Sitemap
from myproject.models import ProductPage, ProductCategory

class ProductPageSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return ProductPage.objects.all().filter(published=True)


class ProductCategorySitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return ProductCategory.objects.all()
</code></pre>

<p>Now add the following to your <strong>urls.py</strong> file:</p>

<pre><code>    from myproject.sitemaps import *
    # from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap

    sitemaps = {
        'product_pages': ProductPageSitemap,
        'product_categories': ProductCategorySitemap,
    }

    urlpatterns = patterns('',
      (r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
    )
</code></pre>

<h2>Adding a new App</h2>

<pre><code>$ python manage.py startapp myappname
</code></pre>

<p>Add myappname to your settings.py file INSTALLED_APPS
Now create some models in your myappname/models.py file.</p>

<p>Then run a syncdb:</p>

<pre><code>$ python manage.py syncdb 
OR to see the SQL
$ python manage.py sql myappname
</code></pre>

<p>Now if you want to add South migrations:</p>

<pre><code>$ python manage.py startmigration myappname --initial
</code></pre>

<h2>Installing PIL</h2>

<p>PIL should not be installed as part of the requirements.txt file, as you will need to compile libjpeg first.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/04/how-to-set-up-and-build-a-django-web-site/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to Install Python on Dreamhost Shared Hosting</title>
		<link>http://blog.emson.co.uk/2010/04/how-to-install-python-on-dreamhost-shared-hosting/</link>
		<comments>http://blog.emson.co.uk/2010/04/how-to-install-python-on-dreamhost-shared-hosting/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 16:31:48 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[databases]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[dreamhost]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=80</guid>
		<description><![CDATA[This article describes how to install and set up Python and VirtualEnv on Dreamhost web site hosting.

Some of these notes are based on this article: 
URL:  http://blog.localkinegrinds.com/2007/08/20/custom-python-installation-for-django-on-dreamhost/

Set up

Log into your shared server and do the following:

$ mkdir -p opt/python261
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.1/Python-2.6.1.tgz
$ tar xvzf Python-2.6.1.tgz


Note that:
According to the Filesystem Hierarchy Standard, [...]]]></description>
			<content:encoded><![CDATA[<p>This article describes how to install and set up Python and VirtualEnv on <a href="http://www.dreamhost.com/r.cgi?105422">Dreamhost web site hosting</a>.</p>

<p>Some of these notes are based on this article: 
URL:  http://blog.localkinegrinds.com/2007/08/20/custom-python-installation-for-django-on-dreamhost/</p>

<h2>Set up</h2>

<p>Log into your shared server and do the following:</p>

<pre><code>$ mkdir -p opt/python261
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.1/Python-2.6.1.tgz
$ tar xvzf Python-2.6.1.tgz
</code></pre>

<p>Note that:
According to the <a href="http://www.pathname.com/fhs/pub/fhs-2.3.html#OPTADDONAPPLICATIONSOFTWAREPACKAGES">Filesystem Hierarchy Standard</a>, the /opt dir &#8220;is reserved for the installation of add-on application software packages.&#8221;</p>

<p>Now configure where your new Python instance will be installed:</p>

<pre><code>$ cd Python-2.6.1
$ ./configure --prefix=$HOME/opt/python261
$ make
$ make install &gt; install.txt
</code></pre>

<p>NB: The install.txt file is useful to locate files if you wish to uninstall Python later.
NB: you might wish to use:</p>

<pre><code>$ ./configure --prefix=$HOME/opt/python261  --enable-unicode=ucs4
</code></pre>

<p>But Dreamhost does uses ucs2 by default (Python&#8217;s default to), and there can be issues if you try to load packages that are compiled using a different Unicode setting.</p>

<p>Now edit your ~/.bash_profile file to specify the new Python install located in: ~/opt/</p>

<pre><code>export PATH=$PATH:$HOME/opt/python261/bin
</code></pre>

<p>You might also want to add an alias so that instead of typing <strong>python2.6</strong> to access the python shell, you can just type <strong>python</strong> in the command line.</p>

<pre><code>alias python='python2.6'
</code></pre>

<p>Don&#8217;t forget to tell bash to load this file after you have made your changes:</p>

<pre><code>$ source ~/.bash_profile
$ python -V  # will display your new version 2.6.1
</code></pre>

<h2>Installing VirtualEnv</h2>

<pre><code>$ cd downloads/
$ curl -O http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.4.5.tar.gz
$ tar -xvzf virtualenv-1.4.5.tar.gz
$ python virtualenv-1.4.5/virtualenv.py $HOME/virtual --no-site-packages
</code></pre>

<p>NB: This binds your new install with virtualenv and creates a virtual directory in your user home directory.
You will need to use the <strong>&#8211;no-site-packages</strong> option so that virtualenv doesn&#8217;t use any of the original Dreamhost Python install packages.</p>

<p>Update your <strong>~/.bash_profile</strong> file so that it puts the virtualenv packages onto the Python path, and <em>activate(s)</em> your virtual environment:</p>

<pre><code>export PATH="$PATH:$HOME/opt/python261/bin:$HOME/virtual/bin"
source $HOME/virtual/bin/activate
</code></pre>

<p>Check that the packages directory is in your new virtual <strong>site_packages</strong> directory:</p>

<pre><code>$ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
</code></pre>

<p>Now activate your virtual environment, by executing the <strong>.bash_profile</strong> file:</p>

<pre><code>$ source ~/.bash_profile
</code></pre>

<p>Or manually activate it by:</p>

<pre><code>$ . ~/virtual/bin activate
</code></pre>

<h2>Installing MySQL Python Bindings</h2>

<!-- http://sourceforge.net/projects/mysql-python/files/mysql-python-test/1.2.3c1/MySQL-python-1.2.3c1.tar.gz/download -->

<pre><code>(virtual)$ cd downloads
(virtual)$ wget http://internap.dl.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.3c1.tar.gz
(virtual)$ tar xvzf MySQL-python-1.2.3c1.tar.gz
(virtual)$ cd MySQL-python-1.2.3c1
(virtual)$ python setup.py install
</code></pre>

<p>Check that you can import the database correctly (NB: do this from a different directory from the one where MySQL-python was installed, as you will get Module already imported warnings):</p>

<pre><code>(virtual)$ cd ~
(virtual)$ python
&gt;&gt;&gt; import MySQLdb
</code></pre>

<p>If you don&#8217;t get an error all succeeded OK.</p>

<h2>Install Django</h2>

<pre><code>(virtual)$ pip install Django
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/04/how-to-install-python-on-dreamhost-shared-hosting/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>How to Automatically Log In Using SSH On Dreamhost</title>
		<link>http://blog.emson.co.uk/2009/09/how-to-automatically-log-in-using-ssh-on-dreamhost/</link>
		<comments>http://blog.emson.co.uk/2009/09/how-to-automatically-log-in-using-ssh-on-dreamhost/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 08:34:18 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[commands]]></category>
		<category><![CDATA[command line]]></category>
		<category><![CDATA[dreamhost]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=74</guid>
		<description><![CDATA[If you build web sites and host (or want to host) them on Dreamhost, you will be well aware that at some stage you will be using SSH to log in and out of your hosting server. If you have many sites then this gradually becomes tiresome &#8211; especially if you use tools like Capistrano [...]]]></description>
			<content:encoded><![CDATA[<p>If you build web sites and <a href="http://www.dreamhost.com/r.cgi?105422">host (or want to host) them on Dreamhost</a>, you will be well aware that at some stage you will be using SSH to log in and out of your hosting server. If you have many sites then this gradually becomes tiresome &#8211; especially if you use tools like <a href="http://www.capify.org/index.php/Capistrano">Capistrano</a> to deploy your applications, as you will constantly have to re-enter your passwords.</p>

<p>Fortunately you can certify your local computer, such that it will automatically enter the SSH password for you. Here are some quick tips on how to do it.</p>

<h3>Generate Your Security Keys</h3>

<p>Generate your private/public key pair on your local machine, from your home directory:</p>

<pre><code>ssh-keygen -d

Now DON'T enter a password - just press return, otherwise you 
will still need to enter a password, when you log in with SSH.
</code></pre>

<h3>Set Privileges And Copy The Public Key To Your Server</h3>

<p>Use the following command to copy your newly created <strong>~/.ssh/id_dsa.pub</strong> file up to the server you wish to remote log in to.  Note that this command below will set the permissions both locally and remotely. The remote .ssh/* needs to be set to 0600.</p>

<p>N.B. Replace USERNAME and MY_DOMAIN with your own username and domain.</p>

<pre><code>ssh USERNAME@ftp.MY_DOMAIN.COM 'test -d .ssh || mkdir -m 0700 .ssh ; cat &gt;&gt; .ssh/authorized_keys &amp;&amp; chmod 0600 .ssh/*' &lt; ~/.ssh/id_dsa.pub

  Enter the normal USERNAME password.
</code></pre>

<h3>Log In Using SSH</h3>

<p>Now log in using:</p>

<pre><code>ssh USERNAME@ftp.MY_DOMAIN.COM

You shouldn't neet to enter a password.
</code></pre>

<h3>Taking It Further</h3>

<p>To simplify things even further you can modify the <strong>~/.ssh/config</strong> file such:</p>

<pre><code>Host NICKNAME
Hostname MY_DOMAIN.COM
User USERNAME
</code></pre>

<p>Now you only need to type:</p>

<pre><code>ssh NICKNAME

And you will be automatically logged in.
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2009/09/how-to-automatically-log-in-using-ssh-on-dreamhost/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Create Sinatra Partials The Rails Way</title>
		<link>http://blog.emson.co.uk/2009/09/create-sinatra-partials-the-rails-way/</link>
		<comments>http://blog.emson.co.uk/2009/09/create-sinatra-partials-the-rails-way/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 08:09:57 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[sinatra]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=71</guid>
		<description><![CDATA[This is just a quick post. I&#8217;ve been playing around with the Sinatra micro web framework, and have to say that it is excellent. It really is the perfect tool for rapidly creating small and useful Ruby micro-sites.

Being small and lightweight it doesn&#8217;t have many of the features of larger frameworks like Ruby on Rails. [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a quick post. I&#8217;ve been playing around with the <a href="http://www.sinatrarb.com/">Sinatra micro web framework</a>, and have to say that it is excellent. It really is the perfect tool for rapidly creating small and useful <a href="http://www.ruby-lang.org/en/">Ruby</a> micro-sites.</p>

<p>Being small and lightweight it doesn&#8217;t have many of the features of larger frameworks like <a href="http://rubyonrails.org/">Ruby on Rails</a>. One of the features I&#8217;ve begun to need is the handling of Rails like partials.</p>

<p>Notably I need to pass both local variables and collections to the partial code and have the partials rendered accordingly.
I started implementing my own version, and then came across a nice little <a href="http://github.com/">Github</a> project: <a href="http://github.com/sbfaulkner/sinatra-helpers">Sinatra-Helpers by sbfaulkner</a>.</p>

<p>Anyway here is the code he uses for Sinatra partials:</p>

<pre><code>def haml_partial(name, options = {})
  item_name = name.to_sym
  counter_name = "#{name}_counter".to_sym
  if collection = options.delete(:collection)
    collection.enum_for(:each_with_index).collect do |item,index|
      haml_partial name, options.merge(:locals =&gt; {item_name =&gt; item, counter_name =&gt; index+1})
    end.join
  elsif object = options.delete(:object)
    haml_partial name, options.merge(:locals =&gt; {item_name =&gt; object, counter_name =&gt; nil})
  else
    haml "_#{name}".to_sym, options.merge(:layout =&gt; false)
  end
end
</code></pre>

<p>You can use his project or if you just need this feature just pop this code into your Sinatra helpers file  <strong>application_helper.rb</strong>:</p>

<pre><code>helpers do

  def partial(name, options = {})
    item_name = name.to_sym
    counter_name = "#{name}_counter".to_sym
    if collection = options.delete(:collection)
      collection.enum_for(:each_with_index).collect do |item, index|
        partial(name, options.merge(:locals =&gt; { item_name =&gt; item, counter_name =&gt; index + 1 }))
      end.join

    elsif object = options.delete(:object)
      partial name, options.merge(:locals =&gt; {item_name =&gt; object, counter_name =&gt; nil})
    else
      haml "_#{name}".to_sym, options.merge(:layout =&gt; false)
    end
  end
end
</code></pre>

<p>Now you can call the partial from a your page e.g. <strong>index.haml</strong></p>

<pre><code>= partial("mypartial", :locals =&gt; {:var1 =&gt; "value 1", :var2 =&gt; "value 2 and so on"})
</code></pre>

<p>Create a partial in the same directory as the calling page. Note that this code doesn&#8217;t like filenames truncated with a &#8216;-&#8217;, so avoid this if possible. Also like in Rails your partials should start with an underscore. e.g.  <strong>_mypartial.haml</strong></p>

<p>To access the variable from this partial simply call the local variable name in your code:</p>

<pre><code>%h2 
  This is var1:
  = var1

%p 
  And this is var2:
  = var2
</code></pre>

<p>Handling collections, again, is similar to the way Rails handles partial collections. From your page call the partial with a collection such as:</p>

<pre><code>= partial("listitem", :collection =&gt; ["item 1", "item 2 and so on"])
</code></pre>

<p>Now in the <strong>_listitem.haml</strong> partial code simply provide the partial name as a variable or the partialname with _counter for the increment number e.g.</p>

<pre><code>%li
  = listitem
  is the 
  = listitem_counter
  in this array
</code></pre>

<p>Anyway all pretty basic stuff but I hope it helps the casual Sinatra surfer.</p>

<p>Goodluck.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2009/09/create-sinatra-partials-the-rails-way/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>18 Useful bash scripts for web developers</title>
		<link>http://blog.emson.co.uk/2009/06/18-useful-bash-scripts-for-web-developers/</link>
		<comments>http://blog.emson.co.uk/2009/06/18-useful-bash-scripts-for-web-developers/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 10:22:15 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[commands]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=58</guid>
		<description><![CDATA[Using bash scripts to become a more efficient web developer

Here are a few scripts, that I find really useful for speeding up my web development time.

I&#8217;ve been building up this list as I needed to use them &#8211; so they maybe a little raw.

For example often clients send me images with filenames that don&#8217;t match [...]]]></description>
			<content:encoded><![CDATA[<h2>Using bash scripts to become a more efficient web developer</h2>

<p>Here are a few scripts, that I find really useful for speeding up my web development time.</p>

<p>I&#8217;ve been building up this list as I needed to use them &#8211; so they maybe a little raw.</p>

<p>For example often clients send me images with filenames that don&#8217;t match my naming standard, so running the appropriate script really helps keep me focussed on the job in hand and not waste too much time reformatting filenames etc.</p>

<p>Finally if you have any useful little bash scripts why don&#8217;t you add them to the comments below?</p>

<h3>Bash script to append a .txt extension to a filename</h3>

<p>Iterate over the current directory, get all files with .log and append .txt to the end of the entire filename:</p>

<pre><code>for i in *.log*; do mv "$i" "$i.txt"; done
</code></pre>

<h3>Script to make filenames lowercase</h3>

<p>Converts all the file names in a directory and converts them to lowercase.</p>

<p>echo version:</p>

<pre><code>for i in *.log*; do echo mv \"$i\" \"`echo $i| tr [A-Z] [a-z]`\"; done
</code></pre>

<p>real version:</p>

<pre><code>for i in *.txt; do mv "$i" "`echo $i| tr [A-Z] [a-z]`"; done
</code></pre>

<h3>Quick note on how to use grep to search for a string in file</h3>

<p>-o print Only the matched parts of a matching line, with each part on a separate line.
-H print the filename for each match.
-n prefix each line of output with the 1 based line number.
-R, -r recursively read all files under subdirectories.</p>

<pre><code>grep -oHnr "some pattern"  *.txt
</code></pre>

<p>{txt,log} this globs the file extensions together.
2>/dev/null this passes all errors to a blackhole, so that they won&#8217;t be displayed.</p>

<pre><code>grep 123741 ./adapter_logs/*.{txt,log} 2&gt;/dev/null
</code></pre>

<p>Find all occurrences of 123741 in all .txt and .log files in all subdirectories.</p>

<pre><code>for i in 'find . -type d'; do grep 123741 $i/*.{txt,log}; done 2&gt;/dev/null
</code></pre>

<h3>List all files that match this regular expression in the current direcory</h3>

<p>All files with the number 5 in their name.</p>

<pre><code>ls | grep -e .*5.*
</code></pre>

<h3>Bash script to check whether a tag exists in a subversion repository</h3>

<pre><code>svn ls http://www.mysvnserver.co.uk/myproject/tags | grep mytag-0.7.0.1/
</code></pre>

<p>The [ ] is known as a Test, by default it tests integers
Also to end an if statement you use fi</p>

<pre><code>if [ 1 = 1 ] ; then echo YES; else echo NO; fi

if [ "`svn ls http://mysvnserver/mysvnrepository/myproject/tags | grep R-9.20.400.0/`" = "R-9.20.400.0/" ]; then echo YES; else echo NO; fi
</code></pre>

<p>Note need the / in the evaluation part of &#8220;it-0.9.0.7/&#8221;, don&#8217;t really need it in grep it-0.9.0.7/</p>

<pre><code>$ if [ "`svn ls http://www.mysvnserver.co.uk/myproject/tags | grep it-0.7.0.1/`" = "it-0.7.0.1/" ]; then echo YES; else echo NO; fi
</code></pre>

<h3>Quick note on how to increment a variable, in a bash script</h3>

<pre><code>j=0; j=$(($j+1))
</code></pre>

<p>incrementing in a loop</p>

<pre><code>j=0;for i in *.txt; do echo "some_file_"$j".txt"; j=$(($j+1)); done
</code></pre>

<h3>Using a bash for loop to list all text files and append whoopee</h3>

<pre><code>for i in *.txt; do echo $i"whoopee"; done
</code></pre>

<h3>Change all filenames to be a specific incremented name, starting from file 16</h3>

<pre><code>j=16;for i in *.jpg; do mv "$i" "gallery_"$j".jpg"; j=$(($j+1)); done;ls
</code></pre>

<h3>Script to loop through all .txt filenames and make them lower case</h3>

<pre><code>for i in *.txt; do mv "$i" "`echo $i| tr [A-Z] [a-z]`"; done
</code></pre>

<h3>Get all JPG files and create the appropriate HTML list tags for them and add them to a file</h3>

<p>Create an HTML version:</p>

<pre><code>for i in *.jpg; do echo "\t&lt;li&gt;\r\t\t&lt;img src='images/$i' alt='' /&gt;\r\t&lt;/li&gt;"; done &gt; list_items.html
</code></pre>

<p>Create a HAML version:</p>

<pre><code>for i in *.jpg; do echo "\t%li\r\t\t%img{ :src =&gt; 'images/$i', :alt =&gt; '' }\r"; done &gt; imgs.haml
</code></pre>

<h3>Batch change a misspelled filename of certain files, using string replacement</h3>

<pre><code>for i in aples*.jpg; do mv $i ${i/aples/apples} ; done
</code></pre>

<h3>Script to batch create files based on filenames in a file</h3>

<p>Create a file called something like &#8220;my_files.txt&#8221; with the following content:</p>

<blockquote>
  <p>archive_error_112480_0040.txt
  archive_error_114390_0043.txt
  etc&#8230;</p>
</blockquote>

<p>Commands:</p>

<pre><code>for i in `sed -n -e 'p' my_files.txt`; do mkdir a_test/$i; done
or
while read x; do touch $x; done &lt; my_files.txt
or
cat my_files.txt | xargs touch
(xargs passes each line as an argument into EACH touch)
</code></pre>

<h3>Using bash Expansions, and allow escapes</h3>

<p>-e is an undocumented flag that allows escapes
Expansion ${command/parameter/substitution} everything else needs to be escaped.</p>

<pre><code>echo -e ${PATH//\:/\\n}
</code></pre>

<h3>Executing a .bash_script after making changes</h3>

<pre><code>source .bash_profile
or
. .bash_profile
</code></pre>

<p>NB: you can &#8216;include&#8217; other bash .sh scripts in a .bash_profile file by using &#8217;source&#8217; or &#8216;.&#8217;</p>

<h3>Quick tip on using curl for downloading files off the web</h3>

<p>Use -O to name the remote file, curl will save it locally but remove the rest of the path.</p>

<pre><code>curl -O http://rubyforge-files.ruby-forum.com/rubygems/rubygems-0.9.0.tgz
</code></pre>

<h3>Bash command for testing the existence of files and directories</h3>

<p>If a directory does NOT exist create it</p>

<pre><code>[ -d "/var/cache/git" ] || mkdir /var/cache/git
</code></pre>

<p>If a file exists echo a message:</p>

<pre><code>[ -f "./new_file.txt" ] &amp;&amp; echo "its there"
</code></pre>

<h3>Bash command to remove spaces from filenames</h3>

<pre><code>for i in *.html; do mv "$i" "`echo $i| tr -d ' '`"; done
</code></pre>

<p>replace spaces for underscores</p>

<pre><code>for i in *.html; do mv "$i" "`echo $i| tr ' ' '_'`"; done
</code></pre>

<p>Vim regex to replace spaces in images file names of ah HTML page</p>

<pre><code>:%s:\(images\/\)\(\w\+\)\s\(\w\+\.jpg\):\1\2_\3:g
</code></pre>

<h3>Copy text to the clipboard</h3>

<pre><code>echo 'hello world'|pbcopy
cmd + v
</code></pre>

<h2>Conclusion</h2>

<p>Some of these are quite basic but useful none-the-less, please add your own to the comments below.
Many thanks, and good luck.</p>

<h2>Updated&#8230;</h2>

<h3>Script function for .bash_profile to cd to the last opened finder location</h3>

<p>This is a script written by a colleague.  <a href="http://www.visualcortex.co.uk/">James Power</a>.
Add the following function to your <strong>.bash_profile</strong> in Apple OSX.  Now open a directory in Finder, then open terminal and type <strong>cdf</strong>, your terminal will now change directory to the same one as the last Finder opened.</p>

<pre><code># function to change directory to the one set in the last opened finder.
cdf () {
   currFolderPath=$( /usr/bin/osascript &lt;&lt;"         EOT"
       tell application "Finder"
           try
               set currFolder to (folder of the front window as alias)
           on error
               set currFolder to (path to desktop folder as alias)
           end try
           POSIX path of currFolder
       end tell
            EOT
   )
   echo "cd to \"$currFolderPath\""
   cd "$currFolderPath"
}
</code></pre>

<p>Also for a much more comprehensive list of commands check out: <a href="http://www.commandlinefu.com/commands/tagged/34/bash">http://www.commandlinefu.com/commands/tagged/34/bash</a></p>

<h3>Ruby Rush command-line tool</h3>

<p>If you use <strong>Ruby</strong> maybe check out <a href="http://rush.heroku.com/">Rush</a>, it allows you do use Ruby in a bash command-line like way.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2009/06/18-useful-bash-scripts-for-web-developers/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Halcyon Events logo on Jenson Button&#8217;s Formula One helmet</title>
		<link>http://blog.emson.co.uk/2009/03/halcyon-events-logo-on-jenson-buttons-formula-one-helmet/</link>
		<comments>http://blog.emson.co.uk/2009/03/halcyon-events-logo-on-jenson-buttons-formula-one-helmet/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 14:26:30 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[sport]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=35</guid>
		<description><![CDATA[Jenson Button has just got pole position ready for the Australian Formula One race tomorrow.  This is pretty exciting as on either side of his helmet is the Halcyon Events Ltd. logo.

Halcyon Events is a company that specialises in high end bespoke Formula One events.  Through their contacts they can take you and [...]]]></description>
			<content:encoded><![CDATA[<p>Jenson Button has just got pole position ready for the Australian Formula One race tomorrow.  This is pretty exciting as on either side of his helmet is the <a href="http://www.halcyonsport.com">Halcyon Events Ltd. logo.</a></p>

<div id="attachment_39" class="wp-caption alignnone" style="width: 510px"><a href="http://www.halcyonsport.com"><img src="http://blog.emson.co.uk/wp-content/uploads/2009/03/helmet_logo.jpg" alt="Jenson Button&#039;s Helmet with Halcyon Logo" title="helmet_logo" width="500" height="333" class="size-full wp-image-39" /></a><p class="wp-caption-text">Jenson Button's Helmet with Halcyon Logo</p></div>

<p><a href="http://www.halcyonsport.com">Halcyon Events</a> is a company that specialises in high end bespoke Formula One events.  Through their contacts they can take you and your clients behind the scenes to areas not normally permitted, and give you a unique experience into Formula One (F1).</p>

<p>The web site was built by me, the design was created by <a href="http://www.scamperbranding.com/">Scamper Branding</a> and the logo on Jenson&#8217;s helmet was designed by <a href="http://www.fireflycreative.co.uk/">Firefly Creative</a>.</p>

<p><a href="http://www.fireflycreative.com"><img src="http://blog.emson.co.uk/wp-content/uploads/2009/03/fireflylogo_sml.jpg" alt="Firefly Creative logo" title="Firefly Creative logo" width="150" height="49" /></a></p>

<p>Anyway fingers crossed for Jenson Button to win the Australian Grand Prix!.</p>

<p><strong>&#8211; Update &#8211;</strong> Fantastic Jenson Button won the Melbourne Grand Prix!  How exciting.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2009/03/halcyon-events-logo-on-jenson-buttons-formula-one-helmet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
