<?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>Sugus &#187; code snipplets</title>
	<atom:link href="http://diffract.me/category/code-snipplets/feed/" rel="self" type="application/rss+xml" />
	<link>http://diffract.me</link>
	<description>Specifically Unwanted Gathering of Under-appreciated Stuff</description>
	<lastBuildDate>Thu, 11 Mar 2010 11:24:36 +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>Websockets tutorial/example with pywebsocket</title>
		<link>http://diffract.me/2009/12/websockets-tutorialexample-with-pywebsocket/</link>
		<comments>http://diffract.me/2009/12/websockets-tutorialexample-with-pywebsocket/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 12:37:24 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[computers]]></category>
		<category><![CDATA[experiments]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=634</guid>
		<description><![CDATA[<p>As everyone already knows, Google Chrome now supports websockets. In essence, this allows you to keep a connection open with a webserver indefinitely (analogous to typical sockets) and send data bi-directionally. Unfortunately Chrome is the only browser currently supporting this, but I&#8217;m pretty sure this will change.</p>
<p>So I decided to (...)<br/ >[<a href="http://diffract.me/2009/12/websockets-tutorialexample-with-pywebsocket/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2010/01/my-small-pywebsocket-tutorial/' rel='bookmark' title='Permanent Link: My small pywebsocket tutorial &#8230;'>My small pywebsocket tutorial &#8230;</a></li>
<li><a href='http://diffract.me/2009/10/fabric-for-remote-deployment/' rel='bookmark' title='Permanent Link: Fabric for remote deployment'>Fabric for remote deployment</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>As everyone already knows, <a href="http://www.google.com/chrome">Google Chrome</a> now supports <a href="http://dev.w3.org/html5/websockets/#websocket">websockets</a>. In essence, this allows you to keep a connection open with a webserver indefinitely (analogous to typical sockets) and send data bi-directionally. Unfortunately Chrome is the only browser currently supporting this, but I&#8217;m pretty sure this will change.</p>
<p>So I decided to give this a try and experiment a bit with it. This is my step by step process on getting a web page opening a websocket to a server and receiving the server&#8217;s date and time every second. It is based on an <a href="http://armstrongonsoftware.blogspot.com/2009/12/comet-is-dead-long-live-websockets.html">article by Joe Armstrong</a>, though he uses <a href="http://ftp.sunet.se/pub/lang/erlang/">Erlang</a> for the server, while I decided to follow the easy road and use <a href="http://code.google.com/p/pywebsocket/">Google&#8217;s pywebsocket</a> &#8211; an apache module (uses mod_python) that allows you to create handlers for websocket connections in a easy-to-use fashion. The code also contains a way to start a standalone server (i.e. not requiring apache) for testing purposes.</p>
<p>So here are the steps I took to get this working:</p>
<h4>1. Create a web page</h4>
<p>This is the code I borrowed from Joe, though slightly modified to fit my purposes (it requires <a href="http://jquery.com/">jquery</a>, by the way):</p>
<pre>&lt;html&gt;

&lt;head&gt;

&lt;script src="jquery-1.3.2.min.js"&gt;&lt;/script&gt;
&lt;script&gt;

$(document).ready(function(){

var ws;

if ("WebSocket" in window) {
debug("Horray you have web sockets. Trying to connect...");
ws = new WebSocket("ws://localhost:9998/echo");

ws.onopen = function() {
// Web Socket is connected. You can send data by send() method.
debug("connected...");
ws.send("hello from the browser");
ws.send("more from browser");
};

run = function() {
var val=$("#i1").val(); // read the entry
$("#i1").val("");       // and clear it
ws.send(val);           // tell erlang
return true;            // must do this
};

ws.onmessage = function (evt)
{
//alert(evt.data);
var data = evt.data;
var i = data.indexOf("!");
var tag = data.slice(0,i);
var val = data.slice(i+1);
$("#" + tag).html(val);
};

ws.onclose = function()
{
debug(" socket closed");
};
} else {
alert("You have no web sockets");
};

function debug(str){
$("#debug").append("&lt;p&gt;" +  str);
};

});
&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;h1&gt;Interaction experiment&lt;/h1&gt;

&lt;h2&gt;Debug&lt;/h2&gt;
&lt;div id="debug"&gt;&lt;/div&gt;

&lt;fieldset&gt;
&lt;legend&gt;Clock&lt;/legend&gt;
&lt;div id="clock"&gt;I am a clock&lt;/div&gt;
&lt;/fieldset&gt;

&lt;/body&gt;

&lt;/html&gt;</pre>
<h4>2. Download and install pywebsocket</h4>
<p>Checkout the code with</p>
<pre><span>svn checkout http</span><span>:</span><span>//pywebsocket.googlecode.com/svn/trunk/ pywebsocket-read-only
</span></pre>
<p>Then do <strong>python setup.py build</strong> and <strong>sudo python setup.py install</strong> inside the <strong>src</strong> folder. This will install it into your python environment.</p>
<h4>3. Being lazy, means we will change an example handler</h4>
<p>The way pywebsocket works is delegating the connections to something they call handlers. In the <strong><span>pywebsocket-read-only/src/example</span></strong><span> folder you will find a file named <strong>echo_wsh.py</strong>. They have this convention where handlers are named <strong>&lt;entry_point&gt;_wsh.py</strong>. This means that when you later call (from your web page) the url <strong>http://localhost:9998/echo</strong> the server will delegate the processing of that connection to that file.</span></p>
<p><span>I modified that file to something like this:</span></p>
<pre># Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from mod_pywebsocket import msgutil
from datetime import datetime
import time

_GOODBYE_MESSAGE = 'Goodbye'

def web_socket_do_extra_handshake(request):
 print 'Connected.'
 pass  # Always accept.

def web_socket_transfer_data(request):
 while True:
 time.sleep(1)
 date = datetime.now()
 #try:
 #    line = msgutil.receive_message(request)
 #except Exception, e:
 #    print 'Foi com os porcos'
 #    raise e
 #print 'Got something: %s' % line
 #msgutil.send_message(request, line)
 msgutil.send_message(request, 'clock!%s' % date)
 #if line == _GOODBYE_MESSAGE:
 #    return</pre>
<p>So basically whenever a new connection is made to this entry point, a call to <strong>web_socket_do_extra_handshake</strong> is made. After that, <strong>web_socket_transfer_data</strong> is called and it&#8217;s your responsibility to create the loop that receives messages and handles the flow (as you can see in the commented lines). I don&#8217;t care about that right now, since I only want to push the date and time to the client every second.</p>
<h4>3. Start the standalone server</h4>
<p>Go to the <strong><span>pywebsocket-read-only/src/mod_pywebsocket</span></strong> folder and run the following command:</p>
<pre>sudo python standalone.py -p 9998 -w ../example/</pre>
<p>This will start the server in port 9998 and use the handlers directory specified by the -w option. That is where our echo_wsh.py lives.</p>
<h4>4. Test it <img src='http://diffract.me/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </h4>
<p>So now open your browser (remember, only chrome supports websockets currently) and open the html file your created in the beginning. Voilá, server&#8217;s date and time every second in the clock div.</p>


<p>Related posts:<ol><li><a href='http://diffract.me/2010/01/my-small-pywebsocket-tutorial/' rel='bookmark' title='Permanent Link: My small pywebsocket tutorial &#8230;'>My small pywebsocket tutorial &#8230;</a></li>
<li><a href='http://diffract.me/2009/10/fabric-for-remote-deployment/' rel='bookmark' title='Permanent Link: Fabric for remote deployment'>Fabric for remote deployment</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/12/websockets-tutorialexample-with-pywebsocket/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Android location provider mock</title>
		<link>http://diffract.me/2009/11/android-location-provider-mock/</link>
		<comments>http://diffract.me/2009/11/android-location-provider-mock/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 15:50:42 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[computers]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=578</guid>
		<description><![CDATA[<p>So, yeah, I resumed playing around with android, this time version 2.0.</p>
<p>I&#8217;m really tempted to buy the new Motorola Milestone that should come out in Europe sometime between&#8230; now&#8230; and early next year, so I wanna be ready to create all the crazy stuff I have in mind for it (...)<br/ >[<a href="http://diffract.me/2009/11/android-location-provider-mock/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2009/07/ssh-login-without-password-authorized_keys/' rel='bookmark' title='Permanent Link: SSH login without password (authorized_keys)'>SSH login without password (authorized_keys)</a></li>
<li><a href='http://diffract.me/2009/01/double-clicktap-detection-on-androids-mapview/' rel='bookmark' title='Permanent Link: Double click/tap detection on android&#8217;s MapView'>Double click/tap detection on android&#8217;s MapView</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>So, yeah, I resumed playing around with android, this time version 2.0.</p>
<p>I&#8217;m really tempted to buy the new <a href="http://developer.motorola.com/products/milestone/">Motorola Milestone</a> that should come out in Europe sometime between&#8230; now&#8230; and early next year, so I wanna be ready to create all the crazy stuff I have in mind for it <img src='http://diffract.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>One of the things I noticed was that it&#8217;s not that straightforward to provide sample GPS data. Somehow the emulator&#8217;s GPX and KMZ functionality is not working fine for me and, even if it was, I don&#8217;t want to load the file everytime (i.e. I&#8217;m lazy).</p>
<p>So, after some googling around, here&#8217;s my solution to read points from a file and feed them 1 per second to the location manager, so I can finally work with them in my app:</p>
<p>My main activity implements <strong>LocationListener</strong>, so it can be passed to the <strong>LocationManager</strong> to receive GPS events. Here&#8217;s what I do when creating my activity:</p>
<pre>public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		((TextView) this.findViewById(R.id.textView)).setText("Something else");

		// LocationManager locationManager = (LocationManager)
		// getSystemService(Context.LOCATION_SERVICE);
		// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		// 0, 0, this);

		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		String mocLocationProvider = LocationManager.GPS_PROVIDER;
		locationManager.addTestProvider(mocLocationProvider, false, false,
				false, false, true, true, true, 0, 5);
		locationManager.setTestProviderEnabled(mocLocationProvider, true);
		locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, this);

		try {

			List data = new ArrayList();
			InputStream is = getAssets().open("data.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = reader.readLine()) != null) {

				data.add(line);
			}
			Log.e(LOG_TAG, data.size() + " lines");

			new MockLocationProvider(locationManager, mocLocationProvider, data).start();

		} catch (IOException e) {

			e.printStackTrace();
		}
	}</pre>
<p>This will basically setup the test location provider and read the points into a list. Then I feed that stuff to my mock location provider (just a normal thread) that will read them 1 per second and trigger the new location back to this activity. Here&#8217;s the code for <strong>MockLocationProvider</strong>:</p>
<pre>public class MockLocationProvider extends Thread {

    private List data;

    private LocationManager locationManager;

    private String mocLocationProvider;

    private String LOG_TAG = "faren";

    public MockLocationProvider(LocationManager locationManager,
            String mocLocationProvider, List data) throws IOException {

        this.locationManager = locationManager;
        this.mocLocationProvider = mocLocationProvider;
        this.data = data;
    }

    @Override
    public void run() {

        for (String str : data) {

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

            // Set one position
            String[] parts = str.split(",");
            Double latitude = Double.valueOf(parts[0]);
            Double longitude = Double.valueOf(parts[1]);
            Double altitude = Double.valueOf(parts[2]);
            Location location = new Location(mocLocationProvider);
            location.setLatitude(latitude);
            location.setLongitude(longitude);
            location.setAltitude(altitude);

            Log.e(LOG_TAG, location.toString());

            // set the time in the location. If the time on this location
            // matches the time on the one in the previous set call, it will be
            // ignored
            location.setTime(System.currentTimeMillis());

            locationManager.setTestProviderLocation(mocLocationProvider,
                    location);
        }
    }
}</pre>
<p>Notice the <em><strong>location.setTime()</strong></em> call. Read the comment why it is necessary. Took me forever to find this one in google <img src='http://diffract.me/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Peace and great Androiding <img src='http://diffract.me/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/07/ssh-login-without-password-authorized_keys/' rel='bookmark' title='Permanent Link: SSH login without password (authorized_keys)'>SSH login without password (authorized_keys)</a></li>
<li><a href='http://diffract.me/2009/01/double-clicktap-detection-on-androids-mapview/' rel='bookmark' title='Permanent Link: Double click/tap detection on android&#8217;s MapView'>Double click/tap detection on android&#8217;s MapView</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/11/android-location-provider-mock/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Grabbing title tag from web page</title>
		<link>http://diffract.me/2009/10/grabbing-title-tag-from-web-page/</link>
		<comments>http://diffract.me/2009/10/grabbing-title-tag-from-web-page/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 13:16:24 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[computers]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=433</guid>
		<description><![CDATA[<p>At least a couple of options, the first using BeautifulSoup:</p>
<pre>import urllib
import BeautifulSoup

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen("https://www.google.com"))
print soup.title.string</pre>
<p>And the second one using lxml:</p>
<pre>import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text</pre>


<p>Related posts:Several years of email statistics &#8211; code included
Double click/tap detection on android&#8217;s MapView
</p>


Related posts:<ol><li><a href='http://diffract.me/2009/07/several-years-of-email-statistics-code-included/' rel='bookmark' title='Permanent Link: Several years of email statistics &#8211; code included'>Several years of email statistics &#8211; code included</a></li>
<li><a href='http://diffract.me/2009/01/double-clicktap-detection-on-androids-mapview/' rel='bookmark' title='Permanent Link: Double click/tap detection on android&#8217;s MapView'>Double click/tap detection on android&#8217;s MapView</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>At least a couple of options, the first using <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>:</p>
<pre>import urllib
import BeautifulSoup

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen("https://www.google.com"))
print soup.title.string</pre>
<p>And the second one using <a href="http://codespeak.net/lxml/">lxml</a>:</p>
<pre>import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text</pre>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/07/several-years-of-email-statistics-code-included/' rel='bookmark' title='Permanent Link: Several years of email statistics &#8211; code included'>Several years of email statistics &#8211; code included</a></li>
<li><a href='http://diffract.me/2009/01/double-clicktap-detection-on-androids-mapview/' rel='bookmark' title='Permanent Link: Double click/tap detection on android&#8217;s MapView'>Double click/tap detection on android&#8217;s MapView</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/10/grabbing-title-tag-from-web-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django template filter: Show list of objects as table with fixed number of columns</title>
		<link>http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/</link>
		<comments>http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 12:14:41 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[computers]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=414</guid>
		<description><![CDATA[<p>I recently ran into the following problem: I needed to be able to display a list of users in a table that had a maximum of X columns. Since I could not find the solution on the Internet I decided to give it a try and here is my resulting (...)<br/ >[<a href="http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2009/08/django-dynamic-redirection-after-login/' rel='bookmark' title='Permanent Link: [Django] Dynamic redirection after login'>[Django] Dynamic redirection after login</a></li>
<li><a href='http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/' rel='bookmark' title='Permanent Link: Django: Reverse HTTP redirect with parameters'>Django: Reverse HTTP redirect with parameters</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I recently ran into the following problem: I needed to be able to display a list of users in a table that had a maximum of X columns. Since I could not find the solution on the Internet I decided to give it a try and here is my resulting template filter to do it:</p>
<pre>def tablecols(data, cols):
    rows = []
    row = []
    index = 0
    for user in data:
        row.append(user)
        index = index + 1
        if index % cols == 0:
            rows.append(row)
            row = []
    # Still stuff missing?
    if len(row) &gt; 0:
        rows.append(row)
    return rows
register.filter_function(tablecols)</pre>
<p>Then you can use it in your templates like so:</p>
<pre>&lt;table&gt;
{% for row in members|tablecols:5 %}
    &lt;tr&gt;
    {% for member in row %}
        &lt;td&gt;
            {% show_simple_profile member user %}
        &lt;/td&gt;
    {% endfor %}
    &lt;/tr&gt;
{% endfor %}
&lt;/table&gt;</pre>
<p>It will break down the &#8220;members&#8221; list into a list of lists, each of the first being a group of (in this case) 5 users max.</p>
<p>Have fun <img src='http://diffract.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/08/django-dynamic-redirection-after-login/' rel='bookmark' title='Permanent Link: [Django] Dynamic redirection after login'>[Django] Dynamic redirection after login</a></li>
<li><a href='http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/' rel='bookmark' title='Permanent Link: Django: Reverse HTTP redirect with parameters'>Django: Reverse HTTP redirect with parameters</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python: Sort list of tuples by second item</title>
		<link>http://diffract.me/2009/09/sort-list-of-tuples-by-second-item/</link>
		<comments>http://diffract.me/2009/09/sort-list-of-tuples-by-second-item/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 11:38:01 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=401</guid>
		<description><![CDATA[<p>Straight from the PythonInfo Wiki:</p>
<pre>&#62;&#62;&#62; import operator
&#62;&#62;&#62; L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
&#62;&#62;&#62; map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
&#62;&#62;&#62; map(operator.itemgetter(1), L)
[2, 1, 4, 3]
&#62;&#62;&#62; sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]</pre>


<p>Related posts:Django template filter: Show list of objects as table with fixed number of columns
JIRA (...)<br/ >[<a href="http://diffract.me/2009/09/sort-list-of-tuples-by-second-item/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/' rel='bookmark' title='Permanent Link: Django template filter: Show list of objects as table with fixed number of columns'>Django template filter: Show list of objects as table with fixed number of columns</a></li>
<li><a href='http://diffract.me/2009/08/jira-issues-reporting-with-python/' rel='bookmark' title='Permanent Link: JIRA issues reporting with Python'>JIRA issues reporting with Python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Straight from the <a href="http://wiki.python.org/moin/HowTo/Sorting">PythonInfo Wiki</a>:</p>
<pre>&gt;&gt;&gt; import operator
&gt;&gt;&gt; L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
&gt;&gt;&gt; map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
&gt;&gt;&gt; map(operator.itemgetter(1), L)
[2, 1, 4, 3]
&gt;&gt;&gt; sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]</pre>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/09/django-template-filter-show-list-of-objects-as-table-with-fixed-number-of-columns/' rel='bookmark' title='Permanent Link: Django template filter: Show list of objects as table with fixed number of columns'>Django template filter: Show list of objects as table with fixed number of columns</a></li>
<li><a href='http://diffract.me/2009/08/jira-issues-reporting-with-python/' rel='bookmark' title='Permanent Link: JIRA issues reporting with Python'>JIRA issues reporting with Python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/09/sort-list-of-tuples-by-second-item/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django: Reverse HTTP redirect with parameters</title>
		<link>http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/</link>
		<comments>http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 10:08:52 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[computers]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=376</guid>
		<description><![CDATA[<p>Here&#8217;s how to, from a view, redirect to another URL passing parameters to it. For instance, to redirect the user to a certain page after login:</p>
<pre>return HttpResponseRedirect(reverse('dz_details', kwargs={'dz_id':dz.id}))</pre>
<p>This will lookup the &#8216;dz_details&#8217; name in your urls.py file, which could be defined like so:</p>
<pre>url(r'^details/(\d+)/$', views.dz_details, name='dz_details'),</pre>
<p>There is a simpler way to (...)<br/ >[<a href="http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2009/08/django-dynamic-redirection-after-login/' rel='bookmark' title='Permanent Link: [Django] Dynamic redirection after login'>[Django] Dynamic redirection after login</a></li>
<li><a href='http://diffract.me/2009/08/java-http-proxy-servlet-with-spring/' rel='bookmark' title='Permanent Link: Java HTTP proxy servlet (with Spring)'>Java HTTP proxy servlet (with Spring)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s how to, from a view, redirect to another URL passing parameters to it. For instance, to redirect the user to a certain page after login:</p>
<pre>return HttpResponseRedirect(reverse('dz_details', kwargs={'dz_id':dz.id}))</pre>
<p>This will lookup the &#8216;dz_details&#8217; name in your urls.py file, which could be defined like so:</p>
<pre>url(r'^details/(\d+)/$', views.dz_details, name='dz_details'),</pre>
<p>There is a simpler way to do it, if you don&#8217;t want to use the parameters&#8217; names, but you have to know the order on which they appear in the method:</p>
<pre>return HttpResponseRedirect(reverse('dz_details', args=[ dz.id ]))</pre>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/08/django-dynamic-redirection-after-login/' rel='bookmark' title='Permanent Link: [Django] Dynamic redirection after login'>[Django] Dynamic redirection after login</a></li>
<li><a href='http://diffract.me/2009/08/java-http-proxy-servlet-with-spring/' rel='bookmark' title='Permanent Link: Java HTTP proxy servlet (with Spring)'>Java HTTP proxy servlet (with Spring)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[Django] Dynamic redirection after login</title>
		<link>http://diffract.me/2009/08/django-dynamic-redirection-after-login/</link>
		<comments>http://diffract.me/2009/08/django-dynamic-redirection-after-login/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 17:17:24 +0000</pubDate>
		<dc:creator>Pedro Assuncao</dc:creator>
				<category><![CDATA[code snipplets]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://diffract.me/?p=344</guid>
		<description><![CDATA[<p>Here&#8217;s how to redirect to the login page in django, making it go to a certain view (by name) after a successful login:</p>
<pre>login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index'))
return HttpResponseRedirect(login_url)</pre>
<p>Notes:</p>

acct_login is django&#8217;s view name for the login page (double check this, as it might change in future django versions);
jumplog_index is the (...)<br/ >[<a href="http://diffract.me/2009/08/django-dynamic-redirection-after-login/">continue reading</a>]


Related posts:<ol><li><a href='http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/' rel='bookmark' title='Permanent Link: Django: Reverse HTTP redirect with parameters'>Django: Reverse HTTP redirect with parameters</a></li>
<li><a href='http://diffract.me/2008/06/django-in-appengine/' rel='bookmark' title='Permanent Link: Django in AppEngine'>Django in AppEngine</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s how to redirect to the login page in django, making it go to a certain view (by name) after a successful login:</p>
<pre>login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index'))
return HttpResponseRedirect(login_url)</pre>
<p>Notes:</p>
<ul>
<li><strong>acct_login</strong> is django&#8217;s view name for the login page (double check this, as it might change in future django versions);</li>
<li><strong>jumplog_index</strong> is the target view where I want the user to go after successfully logging in.</li>
</ul>
<p>UPDATE: An alternative, much more awesome, is to use the @login_required decorator on the view you want login to be required. Like so:</p>
<pre>@login_required
def index(request):
   # Your code here</pre>
<p>The decorator can be imported from this module:</p>
<pre>from django.contrib.auth.decorators import login_required</pre>
<p>I guess the first dirtier method can be used when you want to do something more custom, like sending some data to the login view, or something like that <img src='http://diffract.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Thanks for the tip, Steve <img src='http://diffract.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>


<p>Related posts:<ol><li><a href='http://diffract.me/2009/08/django-reverse-http-redirect-with-parameters/' rel='bookmark' title='Permanent Link: Django: Reverse HTTP redirect with parameters'>Django: Reverse HTTP redirect with parameters</a></li>
<li><a href='http://diffract.me/2008/06/django-in-appengine/' rel='bookmark' title='Permanent Link: Django in AppEngine'>Django in AppEngine</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://diffract.me/2009/08/django-dynamic-redirection-after-login/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
