<?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>Chui's counterpoint &#187; Python</title>
	<atom:link href="http://www.redmountainsw.com/wordpress/archives/category/python/feed" rel="self" type="application/rss+xml" />
	<link>http://www.redmountainsw.com/wordpress</link>
	<description>pulling the rug</description>
	<lastBuildDate>Fri, 19 Mar 2010 03:35:21 +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>Python Memory Usage using __slots__</title>
		<link>http://www.redmountainsw.com/wordpress/archives/python-memory-usage-using-__slots__</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/python-memory-usage-using-__slots__#comments</comments>
		<pubDate>Fri, 27 Nov 2009 16:59:33 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=880</guid>
		<description><![CDATA[I have been trying to reduce memory usage on our application server, and experimented with using __slots__ to reduce memory usage.
The memory overhead of using __dict__ vs __slots__ turned out to be 147 bytes per object.
Here are my results



Test
Total Memory
Bytes per object


slots
40880K
41


dicts
183840K
188



Using the following test script

class C(object):
#__slots__ = (&#039;abc&#039;, &#039;defg&#039;)
pass

a = []
for i in xrange(1000000):
c [...]]]></description>
			<content:encoded><![CDATA[<p>I have been trying to reduce memory usage on our application server, and experimented with using __slots__ to reduce memory usage.</p>
<p>The memory overhead of using __dict__ vs __slots__ turned out to be 147 bytes per object.</p>
<p>Here are my results</p>
<table border="0">
<tbody>
<tr>
<th>Test</th>
<th>Total Memory</th>
<th>Bytes per object</th>
</tr>
<tr>
<td>slots</td>
<td>40880K</td>
<td>41</td>
</tr>
<tr>
<td>dicts</td>
<td>183840K</td>
<td>188</td>
</tr>
</tbody>
</table>
<p>Using the following test script</p>
<pre class="brush: python">
class C(object):
#__slots__ = (&#039;abc&#039;, &#039;defg&#039;)
pass

a = []
for i in xrange(1000000):
c = C()
c.abc = 1
c.defg = 2
a.append(c)
</pre>
<p>That&#8217;s quite promising. Now, if I can make that work with our in-house ORM.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/python-memory-usage-using-__slots__/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Converting a .dotx file to a .docx file with Python</title>
		<link>http://www.redmountainsw.com/wordpress/archives/converting-a-dotx-file-to-a-docx-file-with-python</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/converting-a-dotx-file-to-a-docx-file-with-python#comments</comments>
		<pubDate>Mon, 19 Oct 2009 02:42:58 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=859</guid>
		<description><![CDATA[It used to be that one could simply rename a Word Template .dot file to .doc. However, Microsoft has made it somewhat harder today.
One way to do this is through using Word Automation. However, another way is to do some XML manipulation, given that .dotx and .dotcx files are actually zip archives.

import xml.dom.minidom
import zipfile

def dotx2docx(src, [...]]]></description>
			<content:encoded><![CDATA[<p>It used to be that one could simply rename a Word Template .dot file to .doc. However, Microsoft has made it somewhat harder today.</p>
<p>One way to do this is through using Word Automation. However, another way is to do some XML manipulation, given that .dotx and .dotcx files are actually zip archives.</p>
<pre class="brush: python">
import xml.dom.minidom
import zipfile

def dotx2docx(src, dst)

    OLD_CONTENT_TYPE = &quot;application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml&quot;
    NEW_CONTENT_TYPE = &quot;application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml&quot;
    CONTENTTYPE_FILENAME = &#039;[Content_Types].xml&#039;
    arc_in  = zipfile.ZipFile(src, &#039;r&#039;)
    arc_out = zipfile.ZipFile(dst, &#039;w&#039;)
    for zinfo in arc_in.infolist():
        if zinfo.filename == CONTENTTYPE_FILENAME:
                doc = xml.dom.minidom.parseString(arc_in.read(CONTENTTYPE_FILENAME))
                els = doc.getElementsByTagName(&#039;Override&#039;)
                for el in els:
                    attr_contenttype = el.getAttribute(&#039;ContentType&#039;)
                    if attr_contenttype == OLD_CONTENT_TYPE:
                        if el.getAttribute(&#039;PartName&#039;) == &#039;/word/document.xml&#039;:
                            el.setAttribute(&#039;ContentType&#039;, NEW_CONTENT_TYPE)
                arc_out.writestr(CONTENTTYPE_FILENAME, doc.toxml())
                doc.unlink()
        else:
            contents = arc_in.read(zinfo.filename)
            arc_out.writestr(zinfo.filename, contents)
    arc_in.close()
    arc_out.close()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/converting-a-dotx-file-to-a-docx-file-with-python/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Printing the current running stack in Python</title>
		<link>http://www.redmountainsw.com/wordpress/archives/printing-the-current-running-stack-in-python</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/printing-the-current-running-stack-in-python#comments</comments>
		<pubDate>Thu, 23 Jul 2009 23:30:37 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/archives/printing-the-current-running-stack-in-python</guid>
		<description><![CDATA[The traceback module has utility functions for printing the currently running stack, not just tracebacks.

import traceback
import logging

# somewhere in your buggy code
logging.log(1, &#34;&#34;.join(traceback.format_stack())

]]></description>
			<content:encoded><![CDATA[<p>The traceback module has utility functions for printing the currently running stack, not just tracebacks.</p>
<pre class="brush: python">
import traceback
import logging

# somewhere in your buggy code
logging.log(1, &quot;&quot;.join(traceback.format_stack())
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/printing-the-current-running-stack-in-python/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>unable to remap C:\cygwin\bin\tk84.dll to same address as parent</title>
		<link>http://www.redmountainsw.com/wordpress/archives/unable-to-remap-ccygwinbintk84dll-to-same-address-as-parent</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/unable-to-remap-ccygwinbintk84dll-to-same-address-as-parent#comments</comments>
		<pubDate>Sat, 25 Apr 2009 11:00:33 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[PIL]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/archives/unable-to-remap-ccygwinbintk84dll-to-same-address-as-parent</guid>
		<description><![CDATA[I was checking out Tauber&#8217;s Pinax, and came across VirtualEnv for the first time. Those are two cool projects. 
However, building PIL on Cygwin Python 2.5 yields the following error message:
unable to remap C:\cygwin\bin\tk84.dll to same address as parent
Thanks to the power of Google, DataHammer has already found a resolution


C:\>cd \cygwin\bin
C:\cygwin\bin>ash
$ ./rebase -b 0x1000000000 tk84.dll

]]></description>
			<content:encoded><![CDATA[<p>I was checking out Tauber&#8217;s Pinax, and came across VirtualEnv for the first time. Those are two cool projects. </p>
<p>However, building PIL on Cygwin Python 2.5 yields the following error message:</p>
<pre>unable to remap C:\cygwin\bin\tk84.dll to same address as parent</pre>
<p>Thanks to the power of Google, <a href="http://blog.datahammer.info">DataHammer</a> has already found <a href="http://blog.datahammer.info/2008/11/install-pil-under-cygwin-python-25.html">a resolution</a><br />
<code>
<pre>
C:\>cd \cygwin\bin
C:\cygwin\bin>ash
$ ./rebase -b 0x1000000000 tk84.dll
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/unable-to-remap-ccygwinbintk84dll-to-same-address-as-parent/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cygwin Python and sqlite3</title>
		<link>http://www.redmountainsw.com/wordpress/archives/cygwin-python-and-sqlite3</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/cygwin-python-and-sqlite3#comments</comments>
		<pubDate>Mon, 08 Sep 2008 01:57:33 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[cygwin]]></category>
		<category><![CDATA[sqlite3]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=479</guid>
		<description><![CDATA[Apparently, cygwin&#8217;s distribution of Python 2.5.1 doesn&#8217;t come with sqlite3. This is a pity for those who would like to work with Django using cygwin Python.
Building _sqlite3.dll on cygwin is not too difficult. If you are in a hurry, heres the download _sqlite3.dll.
Prerequisites

/bin/cygsqlite3-0.dll
/bin/libpython2.5.dll
/usr/include/sqlite3.h
/usr/include/python2.5/Python.h [et.c]



tar jxf Python-2.5.2.tar.bz2 Python-2.5.2/Modules/_sqlite/
cd Python-2.5.2/Modules/_sqlite/
gcc -shared -o _sqlite3.dll -I /usr/include/python2.5 -L /bin [...]]]></description>
			<content:encoded><![CDATA[<p>Apparently, <a href="http://www.mail-archive.com/cygwin@cygwin.com/msg83812.html">cygwin&#8217;s distribution of Python 2.5.1 doesn&#8217;t come with sqlite3</a>. This is a pity for those who would like to work with Django using cygwin Python.</p>
<p>Building _sqlite3.dll on cygwin is not too difficult. If you are in a hurry, heres the <b>download</b> <a href="/wordpress/wp-content/uploads/_sqlite3.dll">_sqlite3.dll</a>.</p>
<p><b>Prerequisites</b><br/></p>
<ul>
<li>/bin/cygsqlite3-0.dll</li>
<li>/bin/libpython2.5.dll</li>
<li>/usr/include/sqlite3.h</li>
<li>/usr/include/python2.5/Python.h [et.c]
</li>
</ul>
<pre class="brush: sh">
tar jxf Python-2.5.2.tar.bz2 Python-2.5.2/Modules/_sqlite/
cd Python-2.5.2/Modules/_sqlite/
gcc -shared -o _sqlite3.dll -I /usr/include/python2.5 -L /bin -lpython2.5 -lsqlite3-0 -D&#039;MODULE_NAME=&quot;_sqlite3&quot;&#039; *.c
cp _sqlite3.dll /usr/lib/python2.5/lib-dynload/
</pre>
<p><b>download</b><br/><br />
<a href="/wordpress/wp-content/uploads/_sqlite3.dll">_sqlite3.dll</a></p>
<h2>Update 10 Sept 2008</h2>
<p>Download link fixed. (Thanks Steve)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/cygwin-python-and-sqlite3/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>First Encounter with Genshi</title>
		<link>http://www.redmountainsw.com/wordpress/archives/first-encounter-with-genshi</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/first-encounter-with-genshi#comments</comments>
		<pubDate>Wed, 04 Jun 2008 12:09:10 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[code generation]]></category>
		<category><![CDATA[codeigniter]]></category>
		<category><![CDATA[genshi]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=362</guid>
		<description><![CDATA[I was playing around with code generation of some scaffolding-style code for CodeIgniter. Initially, python&#8217;s string interpolation operator % sufficed. As time progressed, it became clearer that resorting to a templating library buys me cleaner code. 
Problem #1
The $ used by Genshi for string interpolation conflicts with PHP&#8217;s $variables. 
Solution #1
After 10 minutes of source [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with code generation of some scaffolding-style code for <a href="http://www.codeigniter.com/">CodeIgniter</a>. Initially, python&#8217;s string interpolation operator % sufficed. As time progressed, it became clearer that resorting to a templating library buys me cleaner code. </p>
<p><b>Problem #1</b><br />
The $ used by Genshi for string interpolation conflicts with PHP&#8217;s $variables. </p>
<p><b>Solution #1</b><br />
After 10 minutes of source diving (by the way, <a href="http://genshi.edgewall.org">Genshi</a> source is a work of art &#8211; wish I could write like that).</p>
<pre class="brush: python">
import genshi.template.interpolation
genshi.template.interpolation.PREFIX = &#039;^&#039;

from genshi.template import TextTemplate
template = TextTemplate(&quot;$this-&gt;^{foo} = &#039;home&#039;;&quot;)
stream = template.generate(foo=&quot;customer&quot;)
print stream
</pre>
<p><b>Problem #2</b><br />
The generated output quotes the > into &gt;</p>
<p><b>Solution #2</b><br />
The Stream render() method takes a parameter specifying the kind of escaping.</p>
<pre class="brush: python">
print stream.render(&#039;text&#039;)
</pre>
<p><b>Overall Solution</b></p>
<pre class="brush: python">
from genshi.template import TextTemplate
import genshi.template.interpolation
genshi.template.interpolation.PREFIX = &#039;^&#039;
for tablename, table in specs.items():
    fd = open(&#039;controllers/%s.php&#039; % tablename, &#039;w&#039;)
    template = TextTemplate(open(&#039;controllers.php&#039;, &#039;r&#039;), filename=&#039;controller.php&#039;)
    print template.generate(tablename=tablename, columns=table).render(&#039;text&#039;)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/first-encounter-with-genshi/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python subclassing file types</title>
		<link>http://www.redmountainsw.com/wordpress/archives/python-subclassing-file-types</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/python-subclassing-file-types#comments</comments>
		<pubDate>Tue, 03 Jun 2008 00:41:16 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=361</guid>
		<description><![CDATA[I was hoping to write a simple tee class by subclassing file, but there must be further type magic getting in the way when print &#62;&#62; is used.

import sys

class tee(file):
   def write(self, text):
     sys.stdout.write(text)
     file.write(self, text)

fd = tee(&#34;output.txt&#34;, &#34;w&#34;)
print &#62;&#62; fd, &#34;Test 1&#34;
fd.write(&#34;Test 2\n&#34;)


$ python [...]]]></description>
			<content:encoded><![CDATA[<p>I was hoping to write a simple tee class by subclassing file, but there must be further type magic getting in the way when <code>print &gt;&gt;</code> is used.</p>
<pre class="brush: python">
import sys

class tee(file):
   def write(self, text):
     sys.stdout.write(text)
     file.write(self, text)

fd = tee(&quot;output.txt&quot;, &quot;w&quot;)
print &gt;&gt; fd, &quot;Test 1&quot;
fd.write(&quot;Test 2\n&quot;)
</pre>
<pre>
$ python test.py
Test 2

$ cat output.txt
Test 1
Test 2
</pre>
<p>Using the dis module, we can tell that <code>print >></code> is compiled into <code>PRINT_ITEM_TO</code>.</p>
<pre>
>>> def t(): print >> fd, "foo"
...
>>> import dis; dis.dis(t)
  1           0 LOAD_GLOBAL              0 (fd)
              3 DUP_TOP
              4 LOAD_CONST               1 ('foo')
              7 ROT_TWO
              8 PRINT_ITEM_TO
              9 PRINT_NEWLINE_TO
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
</pre>
<p>and looking through ceval.c, searching for <code>PRINT_ITEM_TO</code> yields</p>
<p><code></p>
<pre class="brush: c">
 case PRINT_ITEM_TO:
    w = stream = POP();
    /* fall through to PRINT_ITEM */

case PRINT_ITEM:
    v = POP();
    if (stream == NULL || stream == Py_None) {
        w = PySys_GetObject(&quot;stdout&quot;);
        if (w == NULL) {
            PyErr_SetString(PyExc_RuntimeError,
                    &quot;lost sys.stdout&quot;);
            err = -1;
        }
    }
    /* PyFile_SoftSpace() can exececute arbitrary code
       if sys.stdout is an instance with a __getattr__.
       If __getattr__ raises an exception, w will
       be freed, so we need to prevent that temporarily. */
    Py_XINCREF(w);
    if (w != NULL &amp;&amp; PyFile_SoftSpace(w, 0))
        err = PyFile_WriteString(&quot; &quot;, w);
    if (err == 0)
        err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
</pre>
<p></code><br />
Any ideas why?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/python-subclassing-file-types/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rich Metadata Mediated UI development</title>
		<link>http://www.redmountainsw.com/wordpress/archives/rich-metadata-mediated-ui-development</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/rich-metadata-mediated-ui-development#comments</comments>
		<pubDate>Sat, 03 May 2008 10:44:27 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[MS Access]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Thinking IT]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[metadata]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=355</guid>
		<description><![CDATA[What would you automate into your boilerplate code after having 10 years of writing database applications? Here are some links to promising projects/essays:

Andromeda
Django Admin
Dataphor
Promises: User interface &#8220;hints&#8221; integrated with the data model

Naked Objects
MS Access and Query By Form
I like how CodeIgniter makes it possible to compose declarative data validations  e.g. &#8220;valid_email&#124;matches[email_confirm]&#124;min_length[6]&#8220;
We need standard ValueConverters [...]]]></description>
			<content:encoded><![CDATA[<p>What would you automate into your boilerplate code after having 10 years of writing database applications? Here are some links to promising projects/essays:</p>
<ul>
<li><a href="http://www.andromeda-project.org/pages/cms/Design+Ideas.html">Andromeda</a></li>
<li><a href="http://www.djangoproject.com/documentation/tutorial02/">Django Admin</a></li>
<li><a href="http://dataphor.org/index.php?title=About:Dataphor">Dataphor</a>
<p>Promises: User interface &#8220;<em>hints</em>&#8221; integrated with the data model</p>
</li>
<li><a href="http://www.nakedobjects.org/">Naked Objects</a></li>
<li><a href="http://www.ukaug.co.uk/TPQBF.asp">MS Access and Query By Form</a></li>
<li>I like how CodeIgniter makes it possible to compose <a href="">declarative data validations</a>  e.g. &#8220;valid_email|matches[email_confirm]|min_length[6]&#8220;</li>
<li>We need standard <a href="http://blogs.msdn.com/bencon/archive/2006/05/10/594886.aspx">ValueConverters</a> for currency, URL, dates and email addresses</a></li>
<li>Someone should write an essay on why database synchronization for off-line applications is a bad idea, and why journaling works better</li>
<li>More ideas here &#8211; <a href="http://dataconstellation.com/blog/older/2008/4/23/there_are_no_attributes/">There are no attributes</a> &#8211; CQL sounds cool</li>
</ul>
<p>What are your thoughts here? Are there any other notable projects in a similar vein?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/rich-metadata-mediated-ui-development/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Managing Conflict Errors in Zope</title>
		<link>http://www.redmountainsw.com/wordpress/archives/managing-conflict-errors-in-zope</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/managing-conflict-errors-in-zope#comments</comments>
		<pubDate>Fri, 25 Apr 2008 03:10:07 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[zope]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=351</guid>
		<description><![CDATA[Sometimes, your Zope application may be unnecessarily writing too many times to the database. An easy way to track what objects are being written to is to use the analyze.py utility. Look at the Count and Pct, and make sure that relatively static objects do not get too many writes.
$ ../../bin/python analyze.py Data.fs
Processed 13382 records [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, your Zope application may be unnecessarily writing too many times to the database. An easy way to track what objects are being written to is to use the analyze.py utility. Look at the Count and Pct, and make sure that relatively static objects do not get too many writes.<br />
<code>$ ../../bin/python analyze.py Data.fs<br />
Processed 13382 records in 5734 transactions<br />
Average record size is 1742.56 bytes<br />
Average transaction size is 4066.78 bytes<br />
Types used:<br />
Class Name Count TBytes Pct AvgSize<br />
---------------------------------------------- ------- --------- ----- -------<br />
AccessControl.User.User 1 138 0.0% 138.00<br />
AccessControl.User.UserFolder 1 110 0.0% 110.00<br />
App.ApplicationManager.ApplicationManager 1 122 0.0% 122.00<br />
App.Product.Product 33 37807 0.2% 1145.67<br />
App.Product.ProductFolder 1 2543 0.0% 2543.00<br />
App.special_dtml.HTML 15 46973 0.2% 3131.53<br />
BTrees.IIBTree.IIBTree 1190 137981 0.6% 115.95<br />
BTrees.IIBTree.IIBucket 231 158454 0.7% 685.95</code></p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/managing-conflict-errors-in-zope/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# 3.0 and 3.5 for experienced developers.</title>
		<link>http://www.redmountainsw.com/wordpress/archives/c-30-and-35-for-experienced-developers</link>
		<comments>http://www.redmountainsw.com/wordpress/archives/c-30-and-35-for-experienced-developers#comments</comments>
		<pubDate>Sun, 20 Apr 2008 04:30:03 +0000</pubDate>
		<dc:creator>Chui</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.redmountainsw.com/wordpress/?p=347</guid>
		<description><![CDATA[Python developers are probably already familiar with List Comprehensions, and lambda expressions. The interesting twist with LINQ is these expressions are translated into SQL and executed on the RDBMS instead of being done on the client side. There was a pretty clever Python project that achieved this in Python through dissassembly of python bytecodes, but [...]]]></description>
			<content:encoded><![CDATA[<p>Python developers are probably already familiar with List Comprehensions, and lambda expressions. The interesting twist with LINQ is these expressions are translated into SQL and executed on the RDBMS instead of being done on the client side. There was a pretty clever Python project that achieved this in Python through dissassembly of python bytecodes, but I can&#8217;t recall it&#8217;s name [Update 23 Apr 2008: see <a href="http://svn.aminus.net/dejavu/branches/ldap/logic.py">http://svn.aminus.net/dejavu/branches/ldap/logic.py</a> ] . There are some interesting ideas raised in LINQ that even Python developers ought to explore and consider adopting in a future Python. [Edit: 23 Apr 2008: Meaning I'd prefer to see this in Python core through AST transformation rather than bytecode hacks, C# has just got macros.]</p>
<ol>
<li>
<h3>Setting up a Linq DataContext</h3>
<div><code>MyDatabaseContext db = new MyDatabaseContext(MyConnectionString); // or MyDatabaseContext db = new MyDatabaseContext();<br />
</code><code> </code></div>
</li>
<li>
<h3>Basic LINQ Expression</h3>
<div><code>var AnIQueryable = from Customer in db.Customers<br />
where Customer.FirstName.StartsWith("m")<br />
select Customer; <br />
</code></div>
</li>
<li>
<h3>Logging the generated queries</h3>
<p><code>db.Log = Console.out<br />
</code><br />
The previous example translates into a LIKE operator:</p>
<p><code>SELECT [t0].[CustomerID], [t0].[FirstName] AS [FirstName]<br />
FROM [dbo].[Customer] AS [t0]<br />
WHERE [t0].[FirstName] LIKE @p0 </code></li>
<li>
<h3>LINQ with Aggregates</h3>
<pre><code>var AverageRuns =(from Master in this.db.Masters select Master.Runs).Average()
</code></pre>
<p>The SQL generated isn&#8217;t too shabby either:</p>
<pre><code>SELECT AVG([t0].[Runs]) AS [value]
FROM [dbo].[Master] AS [t0]</code></pre>
</li>
<li>
<h3>LINQ grouped aggregates</h3>
<pre><code>
   var categories =
      from p in products
      group p by p.Category into g
      select new
              {Category = g.Key,
               AveragePrice = g.Group.Average(p =&gt; p.UnitPrice)
               };
</code></pre>
</li>
<li>
<h3>Lambda Expressions</h3>
<ul>
<li>
<h4>Map</h4>
<pre><code>db.Customers.Select(customer =&gt; master.Customer.LastName.length)</code></pre>
</li>
<li>
<h4>Filter</h4>
<pre><code>db.Customers.Where(customer =&gt; customer.LastName.StartsWith("M")</code></pre>
</li>
<li>
<h4>Reduce / Fold</h4>
<div><code><br />
double[] doubles = { 1.7, 2.4, 3.5, 8.9 };<br />
double result = doubles.Aggregate(0.0, (d1, d2) =&gt; d1+d2);<br />
</code></div>
<p>Note: You can&#8217;t use Aggregate directly on IQueryable from database contexts. Instead,<br />
<code><br />
var arr_masters = this.db.Masters.ToArray();<br />
var totalRuns = arr_masters.Aggregate<br />
(0, // seed<br />
(int accum, MyDB.Master master) =&gt; accum + master.Runs<br />
);<br />
</code></li>
</ul>
</li>
<li>
<h3>Updating Database</h3>
<pre><code>
this.Validate();
this.masterBindingSource.EndEdit();
db.SubmitChanges();
</code></pre>
</li>
<li>
<h3>How to cheat</h3>
<p>Use Microsoft&#8217;s <a href="http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx">101 LINQ samples</a></li>
</ol>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.redmountainsw.com/wordpress/archives/c-30-and-35-for-experienced-developers/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
