title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Is there a string-collapse library function in python?
1,249,786
<p>Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?</p> <p>I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?</p> <pre><code>def collapse(input): import re rn = re.compile(r'(\r\n)+') r = re.compile(r'\r+') n = re.compile(r'\n+') s = re.compile(r'\ +') return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input)))) </code></pre> <p>P.S. Thanks for good observations. <code>' '.join(input.split())</code> seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled <code>r'\s+'</code> regex.</p>
4
2009-08-08T20:18:54Z
1,249,850
<p>The built-in <code>string.split()</code> method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:</p> <pre><code>' '.join(my_string.split()) </code></pre> <p>Here's a complete test script:</p> <pre><code>TEST = """This is a test\twith a mix of\ttabs, newlines and repeating whitespace""" print ' '.join(TEST.split()) # Prints: # This is a test with a mix of tabs, newlines and repeating whitespace </code></pre>
12
2009-08-08T20:43:34Z
[ "python", "string", "line-breaks" ]
Is there a string-collapse library function in python?
1,249,786
<p>Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?</p> <p>I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?</p> <pre><code>def collapse(input): import re rn = re.compile(r'(\r\n)+') r = re.compile(r'\r+') n = re.compile(r'\n+') s = re.compile(r'\ +') return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input)))) </code></pre> <p>P.S. Thanks for good observations. <code>' '.join(input.split())</code> seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled <code>r'\s+'</code> regex.</p>
4
2009-08-08T20:18:54Z
1,249,870
<p>You had the right idea, you just needed to read the python manual a little more closely:</p> <pre><code>import re somewhitespace = re.compile(r'\s+') TEST = """This is a test\twith a mix of\ttabs, newlines and repeating whitespace""" somewhitespace.sub(' ', TEST) 'This is a test with a mix of tabs, newlines and repeating whitespace' </code></pre>
4
2009-08-08T20:52:26Z
[ "python", "string", "line-breaks" ]
Convert Python exception information to string for logging
1,249,795
<p>I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.</p> <p>I came up with this:</p> <pre><code>def logexception(type, value, traceback): print traceback.format_exception(type, value, traceback) sys.excepthook = logexception </code></pre> <p>but it bails out with an argument error when called, though according to the docs it should work. Anyone knows what the problem is with this or have an other drop-in solution?</p>
5
2009-08-08T20:23:17Z
1,249,812
<p>you can use <a href="http://code.activestate.com/recipes/466332/" rel="nofollow">this very simpe logging solution</a></p> <p>or <a href="http://onlamp.com/pub/a/python/2005/06/02/logging.html?page=last" rel="nofollow">this one</a> </p>
-1
2009-08-08T20:27:54Z
[ "python", "exception" ]
Convert Python exception information to string for logging
1,249,795
<p>I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.</p> <p>I came up with this:</p> <pre><code>def logexception(type, value, traceback): print traceback.format_exception(type, value, traceback) sys.excepthook = logexception </code></pre> <p>but it bails out with an argument error when called, though according to the docs it should work. Anyone knows what the problem is with this or have an other drop-in solution?</p>
5
2009-08-08T20:23:17Z
1,249,821
<p>Why should that <code>traceback</code> argument have a <code>format_exception</code> method just like the function in the traceback module whose name it's usurping, and if it had one why would that method require the same object on which it's called to be passed in as the last argument as well?</p> <p>I suspect you just want to give the third argument a different name, so as not to hide the traceback module, say:</p> <pre><code>import sys import traceback def logexception(type, value, tb): print traceback.format_exception(type, value, tb) sys.excepthook = logexception </code></pre> <p>and things should work much better.</p>
5
2009-08-08T20:31:00Z
[ "python", "exception" ]
If a python module says its dependent on debhelper and cdbs is there no way to get it to run on a nondebian linux?
1,249,873
<p>I want to try python purple but I don't have debian. Is there a way to get it to run on either windows or a different linux?</p>
-1
2009-08-08T20:53:35Z
1,249,896
<p>I suppose compiling from source (if availiable) or looking for dbhelper and cbds install files for your distribution</p>
0
2009-08-08T21:04:23Z
[ "python", "linux", "debian", "cdbs" ]
Alter namespace prefixing with ElementTree in Python
1,249,876
<p>By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation:</p> <pre> {http://example.org/namespace/spec}mynode </pre> <p>This makes accessing specific nodes by name a huge pain later in the code.</p> <p>I've read through the docs on ElementTree and namespaces and it looks like the <code>iterparse()</code> function should allow me to alter the way the parser prefixes namespaces, but for the life of me I can't actually make it change the prefix. It seems like that may happen in the background before the ns-start event even fires as in this example:</p> <pre><code>for event, elem in iterparse(source): if event == "start-ns": namespaces.append(elem) elif event == "end-ns": namespaces.pop() else: ... </code></pre> <p>How do I make it change the prefixing behavior and what is the proper thing to return when the function ends?</p>
18
2009-08-08T20:56:03Z
1,255,792
<p>You don't specifically need to use <code>iterparse</code>. Instead, the following script:</p> <pre><code>from cStringIO import StringIO import xml.etree.ElementTree as ET NS_MAP = { 'http://www.red-dove.com/ns/abc' : 'rdc', 'http://www.adobe.com/2006/mxml' : 'mx', 'http://www.red-dove.com/ns/def' : 'oth', } DATA = '''&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;rdc:container xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:rdc="http://www.red-dove.com/ns/abc" xmlns:oth="http://www.red-dove.com/ns/def"&gt; &lt;mx:Style&gt; &lt;oth:style1/&gt; &lt;/mx:Style&gt; &lt;mx:Style&gt; &lt;oth:style2/&gt; &lt;/mx:Style&gt; &lt;mx:Style&gt; &lt;oth:style3/&gt; &lt;/mx:Style&gt; &lt;/rdc:container&gt;''' tree = ET.parse(StringIO(DATA)) some_node = tree.getroot().getchildren()[1] print ET.fixtag(some_node.tag, NS_MAP) some_node = some_node.getchildren()[0] print ET.fixtag(some_node.tag, NS_MAP) </code></pre> <p>produces</p> <pre> ('mx:Style', None) ('oth:style2', None) </pre> <p>Which shows how you can access the fully-qualified tag names of individual nodes in a parsed tree. You should be able to adapt this to your specific needs.</p>
5
2009-08-10T16:12:30Z
[ "python", "xml", "namespaces", "elementtree" ]
Alter namespace prefixing with ElementTree in Python
1,249,876
<p>By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation:</p> <pre> {http://example.org/namespace/spec}mynode </pre> <p>This makes accessing specific nodes by name a huge pain later in the code.</p> <p>I've read through the docs on ElementTree and namespaces and it looks like the <code>iterparse()</code> function should allow me to alter the way the parser prefixes namespaces, but for the life of me I can't actually make it change the prefix. It seems like that may happen in the background before the ns-start event even fires as in this example:</p> <pre><code>for event, elem in iterparse(source): if event == "start-ns": namespaces.append(elem) elif event == "end-ns": namespaces.pop() else: ... </code></pre> <p>How do I make it change the prefixing behavior and what is the proper thing to return when the function ends?</p>
18
2009-08-08T20:56:03Z
1,904,289
<p>xml.etree.ElementTree doesn't appear to have fixtag, well, not according to the documentation. However I've looked at some source code for fixtag and you do:</p> <pre><code>import xml.etree.ElementTree as ET for event, elem in ET.iterparse(inFile, events=("start", "end")): namespace, looktag = string.split(elem.tag[1:], "}", 1) </code></pre> <p>You have the tag string in looktag, suitable for a lookup. The namespace is in namespace.</p>
2
2009-12-14T23:31:43Z
[ "python", "xml", "namespaces", "elementtree" ]
Getting Data into LLNL VisIt via Python
1,250,063
<p>Without using VisIt's python library visit-writer.py, how can I import my data into VisIt? I'm aware of many <a href="https://wci.llnl.gov/codes/visit/FAQ.html#12" rel="nofollow">alternative file formats</a> but I can't find a simple library that takes my arrays of data and just writes it as a file. Specifically, my data consists of adaptive mesh boxes (really, voxels) and so I figure is best represented by an unstructured data grid. For each voxel, I have to attach various scalar or vector variables.</p>
1
2009-08-08T22:40:55Z
1,250,137
<p>From skimming the VisIt manual on "<a href="https://wci.llnl.gov/codes/visit/1.5.4/GettingDataIntoVisIt1.5.4.pdf" rel="nofollow">Getting Data Into VisIt</a>", it seems like there are three basic ways to create VisIt-compatible data files:</p> <ol> <li>For scalar data on a uniform grid, it is probably easiest to format your data for VisIt's BOV ("brick-of-values") database reader plugin. This consists of a binary data file which is essentially a dump of the data array to disk, and a text-format header file which provides, among other things, the dimensions of the data, the type of the data, and the endian representation.</li> <li>For simulation code written in C(++) or Fortran, the <a href="https://wci.llnl.gov/codes/silo/" rel="nofollow">Silo</a> library (also developed at LLNL) can be used to create VisIt-compatible data files. "Getting Data Into VisIt" provides C and Fortran code examples for writing rectangular, curvilinear, point, and unstructured meshes using Silo.</li> <li>For simulation code written in C(++) or Python, the <code>visit_writer</code> library can be used to save the data in VTK (Visualization Toolkit) format.</li> </ol> <p>The short answer is that, even though you wanted to avoid using <code>visit_writer</code>, it is probably the easiest way for Python to save your data in a VisIt-compatible format.</p>
2
2009-08-08T23:28:37Z
[ "python", "visualization" ]
Getting Data into LLNL VisIt via Python
1,250,063
<p>Without using VisIt's python library visit-writer.py, how can I import my data into VisIt? I'm aware of many <a href="https://wci.llnl.gov/codes/visit/FAQ.html#12" rel="nofollow">alternative file formats</a> but I can't find a simple library that takes my arrays of data and just writes it as a file. Specifically, my data consists of adaptive mesh boxes (really, voxels) and so I figure is best represented by an unstructured data grid. For each voxel, I have to attach various scalar or vector variables.</p>
1
2009-08-08T22:40:55Z
15,512,281
<p>There's also a package called <a href="http://documen.tician.de/pyvisfile/" rel="nofollow">pyvisfile</a> that is made to do this. I haven't tried it but it claims to work. </p>
1
2013-03-19T23:12:24Z
[ "python", "visualization" ]
Manipulate MP3 programmatically: Muting certain parts?
1,250,086
<p>I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java.</p> <p>Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will play normally -- only that portion will be silent.</p> <p>Any advice for setting this up in a way that's easy to automate/run on the command line would be fantastic!</p>
3
2009-08-08T22:57:12Z
1,250,130
<p>SoX is a multi-platform sound editing tool and I've used it a lot in the past. More info at <a href="http://sox.sourceforge.net/" rel="nofollow">http://sox.sourceforge.net/</a></p> <p>I don't think you can mute a section of an MP3 file with a single command though. You could split the file into 3 parts, mute the middle part, then stitch them together again.</p> <p>Hope that helps</p>
1
2009-08-08T23:26:16Z
[ "java", "python", "audio", "mp3" ]
Manipulate MP3 programmatically: Muting certain parts?
1,250,086
<p>I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java.</p> <p>Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will play normally -- only that portion will be silent.</p> <p>Any advice for setting this up in a way that's easy to automate/run on the command line would be fantastic!</p>
3
2009-08-08T22:57:12Z
1,250,132
<p><a href="http://audacity.sourceforge.net/" rel="nofollow">Audacity</a> (available for Windows, Mac, Linux) <a href="http://wiki.audacityteam.org/index.php?title=Scripting" rel="nofollow">has a plugin</a> (currently for Windows only) that allows it to be scripted. The target language is Perl, but perhaps Python would work.</p> <p>There's also a built-in XLisp interpreter called Nyquist.</p>
0
2009-08-08T23:26:51Z
[ "java", "python", "audio", "mp3" ]
Manipulate MP3 programmatically: Muting certain parts?
1,250,086
<p>I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java.</p> <p>Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will play normally -- only that portion will be silent.</p> <p>Any advice for setting this up in a way that's easy to automate/run on the command line would be fantastic!</p>
3
2009-08-08T22:57:12Z
1,685,790
<p>Or use <a href="http://www.xuggle.com/xuggler" rel="nofollow">Xuggler</a> to decode the MP3 file, mute out the audio you care about, and then re-encode.</p>
0
2009-11-06T06:26:16Z
[ "java", "python", "audio", "mp3" ]
Manipulate MP3 programmatically: Muting certain parts?
1,250,086
<p>I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java.</p> <p>Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will play normally -- only that portion will be silent.</p> <p>Any advice for setting this up in a way that's easy to automate/run on the command line would be fantastic!</p>
3
2009-08-08T22:57:12Z
5,060,666
<p>One (somehow pretentious) idea: record a mute (silent) mp3 in bitrate that your mp3 is. Then, copy all the frames from original mp3 up to the point when you want your silence to start. Then, copy as much muted frames you need from your 'silence file'. Then, copy the rest from the original file.</p> <p>You'll have muted file without re-encoding the file!</p>
1
2011-02-20T22:53:42Z
[ "java", "python", "audio", "mp3" ]
AttributeError: 'module' object has no attribute
1,250,103
<p>I have two python modules:</p> <p>a.py</p> <pre><code>import b def hello(): print "hello" print "a.py" print hello() print b.hi() </code></pre> <p>b.py</p> <pre><code>import a def hi(): print "hi" </code></pre> <p>When I run <code>a.py</code>, I get:</p> <pre><code>AttributeError: 'module' object has no attribute 'hi' </code></pre> <p>What does the error mean? How do I fix it?</p>
75
2009-08-08T23:12:20Z
1,250,119
<p>The problem is the circular dependency between the modules. <code>a</code> imports <code>b</code> and <code>b</code> imports <code>a</code>. But one of them needs to be loaded first - in this case python ends up initializing module <code>a</code> before <code>b</code> and <code>b.hi()</code> doesn't exist yet when you try to access it in <code>a</code>.</p>
20
2009-08-08T23:19:41Z
[ "python", "attributeerror" ]
AttributeError: 'module' object has no attribute
1,250,103
<p>I have two python modules:</p> <p>a.py</p> <pre><code>import b def hello(): print "hello" print "a.py" print hello() print b.hi() </code></pre> <p>b.py</p> <pre><code>import a def hi(): print "hi" </code></pre> <p>When I run <code>a.py</code>, I get:</p> <pre><code>AttributeError: 'module' object has no attribute 'hi' </code></pre> <p>What does the error mean? How do I fix it?</p>
75
2009-08-08T23:12:20Z
1,250,135
<p>You have mutual top-level imports, which is almost always a bad idea.</p> <p>If you really must have mutual imports in Python, the way to do it is to import them within a function:</p> <pre><code># In b.py: def cause_a_to_do_something(): import a a.do_something() </code></pre> <p>Now a.py can safely do <code>import b</code> without causing problems.</p> <p>(At first glance it might appear that <code>cause_a_to_do_something()</code> would be hugely inefficient because it does an <code>import</code> every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)</p>
83
2009-08-08T23:27:29Z
[ "python", "attributeerror" ]
AttributeError: 'module' object has no attribute
1,250,103
<p>I have two python modules:</p> <p>a.py</p> <pre><code>import b def hello(): print "hello" print "a.py" print hello() print b.hi() </code></pre> <p>b.py</p> <pre><code>import a def hi(): print "hi" </code></pre> <p>When I run <code>a.py</code>, I get:</p> <pre><code>AttributeError: 'module' object has no attribute 'hi' </code></pre> <p>What does the error mean? How do I fix it?</p>
75
2009-08-08T23:12:20Z
3,124,164
<p>I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called <code>commands</code> which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.</p>
39
2010-06-26T14:18:21Z
[ "python", "attributeerror" ]
AttributeError: 'module' object has no attribute
1,250,103
<p>I have two python modules:</p> <p>a.py</p> <pre><code>import b def hello(): print "hello" print "a.py" print hello() print b.hi() </code></pre> <p>b.py</p> <pre><code>import a def hi(): print "hi" </code></pre> <p>When I run <code>a.py</code>, I get:</p> <pre><code>AttributeError: 'module' object has no attribute 'hi' </code></pre> <p>What does the error mean? How do I fix it?</p>
75
2009-08-08T23:12:20Z
29,687,721
<p>I got this error by referencing an enum which was imported in a wrong way, e.g.:</p> <pre><code>from package import MyEnumClass # ... # in some method: return MyEnumClass.Member </code></pre> <p>Correct import:</p> <pre><code>from package.MyEnumClass import MyEnumClass </code></pre> <p>Hope that helps someone</p>
8
2015-04-16T23:32:08Z
[ "python", "attributeerror" ]
AttributeError: 'module' object has no attribute
1,250,103
<p>I have two python modules:</p> <p>a.py</p> <pre><code>import b def hello(): print "hello" print "a.py" print hello() print b.hi() </code></pre> <p>b.py</p> <pre><code>import a def hi(): print "hi" </code></pre> <p>When I run <code>a.py</code>, I get:</p> <pre><code>AttributeError: 'module' object has no attribute 'hi' </code></pre> <p>What does the error mean? How do I fix it?</p>
75
2009-08-08T23:12:20Z
38,021,582
<p>I experienced this error because the module was not actually imported. The code looked like this:</p> <pre><code>import a.b, a.c # ... something(a.b) something(a.c) something(a.d) # My addition, which failed. </code></pre> <p>The last line resulted in an <code>AttributeError</code>. The cause was that I had failed to notice that the submodules of <code>a</code> (<code>a.b</code> and <code>a.c</code>) were <em>explicitly</em> imported, and assumed that the <code>import</code> statement actually imported <code>a</code>.</p>
0
2016-06-24T20:26:45Z
[ "python", "attributeerror" ]
parsing XML file in python with cElementTree: dealing with errors and line number in the file
1,250,192
<p>I am using the <code>cElementTree</code> library to parse XML files in Python. Everything is working fine</p> <p>But I would like to provide full error messages for the user when a value in the XML is not correct.</p> <p>For example, let's suppose I have the following XML:</p> <pre><code>&lt;A name="xxxx" href="yyyy"/&gt; </code></pre> <p>and want to tell the user if the <code>href</code> attribute doesn't exist or have a value that is not in a given list.</p> <p>For the moment, I have something like</p> <pre><code>if elem.get("ref") not in myList: raise XMLException( elem, "the 'href' attribute is not valid or does not exist") </code></pre> <p>where my exception is caught somewhere.</p> <p>But, in addition, I would like to display the line number of the XML element in the file. It seems that the <code>cElementTree</code> doesn't store any information about the line numbers of the XML elements of the tree... :-(</p> <p><strong>Question:</strong> Is there an equivalent XML library that is able to do that? Or a way to have access to the position of an XML element in the XML file ?</p> <p>Thanks</p>
2
2009-08-08T23:58:13Z
1,250,347
<p>The equivalent library that you should be using is <a href="http://lxml.de/" rel="nofollow">lxml</a>. lxml is a wrapper on very fast c libraries libxml2 and libxslt and is generally considered superior to the built in ones.</p> <p>It, luckly, tries to keep to the element tree api and extend it in lxml.etree.</p> <p>lxml.etree has an attribute sourceline for all elements which is just what you are after.</p> <p>So <code>elem.sourceline</code> above in the error message should work.</p>
4
2009-08-09T01:33:30Z
[ "python", "error-handling", "line-numbers", "celementtree" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,250,317
<p>The IDE you use is a personal and subjective thing, but it definitely matters. Personally, for writing short scripts or working with python interactively, I use PyDee available at <a href="http://pydee.googlecode.com/" rel="nofollow">http://pydee.googlecode.com/</a> . It is well done, fairly lightweight, but with good introspection capabilities. </p> <p>For larger projects involving multiple components, I prefer Eclipse with appropriate plugins. It has very sophisticated management and introspection capabilities. You can download it separately or get it as part of Python (X,Y) at <a href="http://www.pythonxy.com/" rel="nofollow">http://www.pythonxy.com/</a> .</p>
1
2009-08-09T01:14:31Z
[ "python", "ide" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,250,364
<ol> <li>How important is an IDE to normal Python development?</li> </ol> <p>Not very, IMHO. It's a lightweight language with much less boilerplate and simpler idioms than in some other languages, so there's less need for an IDE for that part. </p> <p>The standard interactive interpreter provides help and introspection functionality and a reasonable debugger (pdb). When I want a graphical look at my class hierarchies, I use epydoc to generate it. </p> <p>The only IDE-like functionality I sometimes wish I had is something that would help automate refactoring. </p> <ol> <li>Are there good IDEs available for the language?</li> </ol> <p>So I hear. Some of my coworkers use Wing.</p> <ol> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol> <p>N/A. I tried using Wing a few times but found that it interfered with my normal development process rather than supporting it.</p>
3
2009-08-09T01:44:01Z
[ "python", "ide" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,250,375
<p>IDEs arent <em>very</em> useful in Python; powerful editors such as Emacs and Vim seem very popular among Python programmers. This may confuse e.g. Java programmers, because in Java each file generally requires boilerplate code, such as a <code>package</code> statement, getters and setters. Python is much more lightweight in comparison.</p> <p>If you're looking for an equivalent to Visual Studio or Eclipse, there is... Eclipse, with <a href="http://pydev.sourceforge.net/" rel="nofollow">Pydev</a>.</p> <p>Emacs and Vim are very powerful and general, but have a steep learning curve. If you want to use Emacs, I highly recommend <a href="http://sourceforge.net/projects/python-mode/" rel="nofollow">python mode</a>; it's much better than the default Python mode.</p>
9
2009-08-09T01:50:58Z
[ "python", "ide" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,250,429
<p>A matter of habit and personal preferences. Me, I use vim (I have to admit emacs is at least as powerful, but my fingers are deeply trained by over 30 years of vi, and any other editor gives me the jitters, <em>especially</em> when it tries to imitate vi and never really manages to get it 100% right;-), occasionally an interactive environment (python itself, sometimes ipython), and on even rarer occasions a debugger (pdb). A good editor gives me all I need in term of word completion, lookup, &amp;c.</p> <p>I've tried Eclipse, its plugins, eric, and Kommodo, but I just don't like them -- Wing, I think I could get used to, and I have to admit its debugger is absolutely out of this world... but, I very rarely use (or need!) advanced debugging functionality, so after every rare occasion I'd forget, and have to learn it all over again a few months later when the need arose again... nah!-)</p>
4
2009-08-09T02:40:03Z
[ "python", "ide" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,252,287
<p>(1) IDEs are less important than for other languages, but if you find one that is useful, it still makes things easier. Without IDEs -- what are doing? Always running Python from command line?</p> <p>(2-3) On my Mac there's included IDLE which I keep always open for its Python shell (it's colored unlike the one in Terminal) and I use free Komodo Edit which I consider to be well-suited for Python as it doesn't go into the language deeply but rather focuses on coloring, tab management, parsing Python output, running frequent commands etc.</p>
0
2009-08-09T21:05:18Z
[ "python", "ide" ]
What is the importance of an IDE when programming in Python?
1,250,295
<p>I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even <em>possible</em> to program outside of such a tool.</p> <p>However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language.</p> <ol> <li>How important is an IDE to normal Python development? </li> <li>Are there good IDEs available for the language? </li> <li>If you do use an IDE for Python, how do you use it effectively?</li> </ol>
5
2009-08-09T01:02:37Z
1,273,578
<p>In contrast to the other answers i think that IDE's are very important especially for script languages. Almost all code is bad documentated and an IDE with a good debugger gives you much insides about what is really going on what datatypes are assigned to this values. Is this a hash of lists of hashes or a list of hashs of hashs. </p> <p>And the easy documentation lookup will save you time.</p> <p>But this is only important for people who need to count there time, this normally excludes beginners or hobbyists.</p>
1
2009-08-13T17:53:21Z
[ "python", "ide" ]
How to store regular expressions in the Google App Engine datastore?
1,250,313
<p>Regular Expressions are usually expressed as strings, but they also have properties (ie. single line, multi line, ignore case). How would you store them? And for compiled regular expressions, how to store it?</p> <p>Please note that we can write custom property classes: <a href="http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html" rel="nofollow">http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html</a></p> <p>As I don't understand Python enough, my first try to write a custom property which stores a compiled regular expression failed.</p>
1
2009-08-09T01:12:44Z
1,250,339
<p>I'm not sure if Python supprts it, but in .net regex, you can specify these options within the regex itself:</p> <pre><code>(?si)^a.*z$ </code></pre> <p>would specify single-line, ignore case.</p> <p>Indeed, the Python docs describe such a mechanism here: <a href="http://docs.python.org/library/re.html" rel="nofollow">http://docs.python.org/library/re.html</a></p> <p>To recap: (cut'n'paste from link above)</p> <p><em>(?iLmsux)</em></p> <p><em>(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the compile() function.</em></p> <p><em>Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.</em></p>
3
2009-08-09T01:26:54Z
[ "python", "google-app-engine", "gae-datastore", "customproperty" ]
How to store regular expressions in the Google App Engine datastore?
1,250,313
<p>Regular Expressions are usually expressed as strings, but they also have properties (ie. single line, multi line, ignore case). How would you store them? And for compiled regular expressions, how to store it?</p> <p>Please note that we can write custom property classes: <a href="http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html" rel="nofollow">http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html</a></p> <p>As I don't understand Python enough, my first try to write a custom property which stores a compiled regular expression failed.</p>
1
2009-08-09T01:12:44Z
1,250,377
<p>I wouldn't try to store the compiled regex. The data in a compiled regex is not designed to be stored, and is not guaranteed to be picklable or serializable. Just store the string and re-compile (the re module will do this for you behind the scenes anyway).</p>
3
2009-08-09T01:52:14Z
[ "python", "google-app-engine", "gae-datastore", "customproperty" ]
How to store regular expressions in the Google App Engine datastore?
1,250,313
<p>Regular Expressions are usually expressed as strings, but they also have properties (ie. single line, multi line, ignore case). How would you store them? And for compiled regular expressions, how to store it?</p> <p>Please note that we can write custom property classes: <a href="http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html" rel="nofollow">http://googleappengine.blogspot.com/2009/07/writing-custom-property-classes.html</a></p> <p>As I don't understand Python enough, my first try to write a custom property which stores a compiled regular expression failed.</p>
1
2009-08-09T01:12:44Z
1,251,370
<p>You can either store the text, as suggested above, or you can pickle and unpickle the compiled RE. For example, see <a href="http://appengine-cookbook.appspot.com/recipe/pickledproperty/" rel="nofollow">PickledProperty</a> on the cookbook.</p> <p>Due to the (lack of) speed of Pickle, particularly on App Engine where cPickle is unavailable, you'll probably find that storing the text of the regex is the faster option. In fact, it appears that when pickled, a re simply stores the original text anyway.</p>
2
2009-08-09T13:26:06Z
[ "python", "google-app-engine", "gae-datastore", "customproperty" ]
How to pickle numpy's Inf objects?
1,250,367
<p>When trying to pickle the object Inf as defined in numpy (I think), the dumping goes Ok but the loading fails:</p> <pre><code>&gt;&gt;&gt; cPickle.dump(Inf, file("c:/temp/a.pcl",'wb')) &gt;&gt;&gt; cPickle.load(file("c:/temp/a.pcl",'rb')) Traceback (most recent call last): File "&lt;pyshell#257&gt;", line 1, in &lt;module&gt; cPickle.load(file("c:/temp/a.pcl",'rb')) ValueError: could not convert string to float &gt;&gt;&gt; type(Inf) &lt;type 'float'&gt; </code></pre> <p>Why is that? And moreover - is there a way to fix that? I want to pickle something that has Inf in it - changing it to something else will flaw the elegance of the program...</p> <p>Thanks</p>
2
2009-08-09T01:45:21Z
1,250,392
<p>If you specify a pickle protocol more than zero, it will work. Protocol is often specified as -1, meaning use the latest and greatest protocol:</p> <pre><code>&gt;&gt;&gt; cPickle.dump(Inf, file("c:/temp/a.pcl",'wb'), -1) &gt;&gt;&gt; cPickle.load(file("c:/temp/a.pcl",'rb')) 1.#INF -- may be platform dependent what prints here. </code></pre>
5
2009-08-09T02:12:38Z
[ "python", "numpy", "pickle" ]
How to pickle numpy's Inf objects?
1,250,367
<p>When trying to pickle the object Inf as defined in numpy (I think), the dumping goes Ok but the loading fails:</p> <pre><code>&gt;&gt;&gt; cPickle.dump(Inf, file("c:/temp/a.pcl",'wb')) &gt;&gt;&gt; cPickle.load(file("c:/temp/a.pcl",'rb')) Traceback (most recent call last): File "&lt;pyshell#257&gt;", line 1, in &lt;module&gt; cPickle.load(file("c:/temp/a.pcl",'rb')) ValueError: could not convert string to float &gt;&gt;&gt; type(Inf) &lt;type 'float'&gt; </code></pre> <p>Why is that? And moreover - is there a way to fix that? I want to pickle something that has Inf in it - changing it to something else will flaw the elegance of the program...</p> <p>Thanks</p>
2
2009-08-09T01:45:21Z
1,416,922
<p>Try this solution at SourceForge which will work for any arbitrary Python object:</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p>
0
2009-09-13T05:23:41Z
[ "python", "numpy", "pickle" ]
How to find the url using the referer and the href in Python?
1,250,371
<p>Suppose I have</p> <pre><code>window_location = 'http://stackoverflow.com/questions/ask' href = '/users/48465/jader-dias' </code></pre> <p>I want to obtain</p> <pre><code>link = 'http://stackoverflow.com/users/48465/jader-dias' </code></pre> <p>How do I do it in Python?</p> <p>It have to work just as it works in the browser</p>
1
2009-08-09T01:47:29Z
1,250,374
<pre><code>&gt;&gt;&gt; import urlparse &gt;&gt;&gt; urlparse.urljoin('http://stackoverflow.com/questions/ask', ... '/users/48465/jader-dias') 'http://stackoverflow.com/users/48465/jader-dias' </code></pre> <p>From the doc page of <a href="http://docs.python.org/library/urlparse.html#urlparse.urljoin" rel="nofollow">urlparse.urljoin</a>:</p> <blockquote> <p>urlparse.urljoin(base, url[, allow_fragments])</p> <p>Construct a full (“absolute”) URL by combining a “base URL” (base) with another URL (url). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL.</p> <p>If url is an absolute URL (that is, starting with // or scheme://), the url‘s host name and/or scheme will be present in the result.</p> </blockquote>
6
2009-08-09T01:50:42Z
[ "python", "regex", "string", "url", "href" ]
Creating alternative login to Google Users for Google app engine
1,250,437
<p>How does one handle logging in and out/creating users, without using Google Users? I'd like a few more options then just email and password. Is it just a case of making a user model with the fields I need? Is that secure enough?</p> <p>Alternatively, is there a way to get the user to log in using the Google ID, but without being redirected to the actual Google page? </p>
4
2009-08-09T02:46:19Z
1,250,451
<p>I recommend using OpenID, see <a href="http://googlecode.blogspot.com/2009/07/google-apps-openid-identity-hub-for.html" rel="nofollow">here</a> for more -- just like Stack Overflow does!-)</p>
8
2009-08-09T02:53:37Z
[ "python", "google-app-engine", "model-view-controller", "gae-datastore" ]
Creating alternative login to Google Users for Google app engine
1,250,437
<p>How does one handle logging in and out/creating users, without using Google Users? I'd like a few more options then just email and password. Is it just a case of making a user model with the fields I need? Is that secure enough?</p> <p>Alternatively, is there a way to get the user to log in using the Google ID, but without being redirected to the actual Google page? </p>
4
2009-08-09T02:46:19Z
1,251,369
<p>If you roll your own user model, you're going to need to do your own session handling as well; the App Engine Users API creates login sessions for you behind the scenes. </p> <p>Also, while this should be obvious, you shouldn't store the user's password in plaintext; store an SHA-1 hash and compare it to a hash of the user's submitted password when they login.</p>
1
2009-08-09T13:25:27Z
[ "python", "google-app-engine", "model-view-controller", "gae-datastore" ]
How do you enable auto-scrolling on GtkSourceView2?
1,250,566
<p>I am having a problem with GtkSourceView used from Python.</p> <p>Two major problems: 1) When a user types text into the GtkSourceView, and types past the bottom of the visible text, the GtkSourceView does not autoscroll to the users cursor. This wouldnt be so bad, except: 2) The arrow keys, page up and page down keys, do not cause the GtkSourceView to scroll either.</p> <p>The mouse scrollbar does work on the GtkSourceView.</p> <p>Does anyone have knowledge/experience of this?</p> <p>My code is here <a href="http://launchpad.net/kabikaboo" rel="nofollow">http://launchpad.net/kabikaboo</a></p>
0
2009-08-09T04:02:11Z
1,301,796
<p>Ok I just figured this out.</p> <p>I was adding the GtkSourceView2 into a GtkScrolledWindow. Only, it was adding a ViewPort first via ScrolledWindow.add_with_viewport(). This disables part of the scrolling behavior via keyboard. Instead, use ScrolledWindow.add(), and the ViewPort is skipped and the GtkAdjustments take care of the scrolling!</p>
0
2009-08-19T18:29:32Z
[ "python", "gtk" ]
Decompressing a .bz2 file in Python
1,250,688
<p>So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.</p> <p>I'm quite a Python newbie, so the answer is probably quite obvious, please help me.</p> <p>In this bit of the script, I already have the file, and I just want to read it out to a variable, then decompress that? Is that right? I've tried all sorts of way to do this, I usually get "ValueError: couldn't find end of stream" error on the last line in this snippet. I've tried to open up the zipfile and write it out to a string in a zillion different ways. This is the latest.</p> <pre><code>openZip = open(zipFile, "r") s = '' while True: newLine = openZip.readline() if(len(newLine)==0): break s+=newLine print s uncompressedData = bz2.decompress(s) </code></pre> <p>Hi Alex, I should've listed all the other methods I've tried, as I've tried the read() way.</p> <p>METHOD A:</p> <pre><code>print 'decompressing ' + filename fileHandle = open(zipFile) uncompressedData = '' while True: s = fileHandle.read(1024) if not s: break print('RAW "%s"', s) uncompressedData += bz2.decompress(s) uncompressedData += bz2.flush() newFile = open(steamTF2mapdir + filename.split(".bz2")[0],"w") newFile.write(uncompressedData) newFile.close() </code></pre> <p>I get the error: </p> <pre><code>uncompressedData += bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>METHOD B</p> <pre><code>zipFile = steamTF2mapdir + filename print 'decompressing ' + filename fileHandle = open(zipFile) s = fileHandle.read() uncompressedData = bz2.decompress(s) </code></pre> <p>Same error :</p> <pre><code>uncompressedData = bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>Thanks so much for you prompt reply. I'm really banging my head against the wall, feeling inordinately thick for not being able to decompress a simple .bz2 file. </p> <p>By the by, used 7zip to decompress it manually, to make sure the file isn't wonky or anything, and it decompresses fine.</p>
4
2009-08-09T05:01:42Z
1,250,700
<p>You're opening and reading the compressed file as if it was a textfile made up of lines. DON'T! It's NOT.</p> <pre><code>uncompressedData = bz2.BZ2File(zipFile).read() </code></pre> <p>seems to be closer to what you're angling for.</p> <p><strong>Edit</strong>: the OP has shown a few more things he's tried (though I don't see any notes about having tried the best method -- the one-liner I recommend above!) but they seem to all have one error in common, and I repeat the key bits from above:</p> <blockquote> <p>opening ... the compressed file as if it was a textfile ... It's NOT.</p> </blockquote> <p><code>open(filename)</code> and even the more explicit <code>open(filename, 'r')</code> open, for reading, a <strong>text</strong> file -- a compressed file is a <strong>binary</strong> file, so in order to read it correctly you must open it with <code>open(filename, 'rb')</code>. ((my recommended <code>bz2.BZ2File</code> KNOWS it's dealing with a compressed file, of course, so there's no need to tell it anything more)).</p> <p>In Python <code>2.*</code>, on Unix-y systems (i.e. every system except Windows), you could get away with a sloppy use of <code>open</code> (but in Python <code>3.*</code> you can't, as text is Unicode, while binary is bytes -- different types).</p> <p>In Windows (and before then in DOS) it's always been indispensable to distinguish, as Windows' text files, for historical reason, are peculiar (use two bytes rather than one to end lines, and, at least in some cases, take a byte worth <code>'\0x1A'</code> as meaning a logical end of file) and so the reading and writing low-level code must compensate.</p> <p>So I suspect the OP is using Windows and is paying the price for not carefully using the <code>'rb'</code> option ("read binary") to the <code>open</code> built-in. (though <code>bz2.BZ2File</code> is still simpler, whatever platform you're using!-).</p>
14
2009-08-09T05:06:29Z
[ "python", "decompression", "decompress" ]
Decompressing a .bz2 file in Python
1,250,688
<p>So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.</p> <p>I'm quite a Python newbie, so the answer is probably quite obvious, please help me.</p> <p>In this bit of the script, I already have the file, and I just want to read it out to a variable, then decompress that? Is that right? I've tried all sorts of way to do this, I usually get "ValueError: couldn't find end of stream" error on the last line in this snippet. I've tried to open up the zipfile and write it out to a string in a zillion different ways. This is the latest.</p> <pre><code>openZip = open(zipFile, "r") s = '' while True: newLine = openZip.readline() if(len(newLine)==0): break s+=newLine print s uncompressedData = bz2.decompress(s) </code></pre> <p>Hi Alex, I should've listed all the other methods I've tried, as I've tried the read() way.</p> <p>METHOD A:</p> <pre><code>print 'decompressing ' + filename fileHandle = open(zipFile) uncompressedData = '' while True: s = fileHandle.read(1024) if not s: break print('RAW "%s"', s) uncompressedData += bz2.decompress(s) uncompressedData += bz2.flush() newFile = open(steamTF2mapdir + filename.split(".bz2")[0],"w") newFile.write(uncompressedData) newFile.close() </code></pre> <p>I get the error: </p> <pre><code>uncompressedData += bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>METHOD B</p> <pre><code>zipFile = steamTF2mapdir + filename print 'decompressing ' + filename fileHandle = open(zipFile) s = fileHandle.read() uncompressedData = bz2.decompress(s) </code></pre> <p>Same error :</p> <pre><code>uncompressedData = bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>Thanks so much for you prompt reply. I'm really banging my head against the wall, feeling inordinately thick for not being able to decompress a simple .bz2 file. </p> <p>By the by, used 7zip to decompress it manually, to make sure the file isn't wonky or anything, and it decompresses fine.</p>
4
2009-08-09T05:01:42Z
1,250,948
<blockquote> <p>openZip = open(zipFile, "r")</p> </blockquote> <p>If you're running on Windows, you may want to do say <strong>openZip = open(zipFile, "rb")</strong> here since the file is likely to contain CR/LF combinations, and you don't want them to be translated.</p> <blockquote> <p>newLine = openZip.readline()</p> </blockquote> <p>As Alex pointed out, this is very wrong, as the concept of "lines" is foreign to a compressed stream.</p> <blockquote> <p>s = fileHandle.read(1024) [...] uncompressedData += bz2.decompress(s)</p> </blockquote> <p>This is wrong for the same reason. 1024-byte chunks aren't likely to mean much to the decompressor, since it's going to want to work with it's own block-size.</p> <blockquote> <p>s = fileHandle.read() uncompressedData = bz2.decompress(s)</p> </blockquote> <p>If that doesn't work, I'd say it's the new-line translation problem I mentioned above.</p>
8
2009-08-09T08:23:04Z
[ "python", "decompression", "decompress" ]
Decompressing a .bz2 file in Python
1,250,688
<p>So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.</p> <p>I'm quite a Python newbie, so the answer is probably quite obvious, please help me.</p> <p>In this bit of the script, I already have the file, and I just want to read it out to a variable, then decompress that? Is that right? I've tried all sorts of way to do this, I usually get "ValueError: couldn't find end of stream" error on the last line in this snippet. I've tried to open up the zipfile and write it out to a string in a zillion different ways. This is the latest.</p> <pre><code>openZip = open(zipFile, "r") s = '' while True: newLine = openZip.readline() if(len(newLine)==0): break s+=newLine print s uncompressedData = bz2.decompress(s) </code></pre> <p>Hi Alex, I should've listed all the other methods I've tried, as I've tried the read() way.</p> <p>METHOD A:</p> <pre><code>print 'decompressing ' + filename fileHandle = open(zipFile) uncompressedData = '' while True: s = fileHandle.read(1024) if not s: break print('RAW "%s"', s) uncompressedData += bz2.decompress(s) uncompressedData += bz2.flush() newFile = open(steamTF2mapdir + filename.split(".bz2")[0],"w") newFile.write(uncompressedData) newFile.close() </code></pre> <p>I get the error: </p> <pre><code>uncompressedData += bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>METHOD B</p> <pre><code>zipFile = steamTF2mapdir + filename print 'decompressing ' + filename fileHandle = open(zipFile) s = fileHandle.read() uncompressedData = bz2.decompress(s) </code></pre> <p>Same error :</p> <pre><code>uncompressedData = bz2.decompress(s) ValueError: couldn't find end of stream </code></pre> <p>Thanks so much for you prompt reply. I'm really banging my head against the wall, feeling inordinately thick for not being able to decompress a simple .bz2 file. </p> <p>By the by, used 7zip to decompress it manually, to make sure the file isn't wonky or anything, and it decompresses fine.</p>
4
2009-08-09T05:01:42Z
3,637,469
<p>This was very helpful. 44 of 2300 files gave an end of file missing error, on Windows open. Adding the b(inary) flag to open fixed the problem.</p> <pre><code>for line in bz2.BZ2File(filename, 'rb', 10000000) : </code></pre> <p>works well. (the 10M is the buffering size that works well with the large files involved)</p> <p>Thanks!</p>
5
2010-09-03T15:55:57Z
[ "python", "decompression", "decompress" ]
Network Support for Pygame
1,250,739
<p>I am making a simple multiplayer economic game in pygame. It consists of turns of a certain length, at the end of which, data is sent to the central server. A few quick calculations are done on the data and the results are sent back to the players. My question is how I should implement the network support. I was looking at Twisted and at Pyro and any suggestions or advice would be appreciated.</p>
3
2009-08-09T05:31:05Z
1,251,235
<p>Twisted would certainly be a good idea. <a href="https://launchpad.net/game">Here</a> is example code that integrates twisted and pygame.</p>
5
2009-08-09T11:49:52Z
[ "python", "twisted", "pygame", "pyro" ]
Network Support for Pygame
1,250,739
<p>I am making a simple multiplayer economic game in pygame. It consists of turns of a certain length, at the end of which, data is sent to the central server. A few quick calculations are done on the data and the results are sent back to the players. My question is how I should implement the network support. I was looking at Twisted and at Pyro and any suggestions or advice would be appreciated.</p>
3
2009-08-09T05:31:05Z
1,255,178
<p>I've nothing against Twisted and PyRo, but the sort of simple messages you're going to be sending don't require anything like that and might be overcomplicated by using some sort of framework. Pickling an object and sending it over a socket is actually a very easy operation and well worth trying, even if you do eventually go with a more heavyweight framework. Don't fear the network!</p>
1
2009-08-10T14:23:19Z
[ "python", "twisted", "pygame", "pyro" ]
Network Support for Pygame
1,250,739
<p>I am making a simple multiplayer economic game in pygame. It consists of turns of a certain length, at the end of which, data is sent to the central server. A few quick calculations are done on the data and the results are sent back to the players. My question is how I should implement the network support. I was looking at Twisted and at Pyro and any suggestions or advice would be appreciated.</p>
3
2009-08-09T05:31:05Z
9,494,305
<p>There are a number of plug-and-play libraries tailored specifically to work nicely with PyGame on the <a href="http://pygame.org" rel="nofollow">pygame.org</a> website.</p> <p>These include PodSixNet, PygLibs.net, and my own Mastermind (which is, at the risk of self-aggrandizement, lightweight, easy to use, and comes with a simple tutorial).</p>
0
2012-02-29T06:05:49Z
[ "python", "twisted", "pygame", "pyro" ]
Python Class vs. Module Attributes
1,250,779
<p>I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?</p> <p>The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.</p> <p>Feel free to comment on how you would handle the following situations:</p> <ol> <li>Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.</li> <li>Default class attribute, that in rare occasions updated for a special instance of the class.</li> <li>Global data structure used to represent an internal state of a class shared between all instances.</li> <li>A class that initializes a number of default attributes, not influenced by constructor arguments.</li> </ol> <p>Some Related Posts: <br> <a href="http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes">Difference Between Class and Instance Attributes</a></p>
12
2009-08-09T06:04:50Z
1,250,801
<p>Class attributes are often used to allow overriding defaults in subclasses. For example, BaseHTTPRequestHandler has class constants sys_version and server_version, the latter defaulting to <code>"BaseHTTP/" + __version__</code>. SimpleHTTPRequestHandler overrides server_version to <code>"SimpleHTTP/" + __version__</code>.</p>
2
2009-08-09T06:25:04Z
[ "python", "attributes", "class-design", "module" ]
Python Class vs. Module Attributes
1,250,779
<p>I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?</p> <p>The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.</p> <p>Feel free to comment on how you would handle the following situations:</p> <ol> <li>Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.</li> <li>Default class attribute, that in rare occasions updated for a special instance of the class.</li> <li>Global data structure used to represent an internal state of a class shared between all instances.</li> <li>A class that initializes a number of default attributes, not influenced by constructor arguments.</li> </ol> <p>Some Related Posts: <br> <a href="http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes">Difference Between Class and Instance Attributes</a></p>
12
2009-08-09T06:04:50Z
1,251,052
<p>Encapsulation is a good principle: when an attribute is inside the class it pertains to instead of being in the global scope, this gives additional information to people reading the code.</p> <p>In your situations 1-4, I would thus avoid globals as much as I can, and prefer using class attributes, which allow one to benefit from encapsulation.</p>
1
2009-08-09T09:51:08Z
[ "python", "attributes", "class-design", "module" ]
Python Class vs. Module Attributes
1,250,779
<p>I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?</p> <p>The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.</p> <p>Feel free to comment on how you would handle the following situations:</p> <ol> <li>Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.</li> <li>Default class attribute, that in rare occasions updated for a special instance of the class.</li> <li>Global data structure used to represent an internal state of a class shared between all instances.</li> <li>A class that initializes a number of default attributes, not influenced by constructor arguments.</li> </ol> <p>Some Related Posts: <br> <a href="http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes">Difference Between Class and Instance Attributes</a></p>
12
2009-08-09T06:04:50Z
1,251,929
<p>#4: I <em>never</em> use class attributes to initialize default instance attributes (the ones you normally put in <code>__init__</code>). For example:</p> <pre><code>class Obj(object): def __init__(self): self.users = 0 </code></pre> <p>and never:</p> <pre><code>class Obj(object): users = 0 </code></pre> <p>Why? Because it's inconsistent: it doesn't do what you want when you assign anything but an invariant object:</p> <pre><code>class Obj(object): users = [] </code></pre> <p>causes the users list to be shared across all objects, which in this case isn't wanted. It's confusing to split these into class attributes and assignments in <code>__init__</code> depending on their type, so I always put them all in <code>__init__</code>, which I find clearer anyway.</p> <hr> <p>As for the rest, I generally put class-specific values inside the class. This isn't so much because globals are "evil"--they're not so big a deal as in some languages, because they're still scoped to the module, unless the module itself is too big--but if external code wants to access them, it's handy to have all of the relevant values in one place. For example, in module.py:</p> <pre><code>class Obj(object): class Exception(Exception): pass ... </code></pre> <p>and then:</p> <pre><code>from module import Obj try: o = Obj() o.go() except o.Exception: print "error" </code></pre> <p>Aside from allowing subclasses to change the value (which isn't always wanted anyway), it means I don't have to laboriously import exception names and a bunch of other stuff needed to use Obj. "from module import Obj, ObjException, ..." gets tiresome quickly.</p>
7
2009-08-09T18:29:25Z
[ "python", "attributes", "class-design", "module" ]
Python Class vs. Module Attributes
1,250,779
<p>I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?</p> <p>The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.</p> <p>Feel free to comment on how you would handle the following situations:</p> <ol> <li>Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.</li> <li>Default class attribute, that in rare occasions updated for a special instance of the class.</li> <li>Global data structure used to represent an internal state of a class shared between all instances.</li> <li>A class that initializes a number of default attributes, not influenced by constructor arguments.</li> </ol> <p>Some Related Posts: <br> <a href="http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes">Difference Between Class and Instance Attributes</a></p>
12
2009-08-09T06:04:50Z
1,252,241
<blockquote> <p>what is a good use case for class attributes</p> </blockquote> <p><strong>Case 0.</strong> Class methods are just class attributes. This is not just a technical similarity - you can access and modify class methods at runtime by assigning callables to them.</p> <p><strong>Case 1.</strong> A module can easily define several classes. It's reasonable to encapsulate everything about <code>class A</code> into <code>A...</code> and everything about <code>class B</code> into <code>B...</code>. For example, </p> <pre><code># module xxx class X: MAX_THREADS = 100 ... # main program from xxx import X if nthreads &lt; X.MAX_THREADS: ... </code></pre> <p><strong>Case 2.</strong> This class has lots of default attributes which can be modified in an instance. Here the ability to leave attribute to be a 'global default' is a feature, not bug. </p> <pre><code>class NiceDiff: """Formats time difference given in seconds into a form '15 minutes ago'.""" magic = .249 pattern = 'in {0}', 'right now', '{0} ago' divisions = 1 # there are more default attributes </code></pre> <p>One creates instance of NiceDiff to use the existing or slightly modified formatting, but a localizer to a different language subclasses the class to implement some functions in a fundamentally different way <strong>and</strong> redefine constants:</p> <pre><code>class Разница(NiceDiff): # NiceDiff localized to Russian '''Из разницы во времени, типа -300, делает конкретно '5 минут назад'.''' pattern = 'через {0}', 'прям щас', '{0} назад' </code></pre> <p><strong>Your cases</strong>: </p> <ul> <li>constants -- yes, I put them to class. It's strange to say <code>self.CONSTANT = ...</code>, so I don't see a big risk for clobbering them. </li> <li>Default attribute -- mixed, as above may go to class, but may also go to <code>__init__</code> depending on the semantics. </li> <li>Global data structure --- goes to class if used <strong>only</strong> by the class, but may also go to module, in either case must be <strong>very</strong> well-documented. </li> </ul>
3
2009-08-09T20:44:43Z
[ "python", "attributes", "class-design", "module" ]
python urllib, how to watch messages?
1,250,965
<p>How can I watch the messages being sent back and for on urllib shttp requests? If it were simple http I would just watch the socket traffic but of course that won't work for https. Is there a debug flag I can set that will do this?</p> <pre><code>import urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("https://example.com/cgi-bin/query", params) </code></pre>
2
2009-08-09T08:42:45Z
1,251,248
<p>No, there's no debug flag to watch this.</p> <p>You can use your favorite debugger. It is the easiest option. Just add a breakpoint in the urlopen function and you're done.</p> <p>Another option would be to write your own download function:</p> <pre><code>def graburl(url, **params): print "LOG: Going to %s with %r" % (url, params) params = urllib.urlencode(params) return urllib.urlopen(url, params) </code></pre> <p>And use it like this:</p> <pre><code>f = graburl("https://example.com/cgi-bin/query", spam=1, eggs=2, bacon=0) </code></pre>
1
2009-08-09T11:55:40Z
[ "python", "https", "urllib" ]
python urllib, how to watch messages?
1,250,965
<p>How can I watch the messages being sent back and for on urllib shttp requests? If it were simple http I would just watch the socket traffic but of course that won't work for https. Is there a debug flag I can set that will do this?</p> <pre><code>import urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("https://example.com/cgi-bin/query", params) </code></pre>
2
2009-08-09T08:42:45Z
1,251,324
<p>You can always do a little bit of mokeypatching</p> <pre><code>import httplib # override the HTTPS request class class DebugHTTPS(httplib.HTTPS): real_putheader = httplib.HTTPS.putheader def putheader(self, *args, **kwargs): print 'putheader(%s,%s)' % (args, kwargs) result = self.real_putheader(self, *args, **kwargs) return result httplib.HTTPS = DebugHTTPS # set a new default urlopener import urllib class DebugOpener(urllib.FancyURLopener): def open(self, *args, **kwargs): result = urllib.FancyURLopener.open(self, *args, **kwargs) print 'response:' print result.headers return result urllib._urlopener = DebugOpener() params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("https://www.google.com/", params) </code></pre> <p>gives the output</p> <pre><code>putheader(('Content-Type', 'application/x-www-form-urlencoded'),{}) putheader(('Content-Length', '21'),{}) putheader(('Host', 'www.google.com'),{}) putheader(('User-Agent', 'Python-urllib/1.17'),{}) response: Content-Type: text/html; charset=UTF-8 Content-Length: 1363 Date: Sun, 09 Aug 2009 12:49:59 GMT Server: GFE/2.0 </code></pre>
2
2009-08-09T12:53:00Z
[ "python", "https", "urllib" ]
Any reason why socket.send() hangs?
1,250,979
<p>I'm writing an mini FTP server in Python that exposes an underlying database as if it was FTP. The flow is something like this:</p> <pre><code>sock.send("150 Here's the file you wanted\r\n") proc = Popen2(...) for parts in data: data_sock.send(parts) proc.kill() sock.send("226 There's the file you wanted\r\n") data_sock.shutdown(0) data_sock.close() </code></pre> <p>data_sock is the PASV socket that's up and working, confirmed by Wireshark. What's actually happening is after the 163,328th byte has been sent over the data_sock, the data_sock.send() line just hangs. I suspect the send buffer is full, but it's a mystery to me why the FTP clients wouldn't be reading from the PASV socket.</p> <p>I've included the Popen2(...) line because I've managed to reproduce <a href="http://bugs.python.org/issue3006" rel="nofollow">http://bugs.python.org/issue3006</a> on OS X--sockets don't close until the Popen process is killed. Not sure if this is somehow related.</p>
1
2009-08-09T08:57:13Z
1,250,984
<p>I've encountered similar issues on the client side on uploads, which seem to trace to the modem/router choking -- the only workround I have at the moment is to throttle the transmission rate (send 128 bytes, sleep ~50ms, repeat).</p>
0
2009-08-09T09:03:33Z
[ "python", "sockets", "ftp" ]
Any reason why socket.send() hangs?
1,250,979
<p>I'm writing an mini FTP server in Python that exposes an underlying database as if it was FTP. The flow is something like this:</p> <pre><code>sock.send("150 Here's the file you wanted\r\n") proc = Popen2(...) for parts in data: data_sock.send(parts) proc.kill() sock.send("226 There's the file you wanted\r\n") data_sock.shutdown(0) data_sock.close() </code></pre> <p>data_sock is the PASV socket that's up and working, confirmed by Wireshark. What's actually happening is after the 163,328th byte has been sent over the data_sock, the data_sock.send() line just hangs. I suspect the send buffer is full, but it's a mystery to me why the FTP clients wouldn't be reading from the PASV socket.</p> <p>I've included the Popen2(...) line because I've managed to reproduce <a href="http://bugs.python.org/issue3006" rel="nofollow">http://bugs.python.org/issue3006</a> on OS X--sockets don't close until the Popen process is killed. Not sure if this is somehow related.</p>
1
2009-08-09T08:57:13Z
1,251,551
<p>Hard to say from this code fragment and not knowing the client, but is it possible that your sending of 150 (indicating a new data channel), not 125 (indicating use of existing data channel) confuses the client and it simply does not start reading the data?</p> <p>Have you had a look of <a href="http://code.google.com/p/pyftpdlib/" rel="nofollow">pyftpdlib</a> as an alternative for rolling your own server?</p>
1
2009-08-09T15:08:28Z
[ "python", "sockets", "ftp" ]
Any reason why socket.send() hangs?
1,250,979
<p>I'm writing an mini FTP server in Python that exposes an underlying database as if it was FTP. The flow is something like this:</p> <pre><code>sock.send("150 Here's the file you wanted\r\n") proc = Popen2(...) for parts in data: data_sock.send(parts) proc.kill() sock.send("226 There's the file you wanted\r\n") data_sock.shutdown(0) data_sock.close() </code></pre> <p>data_sock is the PASV socket that's up and working, confirmed by Wireshark. What's actually happening is after the 163,328th byte has been sent over the data_sock, the data_sock.send() line just hangs. I suspect the send buffer is full, but it's a mystery to me why the FTP clients wouldn't be reading from the PASV socket.</p> <p>I've included the Popen2(...) line because I've managed to reproduce <a href="http://bugs.python.org/issue3006" rel="nofollow">http://bugs.python.org/issue3006</a> on OS X--sockets don't close until the Popen process is killed. Not sure if this is somehow related.</p>
1
2009-08-09T08:57:13Z
1,251,610
<p>One reason a client could stop reading the data is that somebody unplugged the client (or disconnected its Ethernet cable) during the transfer. In that case, TCP will keep (unsuccessfully) resending packets for several minutes, getting no response, until it gives up. There are other possible reasons as well.</p> <p>Since the above possibilities are something you'll have to deal with if you want a robust server, the real question is not necessarily why it happens but rather what you should do when it does happen. Some possible things to do are:</p> <ol> <li>Make sure the clients don't have any bugs that cause them to stop reading even though data is available</li> <li>Make sure that the server doesn't block even if a particular connection's send() call does block (you can do this via select()/poll() and non-blocking sockets, or possibly via multithreading... I recommend the former if possible)</li> <li>Add some timeout logic to select() so that if more than (N) seconds go by where a socket has data ready to send but isn't actually sending it, the server gives up and closes the socket. (TCP does this itself, but TCP's timeout period may be too long for your taste) </ol>
0
2009-08-09T15:44:13Z
[ "python", "sockets", "ftp" ]
Writing Windows GUI applications with embedded Python scripts
1,251,260
<p>What would be the optimal way to develop a basic graphical application for Windows based on a Python console script? It would be great if the solution could be distributed as a standalone directory, containing the <code>.exe</code> file.</p>
1
2009-08-09T12:04:01Z
1,251,275
<p>I would recommend that you use IronPython, which is Microsoft's implementation of Python for the .NET framework.</p>
3
2009-08-09T12:15:28Z
[ "python", "windows", "user-interface" ]
Writing Windows GUI applications with embedded Python scripts
1,251,260
<p>What would be the optimal way to develop a basic graphical application for Windows based on a Python console script? It would be great if the solution could be distributed as a standalone directory, containing the <code>.exe</code> file.</p>
1
2009-08-09T12:04:01Z
1,251,299
<p>As far as I understand your question, you want to write a graphical windows application in Python, to do this I suggest using wxPython and then py2exe to create a standalone exe that can run on any machine without requiring python to be installed</p> <p>The following tutorial shows everything step by step: <a href="http://www.osdc.org.il/2006/html/quickly%5Fcreating%5Fprofessional%5Flooking%5Fapplication%5Fusing%5Fwxpython%5Fpy2exe%5Fand%5Finnosetup.pdf">Quickly Creating Professional Looking Application Using wxPython, py2exe and InnoSetup</a></p>
8
2009-08-09T12:31:52Z
[ "python", "windows", "user-interface" ]
Writing Windows GUI applications with embedded Python scripts
1,251,260
<p>What would be the optimal way to develop a basic graphical application for Windows based on a Python console script? It would be great if the solution could be distributed as a standalone directory, containing the <code>.exe</code> file.</p>
1
2009-08-09T12:04:01Z
1,253,389
<p><a href="http://docs.python.org/library/tkinter.html" rel="nofollow">Tkinter</a> is quick and easy to use. Tkinter is in the Python standard library.</p>
2
2009-08-10T06:34:18Z
[ "python", "windows", "user-interface" ]
Difference between returning modified class and using type()
1,251,294
<p>I guess it's more of a python question than a django one, but I couldn't replicate this behavior anywhere else, so I'll use exact code that doesn't work as expected.</p> <p>I was working on some dynamic forms in django, when I found this factory function snippet:</p> <pre><code>def get_employee_form(employee): """Return the form for a specific Board.""" employee_fields = EmployeeFieldModel.objects.filter(employee = employee).order_by ('order') class EmployeeForm(forms.Form): def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.employee = employee def save(self): "Do the save" for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return type('EmployeeForm', (forms.Form, ), dict(EmployeeForm.__dict__)) </code></pre> <p>[from :<a href="http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/" rel="nofollow">http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/</a>]</p> <p>And there's one thing that I don't understand, <b> why returning modified EmployeeForm doesn't do the trick?</b> I mean something like this:</p> <pre><code>def get_employee_form(employee): #[...]same function body as before for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return EmployeeForm </code></pre> <p>When I tried returning modified class django ignored my additional fields, but returning type()'s result works perfectly.</p>
3
2009-08-09T12:28:12Z
1,251,343
<p>I just tried this with straight non-django classes and it worked. So it's not a Python issue, but a Django issue.</p> <p>And in this case (although I'm not 100% sure), it's a question of what the Form class does during class creation. I think it has a meta class, and that this meta class will finalize the form initialization during class creation. That means that any fields you add after class creation will be ignored.</p> <p>Therefore you need to create a new class, as is done with the type() statement, so that the class creation code of the meta class is involved, now with the new fields.</p>
3
2009-08-09T13:05:37Z
[ "python", "django", "class", "types" ]
Difference between returning modified class and using type()
1,251,294
<p>I guess it's more of a python question than a django one, but I couldn't replicate this behavior anywhere else, so I'll use exact code that doesn't work as expected.</p> <p>I was working on some dynamic forms in django, when I found this factory function snippet:</p> <pre><code>def get_employee_form(employee): """Return the form for a specific Board.""" employee_fields = EmployeeFieldModel.objects.filter(employee = employee).order_by ('order') class EmployeeForm(forms.Form): def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.employee = employee def save(self): "Do the save" for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return type('EmployeeForm', (forms.Form, ), dict(EmployeeForm.__dict__)) </code></pre> <p>[from :<a href="http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/" rel="nofollow">http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/</a>]</p> <p>And there's one thing that I don't understand, <b> why returning modified EmployeeForm doesn't do the trick?</b> I mean something like this:</p> <pre><code>def get_employee_form(employee): #[...]same function body as before for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return EmployeeForm </code></pre> <p>When I tried returning modified class django ignored my additional fields, but returning type()'s result works perfectly.</p>
3
2009-08-09T12:28:12Z
1,251,567
<p>Lennart's hypothesis is correct: a metaclass is indeed the culprit. No need to guess, just look at <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/forms.py" rel="nofollow">the sources</a>: the metaclass is <code>DeclarativeFieldsMetaclass</code> currently at line 53 of that file, and adds attributes <code>base_fields</code> and possibly <code>media</code> based on what attributes the class has at creation time. At line 329 ff you see:</p> <pre><code>class Form(BaseForm): "A collection of Fields, plus their associated data." # This is a separate class from BaseForm in order to abstract the way # self.fields is specified. This class (Form) is the one that does the # fancy metaclass stuff purely for the semantic sugar -- it allows one # to define a form using declarative syntax. # BaseForm itself has no way of designating self.fields. __metaclass__ = DeclarativeFieldsMetaclass </code></pre> <p>This implies there's some fragility in creating a new class with base <code>type</code> -- the supplied black magic might or might not carry through! A more solid approach is to use the type of <code>EmployeeForm</code> which will pick up any metaclass that may be involved -- i.e.:</p> <pre><code>return type(EmployeeForm)('EmployeeForm', (forms.Form, ), EmployeeForm.__dict__) </code></pre> <p>(no need to copy that <code>__dict__</code>, btw). The difference is subtle but important: rather than using directly <code>type</code>'s 3-args form, we use the 1-arg form to pick up the type (i.e., the metaclass) of the form class, then call THAT metaclass in the 3-args form.</p> <p>Blackly magicallish indeed, but then that's the downside of frameworks which do such use of "fancy metaclass stuff purely for the semantic sugar" &amp;c: you're in clover as long as you want to do exactly what the framework supports, but to get out of that support even a little bit may require countervailing wizardry (which goes some way towards explaining why often I'd rather use a lightweight, transparent setup, such as werkzeug, rather than a framework that ladles magic upon me like Rails or Django do: my mastery of deep black magic does NOT mean I'm happy to have to USE it in plain production code... but, that's another discussion;-).</p>
5
2009-08-09T15:21:58Z
[ "python", "django", "class", "types" ]
Difference between returning modified class and using type()
1,251,294
<p>I guess it's more of a python question than a django one, but I couldn't replicate this behavior anywhere else, so I'll use exact code that doesn't work as expected.</p> <p>I was working on some dynamic forms in django, when I found this factory function snippet:</p> <pre><code>def get_employee_form(employee): """Return the form for a specific Board.""" employee_fields = EmployeeFieldModel.objects.filter(employee = employee).order_by ('order') class EmployeeForm(forms.Form): def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.employee = employee def save(self): "Do the save" for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return type('EmployeeForm', (forms.Form, ), dict(EmployeeForm.__dict__)) </code></pre> <p>[from :<a href="http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/" rel="nofollow">http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/</a>]</p> <p>And there's one thing that I don't understand, <b> why returning modified EmployeeForm doesn't do the trick?</b> I mean something like this:</p> <pre><code>def get_employee_form(employee): #[...]same function body as before for field in employee_fields: setattr(EmployeeForm, field.name, copy(type_mapping[field.type])) return EmployeeForm </code></pre> <p>When I tried returning modified class django ignored my additional fields, but returning type()'s result works perfectly.</p>
3
2009-08-09T12:28:12Z
1,400,444
<p>It's worth noting that this code snippet is a very poor means to the desired end, and involves a common misunderstanding about Django Form objects - that a Form object should map one-to-one with an HTML form. The correct way to do something like this (which doesn't require messing with any metaclass magic) is to use multiple Form objects and an <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets" rel="nofollow">inline formset</a>.</p> <p>Or, if for some odd reason you really want to keep things in a single Form object, just manipulate self.fields in the Form's __init__ method.</p>
1
2009-09-09T15:38:15Z
[ "python", "django", "class", "types" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,251,406
<p>As far as I know, this behaviour is perfectly reasonable. Sockets may, and probably <strong>will</strong> fragment your data as they transmit it. You should be prepared to handle such cases by applying appropriate buffering techniques.</p> <p>On other hand, if you are transmitting the data on the localhost and you are indeed getting only 4 bytes it probably means you have a bug somewhere else in your code.</p> <p><em>EDIT: An idea - try to fire up a packet sniffer and see whenever the packet transmitted will be full or not; this might give you some insight whenever your bug is in your client or in your server.</em></p>
9
2009-08-09T13:45:38Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,251,407
<p>From the Linux man page of recv <a href="http://linux.about.com/library/cmd/blcmdl2%5Frecv.htm" rel="nofollow">http://linux.about.com/library/cmd/blcmdl2_recv.htm</a>: </p> <blockquote> <p>The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested. </p> </blockquote> <p>So, if your sender is still transmitting bytes, the call will only give what has been transmitted so far.</p>
1
2009-08-09T13:45:40Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,251,410
<p>If the sender sends 515 bytes, and your BUFSIZE is 512, then the first recv will return 512 bytes, and the next will return 3 bytes... Could this be what's happening?</p> <p>(This is just one case amongst many which will result in a 3-byte recv from a larger send...)</p>
1
2009-08-09T13:47:29Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,251,512
<p>I assume you're using TCP. TCP is a stream based protocol with no idea of packets or message boundaries.</p> <p>This means when you do a read you may get less bytes than you request. If your data is 128k for example you may only get 24k on your first read requiring you to read again to get the rest of the data.</p> <p>For an example in C:</p> <pre><code>int read_data(int sock, int size, unsigned char *buf) { int bytes_read = 0, len = 0; while (bytes_read &lt; size &amp;&amp; ((len = recv(sock, buf + bytes_read,size-bytes_read, 0)) &gt; 0)) { bytes_read += len; } if (len == 0 || len &lt; 0) doerror(); return bytes_read; } </code></pre>
13
2009-08-09T14:43:25Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,251,533
<p>This is just the way TCP works. You aren't going to get all of your data at once. There are just too many timing issues between sender and receiver including the senders operating system, NIC, routers, switches, the wires themselves, the receivers NIC, OS, etc. There are buffers in the hardware, and in the OS.</p> <p>You can't assume that the TCP network is the same as a OS pipe. With the pipe, it's all software so there's no cost in delivering the whole message at once for most messages. With the network, you have to assume there will be timing issues, even in a simple network.</p> <p>That's why recv() can't give you all the data at once, it may just not be available, even if everything is working right. Normally, you will call recv() and catch the output. That should tell you how many bytes you've received. If it's less than you expect, you need to keep calling recv() (as has been suggested) until you get the correct number of bytes. Be aware that in most cases, recv() returns -1 on error, so check for that and check your documentation for ERRNO values. EAGAIN in particular seems to cause people problems. You can read about it on the internet for details, but if I recall, it means that no data is available at the moment and you should try again.</p> <p>Also, it sounds like from your post that you're sure the sender is sending the data you need sent, but just to be complete, check this: <a href="http://beej.us/guide/bgnet/output/html/multipage/advanced.html#sendall" rel="nofollow">http://beej.us/guide/bgnet/output/html/multipage/advanced.html#sendall</a></p> <p>You should be doing something similar on the recv() end to handle partial receives. If you have a fixed packet size, you should read until you get the amount of data you expect. If you have a variable packet size, you should read until you have the header that tells you how much data you send(), then read that much more data.</p>
3
2009-08-09T14:55:53Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,253,120
<p>The simple answer to your question, "Read from socket: Is it guaranteed to at least get x bytes?", is <strong>no</strong>. Look at the doc strings for these socket methods:</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket() &gt;&gt;&gt; print s.recv.__doc__ recv(buffersize[, flags]) -&gt; data Receive up to buffersize bytes from the socket. For the optional flags argument, see the Unix manual. When no data is available, block until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, return the empty string. &gt;&gt;&gt; &gt;&gt;&gt; print s.settimeout.__doc__ settimeout(timeout) Set a timeout on socket operations. 'timeout' can be a float, giving in seconds, or None. Setting a timeout of None disables the timeout feature and is equivalent to setblocking(1). Setting a timeout of zero is the same as setblocking(0). &gt;&gt;&gt; &gt;&gt;&gt; print s.setblocking.__doc__ setblocking(flag) Set the socket to blocking (flag is true) or non-blocking (false). setblocking(True) is equivalent to settimeout(None); setblocking(False) is equivalent to settimeout(0.0). </code></pre> <p>From this it is clear that <code>recv()</code> is not required to return as many bytes as you asked for. Also, because you are calling <code>settimeout(10.0)</code>, it is possible that some, but not all, data is received near the expiration time for the <code>recv()</code>. In that case <code>recv()</code> will return what it has read - which will be less than you asked for (but consistenty &lt; 4 bytes does seem unlikely).</p> <p>You mention <code>datagram</code> in your question which implies that you are using (connectionless) UDP sockets (not TCP). The distinction is <a href="http://en.wikipedia.org/wiki/Packet%5F%28information%5Ftechnology%29#Packets%5Fvs.%5Fdatagrams" rel="nofollow">described here</a>. The posted code does not show socket creation so we can only guess here, however, this detail can be important. It may help if you could post a more complete sample of your code.</p> <p>If the problem is reproducible you could disable the timeout (which incidentally you do not seem to be handling) and see if that fixes the problem.</p>
5
2009-08-10T04:39:06Z
[ "python", "sockets", "network-protocols" ]
Read from socket: Is it guaranteed to at least get x bytes?
1,251,392
<p>I have a rare bug that seems to occur reading a socket.</p> <p>It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.</p> <p>As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.</p> <p>Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.</p> <p>In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?</p> <p>Does anybody know more?</p> <p>Here is the reading-code I use:</p> <pre><code>mySock, addr = masterSock.accept() mySock.settimeout(10.0) result = mySock.recv(BUFSIZE) # 4 bytes are needed here ... ... # read remainder of datagram ... </code></pre> <p>The sender sends the complete datagram with one call of send.</p> <p>Edit: the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.</p>
4
2009-08-09T13:35:11Z
1,484,627
<p>If you are still interested, patterns like this :</p> <pre><code># 4 bytes are needed here ...... # read remainder of datagram... </code></pre> <p>may create the silly window thing.</p> <p>Check <a href="http://tangentsoft.net/wskfaq/intermediate.html#silly-window" rel="nofollow">this</a> out</p>
1
2009-09-27T22:15:33Z
[ "python", "sockets", "network-protocols" ]
Where is the hidden parameter?
1,251,427
<p>I have this function call here:</p> <pre><code>import test_hosts test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port) </code></pre> <p>and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.</p> <p><code>LocalTestHost</code> is a class which its constructor takes a <code>self</code> parameter and six others: resulting in a total of 7 parameters. This is it's declaration:</p> <pre><code>class LocalTestHost: def __init__(self, mst, port, local_ip, remote_if_mac, remote_if_ip, service_port): ... </code></pre> <p>I've stared at this code for hours, and I can't find the problem. When I run this as is, it fails because I pass 6 parameters, which is too few, if I call the constructor with an added parameter just to see that I can still count, it says I'm passing 8 parameters, which is too many.</p>
1
2009-08-09T13:55:32Z
1,251,442
<p>I've seen these issues before, but it was because of preceding code being crafted in such a way that it syntactically correct but was not as I had intended.</p> <p>This snippet isn't enough to reproduce the problem for me, at least not on 2.5.1 on OS X.</p>
1
2009-08-09T14:02:20Z
[ "python" ]
Where is the hidden parameter?
1,251,427
<p>I have this function call here:</p> <pre><code>import test_hosts test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port) </code></pre> <p>and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.</p> <p><code>LocalTestHost</code> is a class which its constructor takes a <code>self</code> parameter and six others: resulting in a total of 7 parameters. This is it's declaration:</p> <pre><code>class LocalTestHost: def __init__(self, mst, port, local_ip, remote_if_mac, remote_if_ip, service_port): ... </code></pre> <p>I've stared at this code for hours, and I can't find the problem. When I run this as is, it fails because I pass 6 parameters, which is too few, if I call the constructor with an added parameter just to see that I can still count, it says I'm passing 8 parameters, which is too many.</p>
1
2009-08-09T13:55:32Z
1,251,483
<p>Another idea: you are inadvertently calling an older version of the code. Make sure you don't have a .pyc file lying around somewhere.</p>
2
2009-08-09T14:24:37Z
[ "python" ]
Where is the hidden parameter?
1,251,427
<p>I have this function call here:</p> <pre><code>import test_hosts test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port) </code></pre> <p>and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.</p> <p><code>LocalTestHost</code> is a class which its constructor takes a <code>self</code> parameter and six others: resulting in a total of 7 parameters. This is it's declaration:</p> <pre><code>class LocalTestHost: def __init__(self, mst, port, local_ip, remote_if_mac, remote_if_ip, service_port): ... </code></pre> <p>I've stared at this code for hours, and I can't find the problem. When I run this as is, it fails because I pass 6 parameters, which is too few, if I call the constructor with an added parameter just to see that I can still count, it says I'm passing 8 parameters, which is too many.</p>
1
2009-08-09T13:55:32Z
1,252,170
<p>The snippets of code you pasted look fine. As others correctly said, to find the problem you should find the smallest amount of code that still has the bug.</p> <p>My suggestion would be to </p> <p>(1) check that module <code>test_hosts</code> is written for your version of Python and that it's indeed the file being imported </p> <p>(2) copy the <code>class LocalTestHost: def __init__(...</code> function to your file and try calling it from there. It will raise something like NameError if you get the # of params right.</p> <p>(3) if the above function works for you, check the <code>test_hosts.LocalTestHost.__init__()</code> signature using runtime introspection. somebody might be changing it by e.g. <code>__init__ = staticmethod(__init__)</code> somewhere (an old method of defining static functions).</p> <p>And please tell us how it's going!</p>
3
2009-08-09T20:19:08Z
[ "python" ]
Where is the hidden parameter?
1,251,427
<p>I have this function call here:</p> <pre><code>import test_hosts test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port) </code></pre> <p>and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.</p> <p><code>LocalTestHost</code> is a class which its constructor takes a <code>self</code> parameter and six others: resulting in a total of 7 parameters. This is it's declaration:</p> <pre><code>class LocalTestHost: def __init__(self, mst, port, local_ip, remote_if_mac, remote_if_ip, service_port): ... </code></pre> <p>I've stared at this code for hours, and I can't find the problem. When I run this as is, it fails because I pass 6 parameters, which is too few, if I call the constructor with an added parameter just to see that I can still count, it says I'm passing 8 parameters, which is too many.</p>
1
2009-08-09T13:55:32Z
1,260,842
<p>My god, I was an idiot. I need to start reading the error messages more thoroughly.</p> <p>The code that actually caused the problem wasn't in here actually. It was several lines inside the constructor. Here it is:</p> <pre><code>class LocalTestHost: def __init__(self, mst, port, local_ip, remote_if_mac, remote_if_ip, service_port): . . &lt;some initialization code&gt; . # This is the faulty line self.__host_operations = HostOperationsFactory().create( local_ip, port, mst, remote_if_ip) </code></pre> <p>And here is the error message, I kept not reading, and foolishly did not post with my question:</p> <pre><code>&gt;&gt;&gt; test_hosts.LocalTestHost(1,2,3,4,5,6) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "test_hosts.py", line 709, in __init__ self.__host_operations = HostOperationsFactory().create( File "test_hosts.py", line 339, in create remote_ip) File "test_hosts.py", line 110, in __init__ packet_size, remote_ip) TypeError: __init__() takes exactly 7 arguments (6 given) </code></pre> <p>I've refactored my code a bit, and added parameters to several methods and constructors, but I forgot to update their usage in several places. This <code>create</code> function actually returns another object it instantiates, and it's constructor (incidentally has the same parameters as the constructor I picked on) did not receive all the parameters it should have.</p> <p>I did not read the message thoroughly, and my confusion came from the last line stating I have passed the constructor too few parameters. Now, I also tried adding too many parameters as a sanity check, and there it actually was the constructor I was picking on. I'm surprised I didn't see that in this case the error trace was significantly shorter.</p> <p>I've learned a valuable lesson today. The problem is I think I've leaned it several times already for some years.</p>
1
2009-08-11T14:46:00Z
[ "python" ]
Catmull-Rom splines in python
1,251,438
<p>Is there a library or function in python to compute Catmull-Rom spline from three points ?</p> <p>What I need in the end are the x,y coordinates of points along the spline, provided that they are always equidistant of a given amount t along the spline (say, the spline curve is 3 units long and I want the x,y coordinates at spline length 0, 1, 2 and 3)</p> <p>Nothing really exciting. I am writing it by myself, but if you find something nice, It would be great for testing (or to save time)</p>
2
2009-08-09T14:00:21Z
1,251,478
<p>There's this: <a href="http://www.exch.demon.co.uk/jj%5Fcatmull.htm" rel="nofollow">jj_catmull</a>, which seems to be in Python, maybe you can find what you need there.</p>
1
2009-08-09T14:20:28Z
[ "python", "math", "spline" ]
Catmull-Rom splines in python
1,251,438
<p>Is there a library or function in python to compute Catmull-Rom spline from three points ?</p> <p>What I need in the end are the x,y coordinates of points along the spline, provided that they are always equidistant of a given amount t along the spline (say, the spline curve is 3 units long and I want the x,y coordinates at spline length 0, 1, 2 and 3)</p> <p>Nothing really exciting. I am writing it by myself, but if you find something nice, It would be great for testing (or to save time)</p>
2
2009-08-09T14:00:21Z
1,295,081
<p>3 points ? Catmull-Rom is defined for 4 points, say p_1 p0 p1 p2; a cubic curve goes from p0 to p1, and outer points p_1 and p2 determine the slopes at p0 and p1. To draw a curve through some points in an array P, do something like this:</p> <pre><code>for j in range( 1, len(P)-2 ): # skip the ends for t in range( 10 ): # t: 0 .1 .2 .. .9 p = spline_4p( t/10, P[j-1], P[j], P[j+1], P[j+2] ) # draw p def spline_4p( t, p_1, p0, p1, p2 ): """ Catmull-Rom (Ps can be numpy vectors or arrays too: colors, curves ...) """ # wikipedia Catmull-Rom -&gt; Cubic_Hermite_spline # 0 -&gt; p0, 1 -&gt; p1, 1/2 -&gt; (- p_1 + 9 p0 + 9 p1 - p2) / 16 # assert 0 &lt;= t &lt;= 1 return ( t*((2-t)*t - 1) * p_1 + (t*t*(3*t - 5) + 2) * p0 + t*((4 - 3*t)*t + 1) * p1 + (t-1)*t*t * p2 ) / 2 </code></pre> <p>One <em>can</em> use piecewise quadratic curves through 3 points -- see <a href="http://www.cl.cam.ac.uk/~nad10/pubs/quad.pdf">Dodgson, Quadratic Interpolation for Image Resampling</a>. What do you really want to do ?</p>
6
2009-08-18T16:39:30Z
[ "python", "math", "spline" ]
Catmull-Rom splines in python
1,251,438
<p>Is there a library or function in python to compute Catmull-Rom spline from three points ?</p> <p>What I need in the end are the x,y coordinates of points along the spline, provided that they are always equidistant of a given amount t along the spline (say, the spline curve is 3 units long and I want the x,y coordinates at spline length 0, 1, 2 and 3)</p> <p>Nothing really exciting. I am writing it by myself, but if you find something nice, It would be great for testing (or to save time)</p>
2
2009-08-09T14:00:21Z
39,167,367
<p>As mentioned previously you do need 4 points for catmull-rom, and the endpoints are an issue. I was looking at applying these myself instead of natural cubic splines (which the potential overshoots beyond the known data range is impractical in my application). Similar to @denis's code, here is something that might help you (notice a few things. 1) That code just randomly generates points, I'm sure you can use the commented out examples for how to use your own data. 2) I create extended endpoints, preserving the slope between the first/last two points - using an arbitrary distance of 1% of the domain. 3)I include uniform, centripetal, and chordial knot parameterization for comparison):</p> <p><a href="http://i.stack.imgur.com/KthW9.png" rel="nofollow"><img src="http://i.stack.imgur.com/KthW9.png" alt="Catmull-Rom Python Code Output Example Image"></a></p> <pre><code># coding: utf-8 # In[1]: import numpy import matplotlib.pyplot as plt get_ipython().magic(u'pylab inline') # In[2]: def CatmullRomSpline(P0, P1, P2, P3, a, nPoints=100): """ P0, P1, P2, and P3 should be (x,y) point pairs that define the Catmull-Rom spline. nPoints is the number of points to include in this curve segment. """ # Convert the points to numpy so that we can do array multiplication P0, P1, P2, P3 = map(numpy.array, [P0, P1, P2, P3]) # Calculate t0 to t4 alpha = a def tj(ti, Pi, Pj): xi, yi = Pi xj, yj = Pj return ( ( (xj-xi)**2 + (yj-yi)**2 )**0.5 )**alpha + ti t0 = 0 t1 = tj(t0, P0, P1) t2 = tj(t1, P1, P2) t3 = tj(t2, P2, P3) # Only calculate points between P1 and P2 t = numpy.linspace(t1,t2,nPoints) # Reshape so that we can multiply by the points P0 to P3 # and get a point for each value of t. t = t.reshape(len(t),1) A1 = (t1-t)/(t1-t0)*P0 + (t-t0)/(t1-t0)*P1 A2 = (t2-t)/(t2-t1)*P1 + (t-t1)/(t2-t1)*P2 A3 = (t3-t)/(t3-t2)*P2 + (t-t2)/(t3-t2)*P3 B1 = (t2-t)/(t2-t0)*A1 + (t-t0)/(t2-t0)*A2 B2 = (t3-t)/(t3-t1)*A2 + (t-t1)/(t3-t1)*A3 C = (t2-t)/(t2-t1)*B1 + (t-t1)/(t2-t1)*B2 return C def CatmullRomChain(P,alpha): """ Calculate Catmull Rom for a chain of points and return the combined curve. """ sz = len(P) # The curve C will contain an array of (x,y) points. C = [] for i in range(sz-3): c = CatmullRomSpline(P[i], P[i+1], P[i+2], P[i+3],alpha) C.extend(c) return C # In[139]: # Define a set of points for curve to go through Points = numpy.random.rand(10,2) #Points=array([array([153.01,722.67]),array([152.73,699.92]),array([152.91,683.04]),array([154.6,643.45]), # array([158.07,603.97])]) #Points = array([array([0,92.05330318]), # array([2.39580622,29.76345192]), # array([10.01564963,16.91470591]), # array([15.26219886,71.56301997]), # array([15.51234733,73.76834447]), # array([24.88468545,50.89432899]), # array([27.83934153,81.1341789]), # array([36.80443404,56.55810783]), # array([43.1404725,16.96946811]), # array([45.27824599,15.75903418]), # array([51.58871027,90.63583215])]) x1=Points[0][0] x2=Points[1][0] y1=Points[0][1] y2=Points[1][1] x3=Points[-2][0] x4=Points[-1][0] y3=Points[-2][1] y4=Points[-1][1] dom=max(Points[:,0])-min(Points[:,0]) rng=max(Points[:,1])-min(Points[:,1]) pctdom=1 pctdom=float(pctdom)/100 prex=x1+sign(x1-x2)*dom*pctdom prey=(y1-y2)/(x1-x2)*(prex-x1)+y1 endx=x4+sign(x4-x3)*dom*pctdom endy=(y4-y3)/(x4-x3)*(endx-x4)+y4 print len(Points) Points=list(Points) Points.insert(0,array([prex,prey])) Points.append(array([endx,endy])) print len(Points) # In[140]: #Define alpha a=0. # Calculate the Catmull-Rom splines through the points c = CatmullRomChain(Points,a) # Convert the Catmull-Rom curve points into x and y arrays and plot x,y = zip(*c) plt.plot(x,y,c='green',zorder=10) a=0.5 c = CatmullRomChain(Points,a) x,y = zip(*c) plt.plot(x,y,c='blue') a=1. c = CatmullRomChain(Points,a) x,y = zip(*c) plt.plot(x,y,c='red') # Plot the control points px, py = zip(*Points) plt.plot(px,py,'o',c='black') plt.grid(b=True) plt.show() # In[141]: Points # In[104]: </code></pre>
1
2016-08-26T13:21:03Z
[ "python", "math", "spline" ]
Python imports: Will changing a variable in "child" change variable in "parent"/other children?
1,251,611
<p>Suppose you have 3 modules, a.py, b.py, and c.py:</p> <p>a.py:</p> <pre><code>v1 = 1 v2 = 2 etc. </code></pre> <p>b.py:</p> <pre><code>from a import * </code></pre> <p>c.py:</p> <pre><code>from a import * v1 = 0 </code></pre> <p>Will c.py change v1 in a.py and b.py? If not, is there a way to do it?</p>
2
2009-08-09T15:44:15Z
1,251,616
<p>Yes, you just need to access it correctly (and don't use import *, it's evil)</p> <p>c.py:</p> <pre><code>import a print a.v1 # prints 1 a.v1 = 0 print a.v1 # prints 0 </code></pre>
1
2009-08-09T15:46:31Z
[ "python", "import" ]
Python imports: Will changing a variable in "child" change variable in "parent"/other children?
1,251,611
<p>Suppose you have 3 modules, a.py, b.py, and c.py:</p> <p>a.py:</p> <pre><code>v1 = 1 v2 = 2 etc. </code></pre> <p>b.py:</p> <pre><code>from a import * </code></pre> <p>c.py:</p> <pre><code>from a import * v1 = 0 </code></pre> <p>Will c.py change v1 in a.py and b.py? If not, is there a way to do it?</p>
2
2009-08-09T15:44:15Z
1,251,647
<p>The <code>from ... import *</code> form is basically intended for handy interactive use at the interpreter prompt: you'd be well advised to never use it in other situations, as it will give you nothing but problems.</p> <p>In fact, the in-house style guide at my employer goes further, recommending to always import a module, never contents from within a module (a module from within a package is OK and in fact recommended). As a result, in our codebase, references to imported things are always qualified names (<code>themod.thething</code>) and never barenames (which always refer to builtin, globals of this same module, or locals); this makes the code much clearer and more readable and avoids all kinds of subtle anomalies.</p> <p>Of course, if a module's name is too long, an <code>as</code> clause in the import, to give it a shorter and handier alias for the purposes of the importing module, is fine. But, with your one-letter module names, that won't be needed;-).</p> <p>So, if you follow the guideline and always import the module (and not things from inside it), <code>c.v1</code> will always be referring to the same thing as <code>a.v1</code> and <code>b.v1</code>, both for getting AND setting: here's one potential subtle anomaly avoided right off the bat!-)</p> <p>Remember the very last bit of the Zen of Python (do <code>import this</code> at the interpreter prompt to see it all):</p> <pre><code>Namespaces are one honking great idea -- let's do more of those! </code></pre> <p>Importing the whole module (not bits and pieces from within it) preserves its integrity as a namespace, as does always referring to things inside the imported module by qualified (dotted) names. It's one honking great idea: do more of that!-)</p>
2
2009-08-09T16:03:07Z
[ "python", "import" ]
Python imports: Will changing a variable in "child" change variable in "parent"/other children?
1,251,611
<p>Suppose you have 3 modules, a.py, b.py, and c.py:</p> <p>a.py:</p> <pre><code>v1 = 1 v2 = 2 etc. </code></pre> <p>b.py:</p> <pre><code>from a import * </code></pre> <p>c.py:</p> <pre><code>from a import * v1 = 0 </code></pre> <p>Will c.py change v1 in a.py and b.py? If not, is there a way to do it?</p>
2
2009-08-09T15:44:15Z
1,251,653
<p>All that a statement like:</p> <pre><code>v1 = 0 </code></pre> <p>can do is bind the name <code>v1</code> to the object <code>0</code>. It can't affect a different module.</p> <p>If I'm using unfamiliar terms there, and I guess I probably am, I strongly recommend you read Fredrik Lundh's excellent article <a href="http://effbot.org/zone/python-objects.htm" rel="nofollow">Python Objects: Reset your brain</a>.</p>
5
2009-08-09T16:05:49Z
[ "python", "import" ]
How to enumerate an object's properties in Python?
1,251,692
<p>I C# we do it through reflection. In Javascript it is simple as:</p> <pre><code>for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; </code></pre> <p>How to do it in Python?</p>
66
2009-08-09T16:33:02Z
1,251,702
<pre><code>for property, value in vars(theObject).iteritems(): print property, ": ", value </code></pre> <p>Be aware that in some rare cases there's a <code>__slots__</code> property, such classes often have no <code>__dict__</code>.</p>
77
2009-08-09T16:37:09Z
[ "python", "reflection", "properties" ]
How to enumerate an object's properties in Python?
1,251,692
<p>I C# we do it through reflection. In Javascript it is simple as:</p> <pre><code>for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; </code></pre> <p>How to do it in Python?</p>
66
2009-08-09T16:33:02Z
1,251,704
<p><a href="http://docs.python.org/library/functions.html#dir"><code>dir()</code></a> is the simple way. See here:</p> <p><a href="http://www.ibm.com/developerworks/library/l-pyint.html">Guide To Python Introspection</a></p>
27
2009-08-09T16:37:48Z
[ "python", "reflection", "properties" ]
How to enumerate an object's properties in Python?
1,251,692
<p>I C# we do it through reflection. In Javascript it is simple as:</p> <pre><code>for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; </code></pre> <p>How to do it in Python?</p>
66
2009-08-09T16:33:02Z
1,251,705
<p>The <code>__dict__</code> property of the object is a dictionary of all its other defined properties. Note that Python classes can override <a href="http://docs.python.org/reference/datamodel.html#object.__getattr__" rel="nofollow"><strong>getattr</strong></a> and make things that look like properties but are not in<code>__dict__</code>. There's also the builtin functions <code>vars()</code> and <code>dir()</code> which are different in subtle ways. And <code>__slots__</code> can replace <code>__dict__</code> in some unusual classes.</p> <p>Objects are complicated in Python. <code>__dict__</code> is the right place to start for reflection-style programming. <code>dir()</code> is the place to start if you're hacking around in an interactive shell.</p>
10
2009-08-09T16:37:50Z
[ "python", "reflection", "properties" ]
How to enumerate an object's properties in Python?
1,251,692
<p>I C# we do it through reflection. In Javascript it is simple as:</p> <pre><code>for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; </code></pre> <p>How to do it in Python?</p>
66
2009-08-09T16:33:02Z
1,251,789
<p>See <a href="http://docs.python.org/library/inspect.html#inspect.getmembers"><code>inspect.getmembers(object[, predicate])</code></a>.</p> <blockquote> <p>Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.</p> </blockquote> <pre><code>&gt;&gt;&gt; [name for name,thing in inspect.getmembers([])] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] &gt;&gt;&gt; </code></pre>
54
2009-08-09T17:23:08Z
[ "python", "reflection", "properties" ]
How to enumerate an object's properties in Python?
1,251,692
<p>I C# we do it through reflection. In Javascript it is simple as:</p> <pre><code>for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; </code></pre> <p>How to do it in Python?</p>
66
2009-08-09T16:33:02Z
17,024,180
<p>georg scholly shorter version </p> <pre><code>print vars(theObject) </code></pre>
6
2013-06-10T12:44:16Z
[ "python", "reflection", "properties" ]
Is it possible to update an entry on Google App Engine datastore through the object's dictionary?
1,252,092
<p>I tried the following code and it didn't work:</p> <pre><code>class SourceUpdate(webapp.RequestHandler): def post(self): id = int(self.request.get('id')) source = Source.get_by_id(id) for property in self.request.arguments(): if property != 'id': source.__dict__[property] = self.request.get(property) source.put() self.redirect('/source') </code></pre> <p>I am posting all the necessary properties but the entry isn't updated, and no error is shown. How to fix it?</p> <p>BTW</p> <pre><code>class Source(db.Model): #some string properties </code></pre>
0
2009-08-09T19:51:03Z
1,252,100
<p>You're bypassing the <code>__setattr__</code>-like functionality that the models' metaclass (<code>type(type(source))</code>) is normally using to deal with attribute-setting properly. Change your inner loop to:</p> <pre><code>for property in self.request.arguments(): if property != 'id': setattr(source, property, self.request.get(property)) </code></pre> <p>and everything should work (if all the types of properties can be properly set from a string, since that's what you'll get from <code>request.get</code>).</p>
2
2009-08-09T19:55:12Z
[ "python", "google-app-engine", "gae-datastore" ]
Is it possible to update an entry on Google App Engine datastore through the object's dictionary?
1,252,092
<p>I tried the following code and it didn't work:</p> <pre><code>class SourceUpdate(webapp.RequestHandler): def post(self): id = int(self.request.get('id')) source = Source.get_by_id(id) for property in self.request.arguments(): if property != 'id': source.__dict__[property] = self.request.get(property) source.put() self.redirect('/source') </code></pre> <p>I am posting all the necessary properties but the entry isn't updated, and no error is shown. How to fix it?</p> <p>BTW</p> <pre><code>class Source(db.Model): #some string properties </code></pre>
0
2009-08-09T19:51:03Z
1,253,590
<p>Instead of directly setting model values from the request, you might want to look into using Django forms. They're bundled with App Engine, and facilitate validating form data and storing it in the datastore, as well as generating the form HTML. There's an article on how to use them with the App Engine datastore <a href="http://code.google.com/appengine/articles/djangoforms.html" rel="nofollow">here</a>.</p> <p>Also, don't forget that making changes based on a GET request is almost always a bad idea, and leads to XSRF vulnerabilities and other problems!</p>
2
2009-08-10T07:51:09Z
[ "python", "google-app-engine", "gae-datastore" ]
Printing Python version in output
1,252,163
<p>How can I print version number for the current Python installation in the output? </p>
151
2009-08-09T20:15:39Z
1,252,164
<p>Try</p> <pre><code>import sys print(sys.version) </code></pre> <p>This prints the full version information string. If you only want the python version number, then <a href="http://stackoverflow.com/questions/1252163/printing-python-version-in-output/1252175#1252175">Bastien Léonard's solution</a> is the best. You might want to examine the full string and see if you need it or portions of it.</p>
189
2009-08-09T20:16:47Z
[ "python" ]
Printing Python version in output
1,252,163
<p>How can I print version number for the current Python installation in the output? </p>
151
2009-08-09T20:15:39Z
1,252,165
<pre><code>import platform print(platform.python_version()) </code></pre> <p>or</p> <pre><code>import sys print("The Python version is %s.%s.%s" % sys.version_info[:3]) </code></pre> <p>Edit: I had totally missed the platform.python_version() medthod.</p>
21
2009-08-09T20:17:32Z
[ "python" ]
Printing Python version in output
1,252,163
<p>How can I print version number for the current Python installation in the output? </p>
151
2009-08-09T20:15:39Z
1,252,175
<pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; platform.python_version() '2.6.2' </code></pre>
73
2009-08-09T20:21:00Z
[ "python" ]
Printing Python version in output
1,252,163
<p>How can I print version number for the current Python installation in the output? </p>
151
2009-08-09T20:15:39Z
11,734,305
<p>Try </p> <pre><code>python --version </code></pre> <p>or</p> <pre><code>python -V </code></pre> <p>This will return a current python version in terminal.</p>
20
2012-07-31T06:24:33Z
[ "python" ]
Printing Python version in output
1,252,163
<p>How can I print version number for the current Python installation in the output? </p>
151
2009-08-09T20:15:39Z
17,145,598
<pre><code>import sys </code></pre> <p>expanded version </p> <pre><code>sys.version_info sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0) </code></pre> <p>specific</p> <pre><code>maj_ver = sys.version_info.major repr(maj_ver) '3' </code></pre> <p>or </p> <pre><code>print(sys.version_info.major) '3' </code></pre> <p>or</p> <pre><code>version = ".".join(map(str, sys.version_info[:3])) print(version) '3.2.2' </code></pre>
10
2013-06-17T10:42:34Z
[ "python" ]
How to check null value for UserProperty in Google App Engine
1,252,196
<p>In Google App Engine, datastore modelling, I would like to ask how can I check for null value of a property with class UserProperty? for example: I have this code:</p> <pre><code>class Entry(db.Model): title = db.StringProperty() description = db.StringProperty() author = db.UserProperty() editor = db.UserProperty() creationdate = db.DateTimeProperty() </code></pre> <p>When I want to check those entries that have the editor is not null, I can not use this kind of GqlQuery</p> <pre><code>query = db.GqlQuery("SELECT * FROM Entry " + "WHERE editor IS NOT NULL" + "ORDER BY creationdate DESC") entries = query.fetch(5) </code></pre> <p>I am wondering if there is any method for checking the existence of a variable with UserProperty? Thank you!</p>
5
2009-08-09T20:29:00Z
1,252,322
<pre><code>query = db.GqlQuery("SELECT * FROM Entry WHERE editor &gt; :1",None) </code></pre> <p>However, you can't <code>ORDER BY</code> one column <em>and</em> have an inequality condition on another column: that's a well-known GAE limitation and has nothing to do with the property being a UserProperty nor with the inequality check you're doing being with None.</p> <p><strong>Edit</strong>: I had a != before, but as @Nick pointed out, anything that's != None is > None, and > is about twice as fast on GAE (since != is synthesized by union of &lt; and >), so using > here is a worthwhile optimization.</p>
13
2009-08-09T21:21:05Z
[ "python", "google-app-engine", "gae-datastore" ]
PIL Image.resize() not resizing the picture
1,252,218
<p>I have some strange problem with PIL not resizing the image.</p> <pre><code>def handle_uploaded_image(i, u): # resize image from PIL import Image img = Image.open(i) if img.mode not in ('L', 'RGB'): img = img.convert('RGB') width, height = img.size if width == height: img.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS) elif width &gt; height: ratio = floor(width / height) newwidth = ratio * 150 newwidthhalf = floor(newwidth / 2) img.resize((newwidth, 150), Image.ANTIALIAS) box = 1 img.crop((newwidthhalf, 0, 150, 150)) elif height &gt; width: ratio = floor(height / width) newheight = ratio * 150 newheighthalf = floor(newheight / 2) img.resize((150, newheight), image.ANTIALIAS) box = 1 img.crop((0, newheighthalf, 150, 150)) path = '/'.join([settings.MEDIA_ROOT, 'users', u.username, 'mugshotv2.jpg']) img.save(path, format='JPEG') </code></pre> <p>This code runs without any errors and produces me image named mugshotv2.jpg in correct folder, but it does not resize it. It does something to it, because the size of the picture drops from 120 kb to 20 kb, but the dimensions remain the same. </p> <p>Perhaps you can also suggest way to crop images into squares with less code. I kinda thought that Image.thumbnail does it, but what it did was that it scaled my image to 150 px by its width, leaving height 100px.</p> <p>Alan.</p>
19
2009-08-09T20:36:35Z
1,252,229
<p><code>resize()</code> returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:</p> <pre><code>img = img.resize((150, newheight), image.ANTIALIAS) </code></pre> <p><a href="http://effbot.org/imagingbook/image.htm">source</a></p> <p>I think what you are looking for is the ImageOps.fit function. From PIL <a href="http://effbot.org/imagingbook/imageops.htm">docs</a>:</p> <blockquote> <p>ImageOps.fit(image, size, method, bleed, centering) => image</p> <p>Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. The size argument is the requested output size in pixels, given as a (width, height) tuple.</p> </blockquote>
56
2009-08-09T20:39:53Z
[ "python", "django", "resize", "python-imaging-library" ]
Django + Jquery, expanding AJAX div
1,252,275
<p>How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX? </p> <p>Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that. </p> <p>I'm kind of looking for a specific Django version of the solution if anyone has one?</p>
4
2009-08-09T20:58:47Z
1,252,295
<p>Something like this will work</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function loadDiv() { $.get("test.php", function(data){ $('#thediv').html(data); }); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="javascript:loadDiv();"&gt;Load Div&lt;/a&gt; &lt;div id="thediv"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-08-09T21:08:58Z
[ "jquery", "python", "django" ]
Django + Jquery, expanding AJAX div
1,252,275
<p>How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX? </p> <p>Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that. </p> <p>I'm kind of looking for a specific Django version of the solution if anyone has one?</p>
4
2009-08-09T20:58:47Z
1,252,311
<p><a href="http://docs.jquery.com/Ajax/load">jQuery.load</a> does exactly that:</p> <pre><code>$("div#my-container").load("/url/to/content/ #content-id") </code></pre> <p>this fetches the content from <code>/url/to/content/</code>, filters it by <code>#content-id</code> and injects the result into <code>div#my-container</code>.</p> <p>edit: there's really nothing Django-specific about this, since it's all client-side. But if you insist...</p> <p><code>templates/base.html</code></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;My funky example&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt; {% block extrahead %}{% endblock %} &lt;/head&gt; &lt;body&gt; {% block content %}{% endblock %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p><code>templates/page.html</code></p> <pre><code>{% extends "base.html" %} {% block extrahead %} &lt;script type="text/javascript"&gt; $(function(){ $('a.extendable').click(function(){ $(this).after($('&lt;div class="external-content"&gt;&lt;/div&gt;').load($(this).attr('href') + ' #content')); return false; }); }); &lt;/script&gt; {% endblock extrahead %} {% block content %} &lt;p&gt;Hi! &lt;a href="/external/content/a/" class="extendable"&gt;Click here&lt;/a&gt; and wait for something funny to happen!&lt;/p&gt; &lt;p&gt;&lt;a href="/external/content/b/" class="extendable"&gt;This link&lt;/a&gt; is cool, too!&lt;/p&gt; {% endblock content %} </code></pre> <p><code>templates/a.html</code></p> <pre><code>{% extends "base.html" %} {% block content %} &lt;div id="content"&gt;so long and thanks for all the fish&lt;/div&gt; {% endblock %} </code></pre> <p><code>templates/b.html</code></p> <pre><code>{% extends "base.html" %} {% block content %} &lt;div id="content"&gt;Don't panic&lt;/div&gt; {% endblock %} </code></pre> <p><code>urls.py</code></p> <pre><code>from django.conf.urls.defaults import * urlpatterns = patterns('django.views.generic.simple', (r'^$', 'direct_to_template', {'template': 'page.html'}), (r'^external/content/a/$', 'direct_to_template', {'template': 'a.html'}), (r'^external/content/b/$', 'direct_to_template', {'template': 'b.html'}), ) </code></pre> <p>You can download all the code <a href="http://uploading.com/files/ZQ4BPB6J/ajaxy.zip.html">here</a>.</p>
12
2009-08-09T21:13:59Z
[ "jquery", "python", "django" ]
Python and web-tags regex
1,252,316
<p>i have need webpage-content. I need to get some data from it. It looks like:</p> <blockquote> <p>&lt; div class="deg">DATA&lt; /div></p> </blockquote> <p>As i understand, i have to use regex, but i can't choose one.</p> <p>I tried the code below but had no any results. Please, correct me:</p> <pre><code>regexHandler = re.compile('(&lt;div class="deg"&gt;(?P&lt;div class="deg"&gt;.*?)&lt;/div&gt;)') result = regexHandler.search( pageData ) </code></pre>
1
2009-08-09T21:16:30Z
1,252,329
<p>If you want the div tags included in the matched item:</p> <pre><code>regexpHandler = re.compile('(&lt;div class="deg"&gt;.*?&lt;/div&gt;)') </code></pre> <p>If you don't want the div tags included, only the DATA portion:</p> <pre><code>regexpHandler = re.compile('&lt;div class="deg"&gt;(.*?)&lt;/div&gt;') </code></pre> <p>Then to run the match and get the result:</p> <pre><code>result = regexHandler.search( pageData ) matchedText = result.groups()[0] </code></pre>
3
2009-08-09T21:25:09Z
[ "python", "regex" ]
Python and web-tags regex
1,252,316
<p>i have need webpage-content. I need to get some data from it. It looks like:</p> <blockquote> <p>&lt; div class="deg">DATA&lt; /div></p> </blockquote> <p>As i understand, i have to use regex, but i can't choose one.</p> <p>I tried the code below but had no any results. Please, correct me:</p> <pre><code>regexHandler = re.compile('(&lt;div class="deg"&gt;(?P&lt;div class="deg"&gt;.*?)&lt;/div&gt;)') result = regexHandler.search( pageData ) </code></pre>
1
2009-08-09T21:16:30Z
1,252,331
<p>I suggest using a good HTML parser (such as <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> -- but for your purposes, i.e. with well-formed HTML as input, the ones that come with the Python standard library, such as <a href="http://docs.python.org/library/htmlparser.html">HTMLParser</a>, should also work well) rather than raw REs to parse HTML.</p> <p>If you want to persist with the raw RE approach, the pattern:</p> <pre><code>r'&lt;div class="deg"&gt;([^&lt;]*)&lt;/div&gt;' </code></pre> <p>looks like the simplest way to get the string 'DATA' out of the string '<code>&lt;div class="deg"&gt;DATA&lt;/div&gt;</code>' -- assuming that's what you're after. You may need to add one or more <code>\s*</code> in spots where you need to tolerate optional whitespace.</p>
6
2009-08-09T21:26:14Z
[ "python", "regex" ]
Python and web-tags regex
1,252,316
<p>i have need webpage-content. I need to get some data from it. It looks like:</p> <blockquote> <p>&lt; div class="deg">DATA&lt; /div></p> </blockquote> <p>As i understand, i have to use regex, but i can't choose one.</p> <p>I tried the code below but had no any results. Please, correct me:</p> <pre><code>regexHandler = re.compile('(&lt;div class="deg"&gt;(?P&lt;div class="deg"&gt;.*?)&lt;/div&gt;)') result = regexHandler.search( pageData ) </code></pre>
1
2009-08-09T21:16:30Z
1,253,254
<p>you can use simple string functions in Python, no need for regex</p> <pre><code>mystr = """&lt; div class="deg"&gt;DATA&lt; /div&gt;""" if "div" in mystr and "class" in mystr and "deg" in mystr: s = mystr.split("&gt;") for n,item in enumerate(s): if "deg" in item: print s[n+1][:s[n+1].index("&lt;")] </code></pre> <p>my approach, get something to split on. eg in the above, i split on ">". Then go through the splitted items, check for "deg", and get the item after it, since "deg" appears before the data you want to get. of course, this is not the only approach. </p>
0
2009-08-10T05:40:46Z
[ "python", "regex" ]
Python and web-tags regex
1,252,316
<p>i have need webpage-content. I need to get some data from it. It looks like:</p> <blockquote> <p>&lt; div class="deg">DATA&lt; /div></p> </blockquote> <p>As i understand, i have to use regex, but i can't choose one.</p> <p>I tried the code below but had no any results. Please, correct me:</p> <pre><code>regexHandler = re.compile('(&lt;div class="deg"&gt;(?P&lt;div class="deg"&gt;.*?)&lt;/div&gt;)') result = regexHandler.search( pageData ) </code></pre>
1
2009-08-09T21:16:30Z
1,254,768
<p>While it is ok to use rexex for quick and dirty html processing a much better and cleaner way is to use a html parser like <a href="http://codespeak.net/lxml" rel="nofollow">lxml.html</a> and to query the parsed tree with <a href="http://codespeak.net/lxml/xpathxslt.html" rel="nofollow">XPath</a> or <a href="http://codespeak.net/lxml/cssselect.html" rel="nofollow">CSS Selectors</a>.</p> <pre><code>html = """&lt;html&gt;&lt;body&gt;&lt;div class="deg"&gt;DATA1&lt;/div&gt;&lt;div class="deg"&gt;DATA2&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;""" import lxml.html page = lxml.html.fromstring(html) #page = lxml.html.parse(url) for element in page.findall('.//div[@class="deg"]'): print element.text #using css selectors from lxml.cssselect import CSSSelector sel = CSSSelector("div.deg") for element in sel(page): print element.text </code></pre>
0
2009-08-10T13:06:44Z
[ "python", "regex" ]
Is there an object unique identifier in Python
1,252,357
<p>This would be similar to the java.lang.Object.hashcode() method.</p> <p>I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. </p>
31
2009-08-09T21:40:30Z
1,252,364
<pre><code>id(x) </code></pre> <p>will do the trick for you. But I'm curious, what's wrong about the set of objects (which does combine objects by value)? </p> <p>For your particular problem I would probably keep the set of ids or of wrapper objects. A wrapper object will contain one reference and compare by <code>x==y</code> &lt;==> <code>x.ref is y.ref</code>. </p> <p>It's also worth noting that Python objects have a <code>hash</code> function as well. This function is necessary to put an object into a set or dictionary. It is supposed to sometimes collide for different objects, though good implementations of <code>hash</code> try to make it less likely.</p>
49
2009-08-09T21:42:32Z
[ "python" ]
Is there an object unique identifier in Python
1,252,357
<p>This would be similar to the java.lang.Object.hashcode() method.</p> <p>I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. </p>
31
2009-08-09T21:40:30Z
1,252,369
<p>That's what "<code>is</code>" is for.</p> <p>Instead of testing "<code>if a == b</code>", which tests for the same value, </p> <p>test "<code>if a is b</code>", which will test for the same identifier.</p>
12
2009-08-09T21:43:35Z
[ "python" ]
Is there an object unique identifier in Python
1,252,357
<p>This would be similar to the java.lang.Object.hashcode() method.</p> <p>I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. </p>
31
2009-08-09T21:40:30Z
1,252,386
<p>As ilya n mentions, id(x) produces a unique identifier for an object.</p> <p>But your question is confusing, since Java's hashCode method doesn't give a unique identifier. Java's hashCode works like most hash functions: it always returns the same value for the same object, two objects that are equal always get equal codes, and unequal hash values imply unequal hash codes. In particular, two different and unequal objects can get the same value. </p> <p>This is confusing because cryptographic hash functions are quite different from this, and more like (though not exactly) the "unique id" that you asked for.</p> <p>The Python equivalent of Java's hashCode method is hash(x).</p>
2
2009-08-09T21:48:00Z
[ "python" ]
Is there an object unique identifier in Python
1,252,357
<p>This would be similar to the java.lang.Object.hashcode() method.</p> <p>I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. </p>
31
2009-08-09T21:40:30Z
27,936,874
<p>You don't have to compare objects before placing them in a set. set() semantics already takes care of this. </p> <pre><code> class A(object): a = 10 b = 20 def __hash__(self): return hash((self.a, self.b)) a1 = A() a2 = A() a3 = A() a4 = a1 s = set([a1,a2,a3,a4]) s =&gt; set([&lt;__main__.A object at 0x222a8c&gt;, &lt;__main__.A object at 0x220684&gt;, &lt;__main__.A object at 0x22045c&gt;]) </code></pre> <p>Note: You really don't have to override <strong>hash</strong> to prove this behaviour :-)</p>
-1
2015-01-14T06:17:13Z
[ "python" ]
sort dictionary by another dictionary
1,252,481
<p>I've been having a problem with making sorted lists from dictionaries. I have this list</p> <pre><code>list = [ d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'}, d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height':'6.0', 'item_width':'12.4', 'item_depth':'3.0' 'texture_file': 'blue.jpg'}, etc. ] </code></pre> <p>I'm trying to loop through the list and</p> <ul> <li>from each dictionary create a new list containing items from the dictionary. (<strong>It varies which items and how many items need to be appended to the list as the user makes that choice</strong>)</li> <li>sort the list</li> </ul> <p>When I say sort, I imagine creating a new dictionary like this</p> <pre><code>order = { 'file_name': 0, 'item_name': 1, 'item_height': 2, 'item_width': 3, 'item_depth': 4, 'texture_file': 5 } </code></pre> <p>and it sorts each list by the values in the order dictionary. </p> <p><hr /></p> <p>During one execution of the script all the lists might look like this</p> <pre><code>['thisfile.flt', 'box', '8.7', '10.5', '2.2'] ['thatfile.flt', 'teapot', '6.0', '12.4', '3.0'] </code></pre> <p>on the other hand they might look like this</p> <pre><code>['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg'] ['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg'] </code></pre> <p>I guess my question is how would I go about making a list from specific values from a dictionary and sorting it by the values in another dictionary which has the same keys as the first dictionary?</p> <p>Appreciate any ideas/suggestions, sorry for noobish behaviour - I am still learning python/programming</p>
2
2009-08-09T22:26:25Z
1,252,500
<p>The first code box has invalid Python syntax (I suspect the <code>d =</code> parts are extraneous...?) as well as unwisely trampling on the built-in name <code>list</code>.</p> <p>Anyway, given for example:</p> <pre><code>d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'} order = { 'file_name': 0, 'item_name': 1, 'item_height': 2, 'item_width': 3, 'item_depth': 4, 'texture_file': 5 } </code></pre> <p>one nifty way to get the desired result <code>['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg']</code> would be:</p> <pre><code>def doit(d, order): return [d[k] for k in sorted(order, key=order.get)] </code></pre>
7
2009-08-09T22:34:31Z
[ "python", "sorting", "dictionary" ]
Which path module or class do Python folks use instead of os.path?
1,252,639
<p>Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using <code>os.path</code> for joining and splitting paths? Have you used:</p> <ul> <li><a href="http://wiki.python.org/moin/PathModule" rel="nofollow">Jason's path module</a> (updated for PEP 355)</li> <li><a href="http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html" rel="nofollow">Mike Orr's Unipath</a>, basically a more modern version of the above</li> <li><a href="http://wiki.python.org/moin/AlternativePathModule" rel="nofollow">Noam Raphael's alternative path module</a> that subclasses tuple instead of str</li> </ul> <p>I know Jason's path module was made into <a href="http://www.python.org/dev/peps/pep-0355/" rel="nofollow">PEP 355</a> and rejected by the BDFL. This seems like it was mainly because it tried to do everything in one class.</p> <p>Our use case is mainly to simplify joining and splitting components of paths, so we'd be quite happy if such a path class only implemented the split/join type of operations. Who wouldn't want to do this:</p> <pre><code>path(build_dir, path(source_file).name) </code></pre> <p>or this:</p> <pre><code>build_dir / path(source_file).name </code></pre> <p>instead of this:</p> <pre><code>os.path.join(build_dir, os.path.basename(source_file)) </code></pre>
5
2009-08-10T00:03:40Z
1,252,644
<p>I can pick up a Python program and interpret the current standard method without hesitation - it's explicit and there's no ambiguity:</p> <pre><code>os.path.join(build_dir, os.path.basename(source_file)) </code></pre> <p>Python's dynamic typing makes the first method rather difficult to comprehend when reading:</p> <pre><code>build_dir / path(source_file).name </code></pre> <p>Plus it's not common to divide strings, which brings up more confusion. How do I know that those two aren't integers? Or floats? You won't get a TypeError at runtime if both end up as non-string types.</p> <p>Finally,</p> <pre><code>path(build_dir, path(source_file).name) </code></pre> <p>How is that any better than the os.path method?</p> <p>While they may "simplify" coding (ie, make it easier to write), you're going to run into strife if someone else who is unfamiliar with the alternative modules needs to maintain the code.</p> <p>So I guess my answer is: I don't use an alternative path module. os.path has everything I need already, and it's interface isn't half bad.</p>
11
2009-08-10T00:10:48Z
[ "python", "path" ]
Which path module or class do Python folks use instead of os.path?
1,252,639
<p>Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using <code>os.path</code> for joining and splitting paths? Have you used:</p> <ul> <li><a href="http://wiki.python.org/moin/PathModule" rel="nofollow">Jason's path module</a> (updated for PEP 355)</li> <li><a href="http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html" rel="nofollow">Mike Orr's Unipath</a>, basically a more modern version of the above</li> <li><a href="http://wiki.python.org/moin/AlternativePathModule" rel="nofollow">Noam Raphael's alternative path module</a> that subclasses tuple instead of str</li> </ul> <p>I know Jason's path module was made into <a href="http://www.python.org/dev/peps/pep-0355/" rel="nofollow">PEP 355</a> and rejected by the BDFL. This seems like it was mainly because it tried to do everything in one class.</p> <p>Our use case is mainly to simplify joining and splitting components of paths, so we'd be quite happy if such a path class only implemented the split/join type of operations. Who wouldn't want to do this:</p> <pre><code>path(build_dir, path(source_file).name) </code></pre> <p>or this:</p> <pre><code>build_dir / path(source_file).name </code></pre> <p>instead of this:</p> <pre><code>os.path.join(build_dir, os.path.basename(source_file)) </code></pre>
5
2009-08-10T00:03:40Z
1,252,978
<p>Dividing strings to join paths may seem like a "neat trick" but it's precisely that kind of thing that Python programmers like to avoid (and btw, programmers in most other langauges.) The os.path module is widely used and easily understood by all. Doing funky things with overloaded operators on the other hand is confusing, it impairs the readability of your code, which is meant to be one of Python's strong points.</p> <p>C++ programmers, on the other hand, love that kind of thing. Perhaps that's one of the reasons C++ code can be so difficult to read.</p>
-1
2009-08-10T03:17:49Z
[ "python", "path" ]
Which path module or class do Python folks use instead of os.path?
1,252,639
<p>Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using <code>os.path</code> for joining and splitting paths? Have you used:</p> <ul> <li><a href="http://wiki.python.org/moin/PathModule" rel="nofollow">Jason's path module</a> (updated for PEP 355)</li> <li><a href="http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html" rel="nofollow">Mike Orr's Unipath</a>, basically a more modern version of the above</li> <li><a href="http://wiki.python.org/moin/AlternativePathModule" rel="nofollow">Noam Raphael's alternative path module</a> that subclasses tuple instead of str</li> </ul> <p>I know Jason's path module was made into <a href="http://www.python.org/dev/peps/pep-0355/" rel="nofollow">PEP 355</a> and rejected by the BDFL. This seems like it was mainly because it tried to do everything in one class.</p> <p>Our use case is mainly to simplify joining and splitting components of paths, so we'd be quite happy if such a path class only implemented the split/join type of operations. Who wouldn't want to do this:</p> <pre><code>path(build_dir, path(source_file).name) </code></pre> <p>or this:</p> <pre><code>build_dir / path(source_file).name </code></pre> <p>instead of this:</p> <pre><code>os.path.join(build_dir, os.path.basename(source_file)) </code></pre>
5
2009-08-10T00:03:40Z
5,792,853
<p>A simple but useful trick is this:</p> <blockquote> <p>import os</p> <p>Path = os.path.join</p> </blockquote> <p>Then, instead of this:</p> <blockquote> <p>os.path.join(build_dir, os.path.basename(source_file))</p> </blockquote> <p>You can do this:</p> <blockquote> <p>Path(build_dir, Path(source_file))</p> </blockquote>
1
2011-04-26T15:44:47Z
[ "python", "path" ]