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 list |
|---|---|---|---|---|---|---|---|---|---|
How can I create a regular expression in Python? | 1,895,026 | <p>I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format:</p>
<pre><code>word_*_word.word
</code></pre>
<p>So for example, I would like the python code every match. Sample results would be:</p>
<pre><code>program1_0.0-1_log.build
program2_0.1-3_log.bu... | 0 | 2009-12-12T23:21:02Z | 1,895,055 | <p>Looks like you want to use a pattern such as <code>r'\w+_.*_\w+\.\w+'</code> -- assuming that <code>*</code> you have does stand for "zero or more totally arbitrary characters" (if not, then the <code>.*</code> part in the middle needs to be changed accordingly). Once you have the right pattern (depending exactly o... | 2 | 2009-12-12T23:33:42Z | [
"python",
"regex"
] |
How can I create a regular expression in Python? | 1,895,026 | <p>I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format:</p>
<pre><code>word_*_word.word
</code></pre>
<p>So for example, I would like the python code every match. Sample results would be:</p>
<pre><code>program1_0.0-1_log.build
program2_0.1-3_log.bu... | 0 | 2009-12-12T23:21:02Z | 1,895,722 | <p>i don't understand why you would need a regex here.
If the strings you want ends with ".build", you can do this for example</p>
<pre><code>s="blah blah program1_0.0-1_log.build blah blah"
for item in s.split():
if item.endswith(".build"):
print item
</code></pre>
<p>and that's it. If you want to d... | 0 | 2009-12-13T06:15:28Z | [
"python",
"regex"
] |
Persistent MySQL connections in Python | 1,895,089 | <p>PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections.</p>
<p>Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI.</p>
<p>Thank you!</p>
| 2 | 2009-12-12T23:49:34Z | 1,895,111 | <p>If you're using FastCGI, there's no need for "persistent connections", because if you create a connection it is by default persistent, since FastCGI python isn't request based, but constantly running.</p>
<p>This is how FastCGI works in python, to put it short:</p>
<pre><code>1. Run startup code
2. Run request fun... | 5 | 2009-12-12T23:59:25Z | [
"python",
"mysql",
"web-services"
] |
Persistent MySQL connections in Python | 1,895,089 | <p>PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections.</p>
<p>Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI.</p>
<p>Thank you!</p>
| 2 | 2009-12-12T23:49:34Z | 1,895,731 | <p>Note: Persistent connections can have a very negative effect on your system performance. If you have a large number of web server processes all holding persistent connections to your DB server you may exhaust the DB server's limit on connections. This is one of those areas where you need to test it under heavy simul... | 0 | 2009-12-13T06:21:26Z | [
"python",
"mysql",
"web-services"
] |
Python tempfile module and threads aren't playing nice; what am I doing wrong? | 1,895,350 | <p>I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)</p>
<p>Yet if I sort of replicate what the tempfile module is doing (not all... | 6 | 2009-12-13T02:03:24Z | 1,895,407 | <p>I think your answer can be found <a href="http://www.logilab.org/blogentry/17873" rel="nofollow">here</a>. You have to explicitly <code>os.close()</code> the file descriptor given as the first part of the tuple that <code>mkstemp</code> gives you.</p>
<p>Edit: no, the OP is already doing what is supposed to be done... | 3 | 2009-12-13T02:49:11Z | [
"python",
"multithreading",
"temporary-files"
] |
Python tempfile module and threads aren't playing nice; what am I doing wrong? | 1,895,350 | <p>I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)</p>
<p>Yet if I sort of replicate what the tempfile module is doing (not all... | 6 | 2009-12-13T02:03:24Z | 1,895,676 | <p>I am unable to reproduce the problem with (Apple's own build of) Python 2.5.1 on Mac OS X 10.5.9 -- runs to completion just fine!</p>
<p>I've tried both on a Macbook Pro, i.e., an Intel processor, and an old PowerMac, i.e., a PPC processor.</p>
<p>So I can only imagine there must have been a bug in 10.5.8 which I ... | 4 | 2009-12-13T05:53:26Z | [
"python",
"multithreading",
"temporary-files"
] |
Python tempfile module and threads aren't playing nice; what am I doing wrong? | 1,895,350 | <p>I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)</p>
<p>Yet if I sort of replicate what the tempfile module is doing (not all... | 6 | 2009-12-13T02:03:24Z | 1,895,928 | <p>I just tested your code on my Ubuntu Linux computer here, and it worked perfectly for me.</p>
<p>I have one suggestion for you to try. I don't know that it will help but it can't hurt. Rewrite your code to use with:</p>
<pre><code>from __future__ import with_statement
def worker_tempfile():
tempfd, tempfn =... | 1 | 2009-12-13T08:35:12Z | [
"python",
"multithreading",
"temporary-files"
] |
Python tempfile module and threads aren't playing nice; what am I doing wrong? | 1,895,350 | <p>I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)</p>
<p>Yet if I sort of replicate what the tempfile module is doing (not all... | 6 | 2009-12-13T02:03:24Z | 1,898,040 | <p>Why do you think the error is not genuine? You are launching 10000 threads, each opening a file, while the maximum number of open files is typically 1024 under Unix systems.</p>
<p>First try to keep manually track of the number of files currently open and check whether it bumps past the OS limit.</p>
| 1 | 2009-12-13T22:28:52Z | [
"python",
"multithreading",
"temporary-files"
] |
Python tempfile module and threads aren't playing nice; what am I doing wrong? | 1,895,350 | <p>I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)</p>
<p>Yet if I sort of replicate what the tempfile module is doing (not all... | 6 | 2009-12-13T02:03:24Z | 1,904,529 | <p>Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tes... | 0 | 2009-12-15T00:36:07Z | [
"python",
"multithreading",
"temporary-files"
] |
Emacs: Pymacs not loading ropemacs with Carbon Emacs | 1,895,459 | <p>I'm attempting to use Pymacs with rope/ropemacs for flymake syntax checking as described here:
<a href="http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/" rel="nofollow">http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/</a></p>
<p>When I start ... | 3 | 2009-12-13T03:18:26Z | 1,895,588 | <p>Chances are it is a path problem. When you start an emacs from the terminal, your <code>PATH</code> environment variable presumably includes the MacPorts bin directory <code>/opt/local/bin</code> because presumably you modified one of your shell profiles, probably <code>.bash_profile</code>, to include that directo... | 1 | 2009-12-13T04:51:24Z | [
"python",
"emacs",
"flymake",
"ropemacs",
"pymacs"
] |
How to pass an instance's reference in a method? | 1,895,501 | <p>I have the following Bird definition:</p>
<pre><code>class Bird:
def __init__(self, swarm, position = None):
if (swarm == None):
raise ValueError("swarm variable should not be None!")
if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
raise TypeError("swarm v... | 1 | 2009-12-13T03:57:19Z | 1,895,511 | <p>use:</p>
<pre><code>assert isinstance(swarm, ParticleSwarmOptimization)
</code></pre>
<p>The culture of Python is to not do these sorts of defensive checks, instead to simply use the variable. If it is of the wrong type, an exception will eventually be raised.</p>
| 4 | 2009-12-13T04:01:47Z | [
"python"
] |
How to pass an instance's reference in a method? | 1,895,501 | <p>I have the following Bird definition:</p>
<pre><code>class Bird:
def __init__(self, swarm, position = None):
if (swarm == None):
raise ValueError("swarm variable should not be None!")
if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
raise TypeError("swarm v... | 1 | 2009-12-13T03:57:19Z | 1,895,512 | <p>try using </p>
<pre><code>isinstance
</code></pre>
<p>instead.</p>
| 0 | 2009-12-13T04:02:35Z | [
"python"
] |
How to pass an instance's reference in a method? | 1,895,501 | <p>I have the following Bird definition:</p>
<pre><code>class Bird:
def __init__(self, swarm, position = None):
if (swarm == None):
raise ValueError("swarm variable should not be None!")
if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
raise TypeError("swarm v... | 1 | 2009-12-13T03:57:19Z | 1,895,527 | <p>Other people have mentioned the correct way to do this, however the reason you get that error is because you are using an old style class. To get a new-style class make your classes subclass object.</p>
| 4 | 2009-12-13T04:15:18Z | [
"python"
] |
For Loop, os.listdir() not working correctly | 1,895,538 | <p>I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.</p>
<pre><code>yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdi... | 1 | 2009-12-13T04:26:29Z | 1,895,573 | <p>In the <code>for year in yearList</code> loop you change to the year's subdirectory, but probably never leave it again. So in the first iteration you enter the "2005" subdirectory and in the second iteration you are still in that subdirectory. Then you get the error that there is no "2006" directory (in the current ... | 1 | 2009-12-13T04:47:05Z | [
"python",
"directory"
] |
For Loop, os.listdir() not working correctly | 1,895,538 | <p>I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.</p>
<pre><code>yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdi... | 1 | 2009-12-13T04:26:29Z | 1,895,583 | <p>After you do a chdir, the current directory changes to the subdirectory, so you can't move to another subdirectory (a sibling of the first one) later using just its name. Using an absolute path will fix your problem.</p>
<p>Try</p>
<pre><code>os.chdir(os.path.join(driveLetter, clientName, year))
</code></pre>
<p>... | 0 | 2009-12-13T04:49:26Z | [
"python",
"directory"
] |
For Loop, os.listdir() not working correctly | 1,895,538 | <p>I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.</p>
<pre><code>yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdi... | 1 | 2009-12-13T04:26:29Z | 1,895,586 | <p>I haven't tested this on windows, but <code>os.listdir(...)</code> returns a list containing the names of every item in the given directory (which, in your case, is folders). Keep in mind that this is not an absolute path, so when you switch into the subdirectory you can't just <code>os.chdir()</code> with the next... | 0 | 2009-12-13T04:51:17Z | [
"python",
"directory"
] |
For Loop, os.listdir() not working correctly | 1,895,538 | <p>I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.</p>
<pre><code>yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdi... | 1 | 2009-12-13T04:26:29Z | 1,902,386 | <p>There's a context manager that you can use to temporarily store the cwd in that question:</p>
<p><a href="http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd">How do I write a decorator that restores the cwd?</a></p>
| 0 | 2009-12-14T17:48:01Z | [
"python",
"directory"
] |
String representation of arrays in python | 1,895,539 | <p>Is there anything that performs the following, in python? Or will I have to implement it myself?</p>
<pre><code>array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
</code></pre>
<p>which prints</p>
<pre><code>(0, 1, 2)
</code></pre>
<p>Thanks</p>
| 3 | 2009-12-13T04:26:48Z | 1,895,542 | <p>You're in luck, Python has a function for this purpose exactly. It's called <code>join</code>.</p>
<pre><code>print "(" + ", ".join(array) + ")"
</code></pre>
<p>If you're familiar with PHP, <code>join</code> is similar to <code>implode</code>. The <code>", "</code> above is the element separator, and can be repla... | 4 | 2009-12-13T04:28:36Z | [
"python"
] |
String representation of arrays in python | 1,895,539 | <p>Is there anything that performs the following, in python? Or will I have to implement it myself?</p>
<pre><code>array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
</code></pre>
<p>which prints</p>
<pre><code>(0, 1, 2)
</code></pre>
<p>Thanks</p>
| 3 | 2009-12-13T04:26:48Z | 1,895,543 | <pre><code>SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT = tuple
</code></pre>
| 4 | 2009-12-13T04:29:25Z | [
"python"
] |
String representation of arrays in python | 1,895,539 | <p>Is there anything that performs the following, in python? Or will I have to implement it myself?</p>
<pre><code>array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
</code></pre>
<p>which prints</p>
<pre><code>(0, 1, 2)
</code></pre>
<p>Thanks</p>
| 3 | 2009-12-13T04:26:48Z | 1,895,594 | <pre><code>def SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT (arr):
return str(tuple(arr))
</code></pre>
<p>Replace <code>str</code> with <code>unicode</code> if you need to.</p>
| 5 | 2009-12-13T04:55:39Z | [
"python"
] |
String representation of arrays in python | 1,895,539 | <p>Is there anything that performs the following, in python? Or will I have to implement it myself?</p>
<pre><code>array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
</code></pre>
<p>which prints</p>
<pre><code>(0, 1, 2)
</code></pre>
<p>Thanks</p>
| 3 | 2009-12-13T04:26:48Z | 1,895,705 | <p>If your array's items are specifically integers, <code>str(tuple(array))</code> as suggested in @jboxer's answer will work. For most other types of items, it may be more of a problem, since <code>str(tuple(...))</code> uses <code>repr</code>, <strong>not</strong> <code>str</code> -- that's really needed as a defaul... | 1 | 2009-12-13T06:04:50Z | [
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,619 | <pre><code>randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]
</code></pre>
<p>Sample output, for <code>count=10</code> and assuming that you mean the Standard Library <code>random()</code> function:</p>
<pre><code>[(-0.07, -0.40), (0.39, 0.18), (0.13, 0.29), (-0.11, -0.15),\
(-0.49, 0.42), (-0.2... | 4 | 2009-12-13T05:14:49Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,622 | <p>Try this:</p>
<pre><code>while count > 0:
pattern.append((random() - 0.5, random() - 0.5))
count -= 1
</code></pre>
| 0 | 2009-12-13T05:15:25Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,634 | <p>There should be a way to suppress code analysis errors in PyDev, like this:</p>
<p><a href="http://pydev.org/manual%5Fadv%5Fassistants.html" rel="nofollow">http://pydev.org/manual%5Fadv%5Fassistants.html</a></p>
<p>Also, PyDev will ignore unused variables that begin with an underscore, as shown here:</p>
<p><a hr... | 1 | 2009-12-13T05:25:31Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,698 | <p>Late to the party, but here's a potential idea:</p>
<pre><code>def RandomSample(count):
f = lambda: random() - 0.5
r = range if count < 100 else xrange # or some other number
return [(f(), f()) for _ in r(count)]
</code></pre>
<p>Strictly speaking, this is more or less the same as the other answers,... | 2 | 2009-12-13T06:01:58Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,710 | <p>Just for reference for ignoring variables in PyDev</p>
<p>By default pydev will ignore following variables </p>
<pre><code>['_', 'empty', 'unused', 'dummy']
</code></pre>
<p>You can add more by passing supression parameters</p>
<pre><code>-E, --unusednames ignore unused locals/arguments if name is one of these ... | 18 | 2009-12-13T06:06:44Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,895,712 | <p>How about <a href="http://docs.python.org/library/itertools.html#itertools.repeat" rel="nofollow">itertools.repeat</a>:</p>
<pre><code>import itertools
count = 5
def make_pat():
return (random() - 0.5, random() - 0.5)
list(x() for x in itertools.repeat(make_pat, count))
</code></pre>
<p><strong>Sample output:<... | 5 | 2009-12-13T06:06:55Z | [
"eclipse",
"for-loop",
"python"
] |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | <p>This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.</p>
<p>The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev</p>
<pre><code>def RandomSample(count): ... | 8 | 2009-12-13T05:11:46Z | 1,896,444 | <pre><code>import itertools, random
def RandomSample2D(npoints, get_random=lambda: random.uniform(-.5, .5)):
return ((r(), r()) for r in itertools.repeat(get_random, npoints))
</code></pre>
<ul>
<li>uses <code>random.uniform()</code> explicitly</li>
<li>returns an iterator instead of list</li>
</ul>
| 0 | 2009-12-13T13:01:33Z | [
"eclipse",
"for-loop",
"python"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 1,895,674 | <p>Django's <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="nofollow"><code>{% regroup %}</code></a> template tag might be useful for this. Assuming <code>tags</code> is in the context of your template:</p>
<pre><code>{% regroup tags|dictsort:"count" by count as sorted_tags %}
...
{... | 3 | 2009-12-13T05:52:36Z | [
"python",
"django",
"django-tagging"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 1,898,528 | <p>If you need to pull all the tags anyway, and the limit to the top n is simply a presentation thing, Fragsworth's answer is probably the way to go. If you aren't using the remainder of the tags somewhere else, I'd argue that this is really something that should be happening in the database query...you would want to b... | 1 | 2009-12-14T01:45:40Z | [
"python",
"django",
"django-tagging"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 1,899,366 | <p>If you are using the latest version of django, you could use aggregation. <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation">http://docs.djangoproject.com/en/dev/topics/db/aggregation</a> an example on that page ..</p>
<pre><code>Book.objects.annotate(num_authors=Count('authors')).order_by('num_au... | 5 | 2009-12-14T07:03:27Z | [
"python",
"django",
"django-tagging"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 2,064,688 | <p>I find the following sorting code a bit more readable than the one you wrote. Of course it doesn't remove the source problem stated by abeyer</p>
<pre><code>import operator
tags = Tag.objects.usage_for_model(Post, counts=True)
tags.sort(key=operator.attrgetter('count'), reverse=True)
</code></pre>
| 3 | 2010-01-14T14:22:05Z | [
"python",
"django",
"django-tagging"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 6,028,214 | <p>I use raw sql for this:</p>
<pre><code>trends = Tag.objects.raw("select tagging_tag.id, count(object_id) as counter from tagging_tag left join tagging_taggeditem on tagging_tag.id = tagging_taggeditem.tag_id group by tagging_tag.id order by counter DESC limit 10")
</code></pre>
| 0 | 2011-05-17T08:32:12Z | [
"python",
"django",
"django-tagging"
] |
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?) | 1,895,638 | <p>I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries. </p>
<p>Using the following:</p>
<pre><code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code></pre>
<p>It returns an array (note I'm... | 3 | 2009-12-13T05:31:03Z | 31,307,577 | <p>My approach for getting top tags in Django-Tagging is: </p>
<pre><code>top_tags = Tag.objects.annotate(num=Count('taggit_taggeditem_items')).order_by('-num')
</code></pre>
| 0 | 2015-07-09T03:25:18Z | [
"python",
"django",
"django-tagging"
] |
Python app engine import issues after app is cached | 1,895,744 | <p>I'm using a modified version on juno (<a href="http://github.com/breily/juno/" rel="nofollow">http://github.com/breily/juno/</a>) in appengine. The problem I'm having is I have code like this:</p>
<pre><code>import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name_... | 1 | 2009-12-13T06:27:00Z | 1,897,248 | <p>Is it possible you are reassigning the name pprint somewhere? The only two ways I know of for a module-level name (like what you get from the import statement) to become None is if you either assign it yourself <code>pprint = None</code> or upon interpreter shutdown, when Python's cleanup assigns all module-level n... | 0 | 2009-12-13T18:24:49Z | [
"python",
"google-app-engine",
"caching",
"import"
] |
Python app engine import issues after app is cached | 1,895,744 | <p>I'm using a modified version on juno (<a href="http://github.com/breily/juno/" rel="nofollow">http://github.com/breily/juno/</a>) in appengine. The problem I'm having is I have code like this:</p>
<pre><code>import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name_... | 1 | 2009-12-13T06:27:00Z | 3,463,638 | <p>I would leave it that way. I saw a slideshare that Google put out about App Engine optimization that said you can get better performance by keeping imports inside of the methods, so they are not imported unless necessary.</p>
| 0 | 2010-08-11T23:28:13Z | [
"python",
"google-app-engine",
"caching",
"import"
] |
Imports with Pydev/Eclipse | 1,895,745 | <p>I'm working with the interactive console in eclipse, and reload does not show updated functions in my code. My code was : </p>
<pre><code>def func1():
return 1
def func2():
return 2
</code></pre>
<p>but when I changed it to </p>
<pre><code>def afunc1():
return 1
def func2():
return... | 1 | 2009-12-13T06:28:20Z | 1,895,775 | <p>Turns out, eclipse was not saving the file (or not saving it to the correct location) when I hit ctl-s. To get it to work, I had to right click the file name in the Package Explorer and select open with PyDev and save it under that</p>
| 0 | 2009-12-13T06:48:25Z | [
"python",
"eclipse",
"import",
"pydev",
"reload"
] |
Why does Django say I haven't set DATABASE_ENGINE yet? | 1,895,916 | <p>I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database:</p>
<pre><code>import unittest
from foo.models import ObjectType
class DbTest(unittest.TestCase):
def testDBConnection(self):
object_type = ObjectType()
... | 3 | 2009-12-13T08:20:55Z | 1,896,218 | <p>That's probably because you're running tests directly, i.e. just <code>python testfile.py</code>. This way you effectively bypass all Django mechanisms and use Model classes directly.
The downside is, the DB backend isn't set up automatically (by Django, which loads <code>settings.py</code> and connects to the appro... | 3 | 2009-12-13T11:24:42Z | [
"python",
"django",
"postgresql"
] |
Why does Django say I haven't set DATABASE_ENGINE yet? | 1,895,916 | <p>I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database:</p>
<pre><code>import unittest
from foo.models import ObjectType
class DbTest(unittest.TestCase):
def testDBConnection(self):
object_type = ObjectType()
... | 3 | 2009-12-13T08:20:55Z | 1,896,693 | <p>Your Django settings file needs to have been loaded before you can import your models. If you can't use Django's testing framework, then perhaps you can use this code in your tests:</p>
<pre><code>from django.conf import settings
settings.configure(
DATABASE_ENGINE='postgresql_psycopg2',
DATABASE_NA... | 2 | 2009-12-13T14:40:32Z | [
"python",
"django",
"postgresql"
] |
Why does Django say I haven't set DATABASE_ENGINE yet? | 1,895,916 | <p>I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database:</p>
<pre><code>import unittest
from foo.models import ObjectType
class DbTest(unittest.TestCase):
def testDBConnection(self):
object_type = ObjectType()
... | 3 | 2009-12-13T08:20:55Z | 2,384,672 | <p>You should be able to set the environment variable DJANGO_SETTINGS_MODULE=myapp.settings and have that work for standalone scripts.</p>
<p>in Linux/bash you'd do: export DJANGO_SETTINGS_MODULE=myapp.settings</p>
| 2 | 2010-03-05T05:02:28Z | [
"python",
"django",
"postgresql"
] |
Will this urllib2 python code download the page of the file? | 1,895,949 | <p><strong>urllib2.urlopen(theurl).read()</strong> ...this downloads the file.</p>
<p><strong>urllib2.urlopen(theurl).geturl()</strong>...does this download the file? (how long does it take)</p>
| 0 | 2009-12-13T08:54:20Z | 1,895,956 | <p>From the <a href="http://docs.python.org/library/urllib.html#high-level-interface" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>The geturl() method returns the real
URL of the page. In some cases, the
HTTP server redirects a client to
another URL. The urlopen() function
handles this transparently... | 5 | 2009-12-13T09:00:25Z | [
"python",
"http",
"urllib2"
] |
Will this urllib2 python code download the page of the file? | 1,895,949 | <p><strong>urllib2.urlopen(theurl).read()</strong> ...this downloads the file.</p>
<p><strong>urllib2.urlopen(theurl).geturl()</strong>...does this download the file? (how long does it take)</p>
| 0 | 2009-12-13T08:54:20Z | 1,895,957 | <p>No. geturl() returns the url.</p>
<p>For example; <code>urllib2.urlopen("http://www.python.org").geturl()</code> returns the string '<a href="http://www.python.org" rel="nofollow">http://www.python.org</a>'.</p>
<p>You can find this sort of stuff really easily in the python interactive shell e.g;</p>
<pre><code>... | 1 | 2009-12-13T09:00:54Z | [
"python",
"http",
"urllib2"
] |
Will this urllib2 python code download the page of the file? | 1,895,949 | <p><strong>urllib2.urlopen(theurl).read()</strong> ...this downloads the file.</p>
<p><strong>urllib2.urlopen(theurl).geturl()</strong>...does this download the file? (how long does it take)</p>
| 0 | 2009-12-13T08:54:20Z | 1,895,962 | <p>It does not.
For me, a test on google.com:</p>
<pre><code>x= time.time(); urllib2.urlopen("http://www.google.com").read(); print time.time()-x
0.166881084442
x= time.time(); urllib2.urlopen("http://www.google.com").geturl(); print time.time()-x
0.0772399902344
</code></pre>
| 3 | 2009-12-13T09:02:44Z | [
"python",
"http",
"urllib2"
] |
Will this urllib2 python code download the page of the file? | 1,895,949 | <p><strong>urllib2.urlopen(theurl).read()</strong> ...this downloads the file.</p>
<p><strong>urllib2.urlopen(theurl).geturl()</strong>...does this download the file? (how long does it take)</p>
| 0 | 2009-12-13T08:54:20Z | 1,895,965 | <p>Tested with <a href="http://www.wireshark.org/" rel="nofollow">Wireshark</a> and Python 2.5: <code>urllib2.urlopen(theurl).geturl()</code> downloads <em>some</em> of the body. It issues a <code>GET</code>, reads the header and a couple of K of the body, and then stops.</p>
| 4 | 2009-12-13T09:04:12Z | [
"python",
"http",
"urllib2"
] |
Will this urllib2 python code download the page of the file? | 1,895,949 | <p><strong>urllib2.urlopen(theurl).read()</strong> ...this downloads the file.</p>
<p><strong>urllib2.urlopen(theurl).geturl()</strong>...does this download the file? (how long does it take)</p>
| 0 | 2009-12-13T08:54:20Z | 1,896,443 | <p>urllib2.urlopen() returns a file like object, so that when using urlopen() you are actually download the document, and it's loaded into your machine's memory, you can use file functions to read write your file, like so...</p>
<p>#to store python.org into your local file d:\python.org.html</p>
<pre><code>from urlli... | 1 | 2009-12-13T13:01:01Z | [
"python",
"http",
"urllib2"
] |
Using cProfile results with KCacheGrind | 1,896,032 | <p>I'm using cProfile to profile my Python program. Based upon <a href="http://blip.tv/file/1957086/">this talk</a> I was under the impression that KCacheGrind could parse and display the output from cProfile.</p>
<p>However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the... | 42 | 2009-12-13T09:43:00Z | 1,896,129 | <p>It can be done using an external module called <a href="http://www.gnome.org/~johan/lsprofcalltree.py">lscallproftree</a> </p>
<p>This article explains how: <a href="http://tools.cherrypy.org/wiki/Cachegrind">CherryPy - CacheGrind</a></p>
<p>With my resulting code looking like so:</p>
<pre><code>...
if profile:
... | 7 | 2009-12-13T10:40:34Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] |
Using cProfile results with KCacheGrind | 1,896,032 | <p>I'm using cProfile to profile my Python program. Based upon <a href="http://blip.tv/file/1957086/">this talk</a> I was under the impression that KCacheGrind could parse and display the output from cProfile.</p>
<p>However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the... | 42 | 2009-12-13T09:43:00Z | 1,904,113 | <p>If what you're actually trying to do is see what parts of your code could be optimized for speed, and you can randomly pause it in the debugger, <a href="http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">this method works</a>. It may be surprising, but you don't need ... | 6 | 2009-12-14T22:59:28Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] |
Using cProfile results with KCacheGrind | 1,896,032 | <p>I'm using cProfile to profile my Python program. Based upon <a href="http://blip.tv/file/1957086/">this talk</a> I was under the impression that KCacheGrind could parse and display the output from cProfile.</p>
<p>However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the... | 42 | 2009-12-13T09:43:00Z | 2,534,743 | <p>You could use <a href="http://pypi.python.org/pypi/profilestats/"><code>profilestats.profile</code></a> decorator (<code>$ pip install profilestats</code>) -- a simple wrapper for <a href="http://pypi.python.org/pypi/pyprof2calltree">pyprof2calltree</a> module (rebranding of <code>lsprofcalltree.py</code>):</p>
<pr... | 16 | 2010-03-28T22:01:10Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] |
Using cProfile results with KCacheGrind | 1,896,032 | <p>I'm using cProfile to profile my Python program. Based upon <a href="http://blip.tv/file/1957086/">this talk</a> I was under the impression that KCacheGrind could parse and display the output from cProfile.</p>
<p>However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the... | 42 | 2009-12-13T09:43:00Z | 3,561,512 | <p>With cProfile you can also profile existing programs, without making any separate profiling script. Just run program with profiler</p>
<pre><code>python -m cProfile -o profile_data.pyprof script_to_profile.py
</code></pre>
<p>and open profile data in kcachegrind with pyprof2calltree, whose -k switch automatically ... | 73 | 2010-08-24T22:26:25Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] |
Using cProfile results with KCacheGrind | 1,896,032 | <p>I'm using cProfile to profile my Python program. Based upon <a href="http://blip.tv/file/1957086/">this talk</a> I was under the impression that KCacheGrind could parse and display the output from cProfile.</p>
<p>However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the... | 42 | 2009-12-13T09:43:00Z | 39,828,810 | <p>3 differents ways to profile your code and visualizing results in KCachegrind/Qcachegrind:</p>
<h1>I - CPROFILE</h1>
<p>1 - Profile myfunc() from ipython</p>
<pre><code>import cProfile
filename = 'filename.prof'
cProfile.run('myfunc()', filename)
</code></pre>
<p>2 - Convert your file to a usable kcachegrind fil... | 0 | 2016-10-03T09:49:56Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] |
How do I use this information in Python? I don't know how to use this data-type | 1,896,260 | <p>According to the NLTK book, I first apply the grammar, and parse it.</p>
<pre><code>grammar = r"""
NP: {<DT|PP\$>?<JJ>*<NN>}
{<NNP>+}
"""
cp = nltk.RegexpParser(grammar)
chunked_sent = cp.parse(sentence)
</code></pre>
<p>When I <strong>print chun... | 1 | 2009-12-13T11:40:04Z | 3,935,136 | <p>Well you might have already found the answer. I am posting it for the people who might face this scenario in the future.</p>
<pre><code>for subtree in chunked_sent.subtrees():
if subtree.node == 'NP': print subtree
</code></pre>
| 0 | 2010-10-14T15:58:20Z | [
"python",
"list",
"variables",
"types",
"tuples"
] |
How to determine the datatype in Python? | 1,896,261 | <p>astring
('a','tuple')</p>
<p>How do I determine if "x" is a tuple or string?</p>
| 2 | 2009-12-13T11:41:30Z | 1,896,264 | <pre><code>isinstance(x, str)
isinstance(x, tuple)
</code></pre>
<p>In general:</p>
<pre><code>isinstance(variable, type)
</code></pre>
<p>Checks whether <code>variable</code> is an instance of <code>type</code> (or its subtype) (<a href="http://docs.python.org/library/functions.html#isinstance" rel="nofollow">docs<... | 5 | 2009-12-13T11:43:02Z | [
"python"
] |
How to determine the datatype in Python? | 1,896,261 | <p>astring
('a','tuple')</p>
<p>How do I determine if "x" is a tuple or string?</p>
| 2 | 2009-12-13T11:41:30Z | 1,896,268 | <pre><code>if isinstance(x, basestring):
# a string
else:
try: it = iter(x)
except TypeError:
# not an iterable
else:
# iterable (tuple, list, etc)
</code></pre>
<p><a href="http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python/1549854#1549854">@Alex Mar... | 8 | 2009-12-13T11:45:38Z | [
"python"
] |
How to determine the datatype in Python? | 1,896,261 | <p>astring
('a','tuple')</p>
<p>How do I determine if "x" is a tuple or string?</p>
| 2 | 2009-12-13T11:41:30Z | 1,896,403 | <p>use <code>isinstance()</code>, general syntax is:</p>
<pre><code>if isinstance(var, type):
# do something
</code></pre>
| 0 | 2009-12-13T12:47:15Z | [
"python"
] |
Special characters in OSX filename ? (Python os.rename) | 1,896,442 | <p>I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.:</p>
<pre><code>oldname = "/test"
newname = "/test(1\/10)"
os.rename(oldname, newname)
</code></pre>
<p>I think I do have an encoding problem. But different tries with re.e... | 2 | 2009-12-13T13:00:38Z | 1,896,464 | <p>What most of the file systems have in common is that they do not allow directory separators (slashes) in filenames.</p>
<p>That said, in Mac OS X you can have file names <em>appear</em> with slashes in finder, you can try replacing slashes with <code>:</code>.</p>
| 2 | 2009-12-13T13:09:14Z | [
"python",
"osx",
"path",
"character-encoding",
"filesystems"
] |
Special characters in OSX filename ? (Python os.rename) | 1,896,442 | <p>I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.:</p>
<pre><code>oldname = "/test"
newname = "/test(1\/10)"
os.rename(oldname, newname)
</code></pre>
<p>I think I do have an encoding problem. But different tries with re.e... | 2 | 2009-12-13T13:00:38Z | 1,896,477 | <p>If you're trying to rename the folder '/test' you'll need to run python as root, otherwise you won't have privileges to change stuff in the root. Furthermore the slash in your new name won't work as python will try find a directory "/test(1", so you'll have to let the directory separator go. Also this from the pytho... | 0 | 2009-12-13T13:12:48Z | [
"python",
"osx",
"path",
"character-encoding",
"filesystems"
] |
lxml[.objectify] documentElement tagName | 1,896,628 | <p>I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this:</p>
<pre><code>dom = minidom.parseString(the_data)
root = dom.documentElemen... | 0 | 2009-12-13T14:16:04Z | 1,897,267 | <p>FWIW in <a href="http://wiki.xml3k.org/Amara2" rel="nofollow">Amara Bindery</a> you can do something like:</p>
<pre><code>from amara import bindery
doc = bindery.parse(the_data)
top_elem = doc.xml_elements.next()
deleg = getattr(self, 'elem_' + str(top_elem.xml_qname))
deleg(doc)
</code></pre>
<p>And you get a Pyt... | 0 | 2009-12-13T18:30:08Z | [
"python",
"xml",
"lxml"
] |
lxml[.objectify] documentElement tagName | 1,896,628 | <p>I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this:</p>
<pre><code>dom = minidom.parseString(the_data)
root = dom.documentElemen... | 0 | 2009-12-13T14:16:04Z | 1,898,053 | <p>With the help of the <a href="http://codespeak.net/lxml/objectify.html" rel="nofollow">lxml docs</a> and the dir() built_in, I managed to produce this:</p>
<pre><code>>>> from lxml import objectify
>>> import StringIO
>>> tree = objectify.parse(StringIO.StringIO('<parent><child&g... | 3 | 2009-12-13T22:35:30Z | [
"python",
"xml",
"lxml"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 1,896,687 | <p>There is a recipe for sorting files larger than RAM <a href="http://code.activestate.com/recipes/466302/">on this page</a>, though you'd have to adapt it for your case involving CSV-format data. There are also links to additional resources there.</p>
<p><strong>Edit:</strong> True, the file on disk is not "larger ... | 17 | 2009-12-13T14:38:05Z | [
"python",
"memory",
"sorting",
"large-files"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 1,896,753 | <p>Since these are all just numbers, loading them into an Nx2 array would remove some overhead. Use NumPy for multidimensional arrays. Alternatively, you could use two normal python <a href="http://docs.python.org/library/array.html" rel="nofollow">arrays</a> to represent each column. </p>
| 4 | 2009-12-13T14:59:00Z | [
"python",
"memory",
"sorting",
"large-files"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 1,896,925 | <p>The cheapest way to store the input lines in memory is as array.array('i') elements -- assuming each number will fit in a signed 32-bit integer. The memory cost will be 8N bytes, where N is the number of lines.</p>
<p>Here is how to do the sort and write the output file in sorted order:</p>
<pre><code>from array i... | 4 | 2009-12-13T16:14:40Z | [
"python",
"memory",
"sorting",
"large-files"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 1,896,987 | <p>All python objects have a memory overhead on top of the data they are actually storing. According to getsizeof on my 32 bit Ubuntu system a tuple has an overhead of 32 bytes and an int takes 12 bytes, so each row in your file takes a 56 bytes + a 4 byte pointer in the list - I presume it will be a lot more for a 64... | 6 | 2009-12-13T16:32:22Z | [
"python",
"memory",
"sorting",
"large-files"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 1,897,467 | <p>You might want to look at mmap:</p>
<p><a href="http://docs.python.org/library/mmap.html" rel="nofollow">http://docs.python.org/library/mmap.html</a></p>
<p>It'll let you treat the file like a big array/string and will get the OS to handle shuffling data into and out of memory to let it fit.</p>
<p>So you could r... | 2 | 2009-12-13T19:32:17Z | [
"python",
"memory",
"sorting",
"large-files"
] |
Python: How to read huge text file into memory | 1,896,674 | <p>I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file</p>
<pre><code>$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
... | 19 | 2009-12-13T14:34:04Z | 24,887,790 | <p>I created a module for this use case using <a href="http://en.wikipedia.org/wiki/External_sorting#External_merge_sort" rel="nofollow">external merge sort</a>:
<a href="https://bitbucket.org/richardpenman/csvsort" rel="nofollow">https://bitbucket.org/richardpenman/csvsort</a></p>
<pre><code>>>> from csvsort... | 0 | 2014-07-22T12:44:33Z | [
"python",
"memory",
"sorting",
"large-files"
] |
How to return a float point number with a defined number of decimal places? | 1,896,722 | <p>So I know how to <strong>print</strong> a floating point number with a certain decimal places.</p>
<p>My question is how to <strong>return</strong> it with a specified number of decimal places?</p>
<p>Thanks.</p>
| 0 | 2009-12-13T14:46:44Z | 1,896,729 | <p>In order to get two decimal places, multiply the number by 100, floor it, then divide by 100.</p>
<p>And note that the number you will return will not really have only two decimal places because division by 100 cannot be represented exactly in IEEE-754 floating-point arithmetic most of the time. It will only be the... | 4 | 2009-12-13T14:48:52Z | [
"python",
"floating-point"
] |
How to return a float point number with a defined number of decimal places? | 1,896,722 | <p>So I know how to <strong>print</strong> a floating point number with a certain decimal places.</p>
<p>My question is how to <strong>return</strong> it with a specified number of decimal places?</p>
<p>Thanks.</p>
| 0 | 2009-12-13T14:46:44Z | 1,896,737 | <p>Floating point numbers have infinite number of decimal places. The physical representation on the computer is dependent on the representation of float, or double, or whatever and is dependent on a) language b) construct, e.g. float, double, etc. c) compiler implementation d) hardware.</p>
<p>Now, given that you hav... | 2 | 2009-12-13T14:52:00Z | [
"python",
"floating-point"
] |
How to return a float point number with a defined number of decimal places? | 1,896,722 | <p>So I know how to <strong>print</strong> a floating point number with a certain decimal places.</p>
<p>My question is how to <strong>return</strong> it with a specified number of decimal places?</p>
<p>Thanks.</p>
| 0 | 2009-12-13T14:46:44Z | 1,896,741 | <p>You could use the <code>round()</code> function</p>
<p>The docs about it:</p>
<pre><code>round(x[, n])
</code></pre>
<p>x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.</p>
| 6 | 2009-12-13T14:53:16Z | [
"python",
"floating-point"
] |
How to return a float point number with a defined number of decimal places? | 1,896,722 | <p>So I know how to <strong>print</strong> a floating point number with a certain decimal places.</p>
<p>My question is how to <strong>return</strong> it with a specified number of decimal places?</p>
<p>Thanks.</p>
| 0 | 2009-12-13T14:46:44Z | 1,896,786 | <p>If you really want floating point numbers with a fixed precision you could use the <a href="http://docs.python.org/library/decimal.html" rel="nofollow"><code>decimal</code></a> module. Those numbers have a user alterable precision and you could just do your calculation on two-digit decimals.</p>
| 4 | 2009-12-13T15:13:25Z | [
"python",
"floating-point"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 1,896,955 | <p>Use <code>setup.py develop</code> to make your working directory be part of the installed Python environment, then run the tests.</p>
| 3 | 2009-12-13T16:24:53Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 1,896,959 | <p>From the article you linked to:</p>
<blockquote>
<p>Create a test_modulename.py file and
put your unittest tests in it. Since
the test modules are in a separate
directory from your code, you may need
to add your moduleâs parent directory
to your PYTHONPATH in order to run
them:</p>
<pre><code>$ cd ... | 14 | 2009-12-13T16:25:43Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 1,896,964 | <p>if you run "python setup.py develop" then the package will be in the path. But you may not want to do that because you could infect your system python installation, which is why tools like <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> and <a href="http://www.buildout.org/" rel="nofol... | 3 | 2009-12-13T16:27:00Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 1,897,665 | <p>The simplest solution for your users is to provide an executable script (<code>runtests.py</code> or some such) which bootstraps the necessary test environment, including, if needed, adding your root project directory to sys.path temporarily. This doesn't require users to set environment variables, something like th... | 36 | 2009-12-13T20:40:58Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 2,992,477 | <p>I generally create a "run tests" script in the project directory (the one that is common to both the source directory and <code>test</code>) that loads my "All Tests" suite. This is usually boilerplate code, so I can reuse it from project to project.</p>
<p>run_tests.py:</p>
<pre><code>import unittest
import test.... | 13 | 2010-06-07T19:30:11Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 20,371,877 | <p>I had the same problem, with a separate unit tests folder. From the mentioned suggestions I add the <strong>absolute source path</strong> to <code>sys.path</code>.</p>
<p>The benefit of the following solution is, that one can run the file <code>test/test_yourmodule.py</code> without changing at first into the test-... | 2 | 2013-12-04T09:45:09Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 22,244,465 | <p>You should really use the pip tool.</p>
<p>As pointed out by <a href="http://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure#comment32573344_1896955">@Eric Smith</a>, <code>pip install -e</code> install your package in editable mode. This is a very good practise. And I thi... | -2 | 2014-03-07T07:51:46Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 24,266,885 | <p>The best solution in my opinion is to use the <code>unittest</code> <a href="https://docs.python.org/2/library/unittest.html#command-line-interface">command line interface</a> which will add the directory to the <code>sys.path</code> so you don't have to (done in the <code>TestLoader</code> class).</p>
<p>For examp... | 225 | 2014-06-17T14:49:19Z | [
"python",
"unit-testing"
] |
Running unittest with typical test directory structure | 1,896,918 | <p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>for example see thi... | 286 | 2009-12-13T16:10:23Z | 30,693,137 | <p>It's possible to use wrapper which runs selected or all tests.</p>
<p>For instance:</p>
<pre><code>./run_tests antigravity/*.py
</code></pre>
<p>or to run all tests recursively use extended globbing (<code>tests/**/*.py</code>).</p>
<p>The wrapper can basically use <code>argparse</code> to parse the arguments li... | 1 | 2015-06-07T11:45:51Z | [
"python",
"unit-testing"
] |
Creating Regular Expressions in Python | 1,897,254 | <p>I'm trying to create regular expression that filters from the following partial text:</p>
<pre><code>amd64 build of software 1:0.98.10-0.2svn20090909 in archive
</code></pre>
<p>what I want to extract is: </p>
<pre><code>software 1:0.98.10-0.2svn20090909
</code></pre>
<p>How can I do this?? I've been trying and ... | 0 | 2009-12-13T18:26:21Z | 1,897,266 | <p>Don't use a capturing group if you want everything in one piece.</p>
| 0 | 2009-12-13T18:29:54Z | [
"python",
"regex",
"expression"
] |
Creating Regular Expressions in Python | 1,897,254 | <p>I'm trying to create regular expression that filters from the following partial text:</p>
<pre><code>amd64 build of software 1:0.98.10-0.2svn20090909 in archive
</code></pre>
<p>what I want to extract is: </p>
<pre><code>software 1:0.98.10-0.2svn20090909
</code></pre>
<p>How can I do this?? I've been trying and ... | 0 | 2009-12-13T18:26:21Z | 1,897,273 | <p>This will work:</p>
<pre><code>p = re.compile(r'([a-zA-Z0-9\-\+\.]+)\ ([0-9][0-9a-zA-Z\:\.\-]+)')
iterator = p.finditer("amd64 build of dvdrip software 1:0.98.10-0.2svn20090909 in archive")
for match in iterator:
print match.group()
# Prints: software 1:0.98.10-0.2svn20090909
</code></pre>
<p>That works by all... | 3 | 2009-12-13T18:31:02Z | [
"python",
"regex",
"expression"
] |
Creating Regular Expressions in Python | 1,897,254 | <p>I'm trying to create regular expression that filters from the following partial text:</p>
<pre><code>amd64 build of software 1:0.98.10-0.2svn20090909 in archive
</code></pre>
<p>what I want to extract is: </p>
<pre><code>software 1:0.98.10-0.2svn20090909
</code></pre>
<p>How can I do this?? I've been trying and ... | 0 | 2009-12-13T18:26:21Z | 1,897,418 | <p>If you have consistent lines, this is, if each entry is on one line and the first word you want is always before the numbers part (the 1:0.98 ... part) you don't need a regexp. Try this:</p>
<pre><code>>>> s = 'amd64 build of software 1:0.98.10-0.2svn20090909 in archive'
>>> match = [s.split()[3],... | 3 | 2009-12-13T19:16:17Z | [
"python",
"regex",
"expression"
] |
Problem opening registry key on Windows 7 | 1,897,324 | <p>This code used to work on Vista (and Windows XP) but after an upgrade to Windows 7 it now fails with the error shown:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> import _winreg
>>> h1 = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MA... | 4 | 2009-12-13T18:48:57Z | 1,897,673 | <p>I think you have an access right problem.</p>
<p>Try to open the key with a less demanding access right (e.g. <code>KEY_QUERY_VALUE</code>) and check if it works.
Of course, with that change you will not be able to change the registry, but it would be only for pinpointing the issue.<br>
As an alternative, try to ex... | 1 | 2009-12-13T20:45:21Z | [
"python",
"windows-7",
"registry"
] |
Problem opening registry key on Windows 7 | 1,897,324 | <p>This code used to work on Vista (and Windows XP) but after an upgrade to Windows 7 it now fails with the error shown:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> import _winreg
>>> h1 = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MA... | 4 | 2009-12-13T18:48:57Z | 1,898,559 | <p>This was a user mistake, compounded or triggered by changes in Windows 7 to how the UAC feature is implemented. </p>
<p>In Vista, the much-detested User Access Control feature was binary, either on or off. On Windows 7 that has been changed to provide four levels of granularity:</p>
<ul>
<li>Always Notify (when ... | 2 | 2009-12-14T01:54:35Z | [
"python",
"windows-7",
"registry"
] |
ORM library for automatically mapping foreign keys in Python or Ruby | 1,897,465 | <p>A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.</p>
<p>What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts ag... | 3 | 2009-12-13T19:32:06Z | 1,897,483 | <p>In Ruby there are several ORMs like <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html" rel="nofollow">ActiveRecord</a>, <a href="http://datamapper.org/" rel="nofollow">DataMapper</a> or even <a href="http://sequel.rubyforge.org/" rel="nofollow">Sequel</a>.</p>
<p>For example using ActiveRecord you ... | -2 | 2009-12-13T19:36:47Z | [
"python",
"ruby",
"database",
"orm"
] |
ORM library for automatically mapping foreign keys in Python or Ruby | 1,897,465 | <p>A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.</p>
<p>What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts ag... | 3 | 2009-12-13T19:32:06Z | 1,897,637 | <p>Serious Ruby ORMs don't do this for a reason: it's inflexible, not explicit enough and too much magic.</p>
<p>If you <em>really</em> want this in your project, try coding it yourself in Ruby. Here's what I've done in 5 minutes on top of ActiveRecord:</p>
<pre><code>require 'active_record'
class ActiveRecord::Base... | 3 | 2009-12-13T20:28:35Z | [
"python",
"ruby",
"database",
"orm"
] |
ORM library for automatically mapping foreign keys in Python or Ruby | 1,897,465 | <p>A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.</p>
<p>What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts ag... | 3 | 2009-12-13T19:32:06Z | 1,897,964 | <p>You should take a look at the <a href="http://www.sqlalchemy.org/docs/05/reference/ext/sqlsoup.html" rel="nofollow">SQLSoup extension</a> in <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>. It claims to do all this for you (including foreign keys). I haven't tested it myself.</p>
| 4 | 2009-12-13T22:09:21Z | [
"python",
"ruby",
"database",
"orm"
] |
ORM library for automatically mapping foreign keys in Python or Ruby | 1,897,465 | <p>A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.</p>
<p>What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts ag... | 3 | 2009-12-13T19:32:06Z | 1,900,361 | <p>Try the <a href="http://code.google.com/p/sqlautocode/" rel="nofollow">sqlautocode</a> module for SQLAlchemy. It will generate the ORM classes by reflecting the database.</p>
| 0 | 2009-12-14T11:26:57Z | [
"python",
"ruby",
"database",
"orm"
] |
validating correct answer with loops in python | 1,897,531 | <p>Sorry for the non descriptive question I had no idea how to word it.</p>
<p>I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.</p>
<p>My code looks something li... | 0 | 2009-12-13T19:52:22Z | 1,897,540 | <p>I'd recommend that you abstract that user interface detail away from the problem of showing questions, obtaining answers, and determining correctness. You can sort all of that out with nothing more than a command line, text based user interface. Once you have that, then you can proceed with the user interface desi... | 0 | 2009-12-13T19:56:29Z | [
"python",
"user-interface"
] |
validating correct answer with loops in python | 1,897,531 | <p>Sorry for the non descriptive question I had no idea how to word it.</p>
<p>I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.</p>
<p>My code looks something li... | 0 | 2009-12-13T19:52:22Z | 1,897,566 | <p>i don't see a reason the logic would fail, but are you sure you are pressing "A" and not "a" .</p>
| 0 | 2009-12-13T20:02:59Z | [
"python",
"user-interface"
] |
validating correct answer with loops in python | 1,897,531 | <p>Sorry for the non descriptive question I had no idea how to word it.</p>
<p>I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.</p>
<p>My code looks something li... | 0 | 2009-12-13T19:52:22Z | 1,897,571 | <p>I can't say anything about this particular problem, but I would do a</p>
<pre><code>print "'" + answer + "'"
print answer.__class__
</code></pre>
<p>I have encountered wrapper classes (in OTHER situations) which behave like strings
but are not actually strings. Furthermore spaces and newlines can be added everywhe... | 0 | 2009-12-13T20:03:51Z | [
"python",
"user-interface"
] |
validating correct answer with loops in python | 1,897,531 | <p>Sorry for the non descriptive question I had no idea how to word it.</p>
<p>I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.</p>
<p>My code looks something li... | 0 | 2009-12-13T19:52:22Z | 1,897,598 | <p>The problem here seems to be that you're misunderstanding how GUIs work. It's not like the sequential print/read code that most programming instruction starts with. The GUI widgets only create themselves, draw to the screen and wait for events. </p>
<p>This line:</p>
<pre><code>Answer1 = entAnswer.getText()
</code... | 4 | 2009-12-13T20:15:16Z | [
"python",
"user-interface"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 1,897,657 | <p>If you like <code>d.variable</code> syntax better than <code>d['variable']</code>, you can wrap the dictionary in <a href="http://code.activestate.com/recipes/52308/">an almost trivial "bunch" object</a> such as this:</p>
<pre><code>class Bunch:
def __init__(self, **kw):
self.__dict__.update(kw)
</code>... | 7 | 2009-12-13T20:35:32Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 1,897,666 | <p>I do not think you can get any more convenience for dict unpacking in Python. So, here comes the obligatory "if that hurts, don't do that" answer.</p>
<p>Mapping item access IS more cumbersome than attribute access in Python, so maybe you should pass instances of user-defined classes instead of dicts.</p>
| 2 | 2009-12-13T20:41:37Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 1,897,733 | <p>I think the common wisdom is "don't use the <code>inspect</code> module in production code", and I mostly agree with that. As such, I think it is a bad idea to do the following in production code. But, if you're working on a python that supports frames (like CPython), this <em>should</em> work:</p>
<pre><code>>&... | 1 | 2009-12-13T21:02:32Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 1,897,781 | <p>This is similar to your decorator idea, but it is a bit more general, as it allows you to pass an arbitrary number of dicts to <code>foo</code>, and the decorator does not have to know anything about the keys in the dicts or the order of the arguments when calling the underlying <code>foo</code> function.</p>
<pre>... | 2 | 2009-12-13T21:17:52Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 1,897,822 | <p>You can always pass a dictionary as an argument to a function. For instance, </p>
<pre><code>dict = {'a':1, 'b':2}
def myFunc( a=0,b=0,c=0 ):
print a,b,c
myFunc(**dict)
</code></pre>
| 14 | 2009-12-13T21:28:36Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 4,014,043 | <p>Assuming all keys in your dictionary qualify to be identifiers,
You can simply do this:</p>
<pre><code>adict = { 'x' : 'I am x', 'y' : ' I am y' }
for key in adict.keys():
exec(key + " = adict['" + key + "']")
blah(x)
blah(y)
</code></pre>
| 7 | 2010-10-25T11:20:16Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 10,880,106 | <p>This is what I use as a <code>locals().update(d1)</code> workaround:</p>
<pre><code>def f(d1,d2)
exec ','.join(d1) + ', = d1.values()'
blah(x)
blah(y)
</code></pre>
| 2 | 2012-06-04T10:54:46Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 24,112,242 | <p>I wrote a Python package called var_arguments for conveniently bundling and unbundling arguments that should be useful here; it's available <a href="https://github.com/mcoram/var_arguments" rel="nofollow">on github</a>.</p>
<p>Instead of writing, say:</p>
<pre><code>def f(d1,d2):
x,y,a,b = d1['x'],d1['y'],d2['... | 0 | 2014-06-09T00:26:40Z | [
"python",
"function",
"dictionary",
"parameters"
] |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | <p>In the work I do, I often have parameters that I need to group into subsets for convenience:</p>
<pre><code>d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
</code></pre>
<p>I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:</p>
<pre><code>def f(d1,d2):
for k in ... | 19 | 2009-12-13T20:24:33Z | 33,365,141 | <p>Here's a unpacking method in a one liner:</p>
<p><code>x,y = (lambda a,b,**_: (a,b))(**{'a':'x', 'b':'y', 'c': 'z'})</code></p>
<p>the lambda args <code>a</code> and <code>b</code> are the keys I want to unpack into <code>x</code> and <code>y</code> in that order. <code>**_</code> is there to ignore any other keys... | 0 | 2015-10-27T10:14:24Z | [
"python",
"function",
"dictionary",
"parameters"
] |
Executing server-side Unix scripts asynchronously | 1,897,748 | <p>We have a collection of Unix scripts (and/or Python modules) that each perform a long running task. I would like to provide a web interface for them that does the following:</p>
<ul>
<li>Asks for relevant data to pass into scripts.</li>
<li>Allows for starting/stopping/killing them.</li>
<li>Allows for monitoring t... | 2 | 2009-12-13T21:07:43Z | 1,897,759 | <p>Django is great for writing web applications, and the subprocess module (subprocess.Popen en .communicate()) is great for executing shell scripts. You can give it a stdin,stdout and stderr stream for communication if you want.</p>
| 1 | 2009-12-13T21:12:01Z | [
"python",
"http",
"unix",
"asynchronous"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.