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 |
|---|---|---|---|---|---|---|---|---|---|
adding a keyword argument to an overriden method and using **kwarg | 1,715,840 | <p>I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the method.
Is it possible to work with <code>*args</code>... | 11 | 2009-11-11T15:16:28Z | 1,715,904 | <pre><code>class A(object):
def foo(self, arg1, arg2, argopt1="bar"):
print arg1, arg2, argopt1
class B(A):
def foo(self, *args, **kwargs):
argopt2 = kwargs.get('argopt2', default_for_argopt2)
# remove the extra arg so the base class doesn't complain.
del kwargs['argopt2']
... | 9 | 2009-11-11T15:24:33Z | [
"python"
] |
adding a keyword argument to an overriden method and using **kwarg | 1,715,840 | <p>I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the method.
Is it possible to work with <code>*args</code>... | 11 | 2009-11-11T15:16:28Z | 1,716,122 | <p>When subclassing and overriding methods, one must always decide if using <code>super()</code> is a good idea, and <a href="http://fuhm.org/super-harmful/" rel="nofollow">this page</a> is good for that.</p>
<p>I'm <em>not</em> saying that <code>super()</code> should be avoided, like the article author may be: I'm sa... | 1 | 2009-11-11T15:56:18Z | [
"python"
] |
adding a keyword argument to an overriden method and using **kwarg | 1,715,840 | <p>I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the method.
Is it possible to work with <code>*args</code>... | 11 | 2009-11-11T15:16:28Z | 1,716,153 | <blockquote>
<p>What's the right way to do this, do I
have to know and explicitly state all
of the overridden methods arguments?</p>
</blockquote>
<p>If you want to cover all cases (rather than just rely on the caller to always do things your way, e.g., always call you only with the extra argument passed by-name... | 4 | 2009-11-11T16:00:57Z | [
"python"
] |
Something like pubsubhubbub that does not depend on google app engine | 1,716,117 | <p>I am looking for something like <a href="http://en.wikipedia.org/wiki/PubSubHubbub" rel="nofollow">PubSubHubbub</a> that does not depend on google app engine to run.</p>
<p>What I need is a tool that can track for me a big very large number of rss or atom feeds and issue events when they are updated.</p>
| 6 | 2009-11-11T15:55:29Z | 1,716,209 | <p>pubsubhubbub is a protocol, and, as such, does not depend on app engine. For example, <a href="http://superfeedr.com/">superfeedr</a> is another implementation of this protocol (I believe it's free for the first 1000 feeds, then something like 50 dollars a month for the next 1000 feeds, then decreasing gradually fo... | 12 | 2009-11-11T16:08:46Z | [
"python",
"rss",
"atom",
"feed",
"pubsubhubbub"
] |
Something like pubsubhubbub that does not depend on google app engine | 1,716,117 | <p>I am looking for something like <a href="http://en.wikipedia.org/wiki/PubSubHubbub" rel="nofollow">PubSubHubbub</a> that does not depend on google app engine to run.</p>
<p>What I need is a tool that can track for me a big very large number of rss or atom feeds and issue events when they are updated.</p>
| 6 | 2009-11-11T15:55:29Z | 1,716,708 | <p><a href="https://git.participatoryculture.org/djpubsubhubbub/" rel="nofollow">Here</a> is Django library implementing this protocol.</p>
| 3 | 2009-11-11T17:18:09Z | [
"python",
"rss",
"atom",
"feed",
"pubsubhubbub"
] |
Django Form Wizard and Preview with ModelForm | 1,716,247 | <p>I have a large Django model (73 fields) that will will be connected to a ModelForm. I'd like to use a combination of the functionality found the Form Wizard and Form Preview contrib apps. </p>
<p>I.e., the form fields would be split over multiple pages, and the user would have a chance to review/preview the data be... | 7 | 2009-11-11T16:15:14Z | 2,152,059 | <p>I do a similar thing at my first Django project. Using session-based FormWizard, I customized it so user can stop subbmiting data at any form.</p>
<p>At that point you can use FormPreview probably to show information or just dynamically generate form and show it to user. Data stays in the session.</p>
| 1 | 2010-01-28T03:15:32Z | [
"python",
"django",
"forms",
"wizard",
"preview"
] |
def next() for Python pre-2.6? (instead of object.next method) | 1,716,428 | <p>Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?</p>
| 5 | 2009-11-11T16:35:51Z | 1,716,464 | <pre><code>class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
"""next(iterator[, default])
Return the next item from the iterator. If default is given
and the iterator is exhausted, it is returned instead of
raising StopIteration.
"""
try:
iternext = itera... | 11 | 2009-11-11T16:39:56Z | [
"python",
"next"
] |
def next() for Python pre-2.6? (instead of object.next method) | 1,716,428 | <p>Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?</p>
| 5 | 2009-11-11T16:35:51Z | 1,716,492 | <p>R. Pate seems to have a good answer. One extra bell to add: if you're writing code to run on many different versions of Python, you can conditionalize the definition:</p>
<pre><code>try:
next = next
except NameError:
def next():
# blah blah etc
</code></pre>
<p>That way you have <code>next</code> ... | 6 | 2009-11-11T16:43:42Z | [
"python",
"next"
] |
def next() for Python pre-2.6? (instead of object.next method) | 1,716,428 | <p>Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?</p>
| 5 | 2009-11-11T16:35:51Z | 1,717,478 | <p>Simpler method:</p>
<pre><code>import operator
next = operator.methodcaller("next")
</code></pre>
<p>Ned's suggestion about putting it in a <code>try</code> block works here as well, but if you're going to go that route, one minor note: in Python 3, calling <code>next()</code> on a non-iterator raises a <code>Typ... | 2 | 2009-11-11T19:28:02Z | [
"python",
"next"
] |
Which Python 2.x DHT implementation is going to be easiest to port to Python 3.x? | 1,716,526 | <p>Previously I asked <a href="http://stackoverflow.com/questions/1708315/which-dht-implementations-are-compatible-python-3-x">which DHT implementations are compatible with Python 3.x</a> - StackOverflow's answer confirmed my worst fear: So far nobody has released a Python 3.x compatible Distributed Hash Table implemen... | 2 | 2009-11-11T16:48:05Z | 1,716,540 | <p>Try running 2to3 on each of them, then run the resulting code. If one of them works, then it was the easiest to port. If none of them do, then take a guess based on which of their errors you understand best.</p>
| 3 | 2009-11-11T16:51:02Z | [
"python",
"dht"
] |
How to make a custom command line interface using OptionParser? | 1,716,554 | <p>I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). </p>
<p>I have these questions. </p>
<p>1.) I use OptionParser to parse this input, say for eg. (getting multiple args)</p>
<pre><code>my prompt> -a foo -b bar -c spam eggs
</code></pre>
<p>I did this with ... | 2 | 2009-11-11T16:52:08Z | 1,716,598 | <p>For part 2: you want a new OptionParser instance for each line you process. And look at the <a href="http://docs.python.org/library/cmd" rel="nofollow">cmd module</a> for writing a command loop like this.</p>
| 3 | 2009-11-11T16:59:49Z | [
"python",
"optparse"
] |
How to make a custom command line interface using OptionParser? | 1,716,554 | <p>I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). </p>
<p>I have these questions. </p>
<p>1.) I use OptionParser to parse this input, say for eg. (getting multiple args)</p>
<pre><code>my prompt> -a foo -b bar -c spam eggs
</code></pre>
<p>I did this with ... | 2 | 2009-11-11T16:52:08Z | 1,716,644 | <p><code>optparse</code> solves #1 by requiring that an argument always have the same number of <a href="http://docs.python.org/library/optparse.html#optparse.Option.nargs" rel="nofollow">parameters</a> (even if that number is 0), variable-parameter arguments are not allowed:</p>
<blockquote>
<p>Typically, a given o... | 1 | 2009-11-11T17:07:44Z | [
"python",
"optparse"
] |
How to make a custom command line interface using OptionParser? | 1,716,554 | <p>I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). </p>
<p>I have these questions. </p>
<p>1.) I use OptionParser to parse this input, say for eg. (getting multiple args)</p>
<pre><code>my prompt> -a foo -b bar -c spam eggs
</code></pre>
<p>I did this with ... | 2 | 2009-11-11T16:52:08Z | 1,716,696 | <p>You can also solve #1 using the <code>nargs</code> option attribute as follows:</p>
<pre><code>parser = OptionParser()
parser.add_option("-c", "", nargs=2)
parser.add_option("-d", "", nargs=3)
</code></pre>
| 2 | 2009-11-11T17:16:17Z | [
"python",
"optparse"
] |
Python using PRE-FETCH on Oracle 10 | 1,716,606 | <pre><code>import cx_Oracle
import wx
print "Start..." + str(wx.Now())
base = cx_Oracle.makedsn('xxx', port, 'yyyy')
connection = cx_Oracle.connect(user name, password, base)
cursor = connection.cursor()
cursor.execute('select data from t_table')
li_row = cursor.fetchall()
data = []
for row in li_row:
data... | 1 | 2009-11-11T17:00:56Z | 1,717,142 | <p>Fetching 10000 rows...</p>
<p>cursor.arraysize = 10000</p>
| 0 | 2009-11-11T18:19:33Z | [
"python",
"oracle10g"
] |
The choice of XML/XSL lib for Python 2.6.x | 1,716,647 | <p>Currently I have 2 varieties, <a href="http://codespeak.net/lxml/" rel="nofollow">LXML</a> and <a href="http://xmlsoft.org/" rel="nofollow">libXML2</a> that both seem to work. I have tried benchmarking both, specifically for parsing memory string and files into XML and importing XSLT stylesheets and applying them. W... | 1 | 2009-11-11T17:08:39Z | 1,718,902 | <p>I've used LXML and been very impressed. The flexibility offered by having both the etree-like and objectify interfaces is pretty handy. I also like the fact that I don't have to have any separate text nodes.</p>
<p>As far as entity substitutions, I had a few issues too, but for me it was a matter of giving the pa... | 2 | 2009-11-11T23:50:51Z | [
"python",
"xslt",
"lxml",
"libxml2",
"benchmarking"
] |
Untrusted templates in Python - what is a safe library to use? | 1,716,869 | <p>I am building a library that will be used in several Python applications. It get multilingual e-mail templates from an RMDBS, and then variable replacement will be performed on the template in Python before the e-mail is sent.</p>
<p>In addition to variable replacement, I need the template library to support if, el... | 0 | 2009-11-11T17:43:15Z | 1,716,917 | <p>Have you checked out <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>? It's pretty much what you're talking about, and it's a great mix of powerful while keeping things simple and not giving the designer <em>too</em> much power. :)</p>
<p>If you've used Django's template system, it's very similar (if n... | 3 | 2009-11-11T17:48:31Z | [
"python",
"email",
"templates"
] |
Untrusted templates in Python - what is a safe library to use? | 1,716,869 | <p>I am building a library that will be used in several Python applications. It get multilingual e-mail templates from an RMDBS, and then variable replacement will be performed on the template in Python before the e-mail is sent.</p>
<p>In addition to variable replacement, I need the template library to support if, el... | 0 | 2009-11-11T17:43:15Z | 1,716,919 | <p>From the <a href="http://www.djangobook.com/en/2.0/chapter04/" rel="nofollow">Django book</a>:</p>
<blockquote>
<p>For that reason, itâs impossible to call Python code directly within Django templates. All âprogrammingâ is fundamentally limited to the scope of what template tags can do. It is possible to wr... | 4 | 2009-11-11T17:49:00Z | [
"python",
"email",
"templates"
] |
Strange decorator result on related object comparison | 1,716,946 | <p>On views that allow updating/deleting objects, I need a decorator that verifies that the object to be edited belongs to a group(model "loja). Both defined in the url:</p>
<p>/[slug model loja--s_loja]/[viewname-ex:addmenu]/[object id--obj_id]</p>
<p>Because the model of the object can vary, the decorator the model... | 0 | 2009-11-11T17:52:01Z | 1,716,986 | <p>Replace <code>is not</code> with <code>!=</code>.</p>
<p><code>not loja</code> is evaluating to <code>True</code>, and the if statement is testing the equality between <code>objecto.loja</code> and <code>True</code>.</p>
| 1 | 2009-11-11T17:58:31Z | [
"python",
"django",
"decorator"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 1,717,042 | <p>You could <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> the dictionary and store it as a StringProperty.</p>
| 2 | 2009-11-11T18:06:11Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 1,717,064 | <p>Serializing a dict with <code>repr</code> is a good way to do it. You can then reconstitute it with <code>eval</code>, or if you don't trust the data, a "<a href="http://code.activestate.com/recipes/496746/">safe eval</a>".</p>
<p>An advantage of repr over pickling is that the data is readable in the database, eve... | 7 | 2009-11-11T18:09:30Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 1,717,065 | <p>I'm pretty sure there's no way to store a Python dictionary. But why not just place what you'd like in hops as a second model?</p>
<p>Also, as mentioned by John you could use pickle, but (and correct me if I'm wrong) store it as a <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclass... | 2 | 2009-11-11T18:09:36Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 1,717,071 | <p>Your options are basically to use pickle, to use a db.Expando and make each key in the dict a separate property, or to have a StringListProperty of keys and one of values and zip() them back to a dict when reading.</p>
| 1 | 2009-11-11T18:10:24Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 1,717,578 | <p>You can use json</p>
| 6 | 2009-11-11T19:44:58Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
How do I put a dictionary in the datastore? | 1,717,027 | <p>Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:</p>
<pre><code>from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()... | 7 | 2009-11-11T18:03:25Z | 16,560,715 | <p>I did it like this:</p>
<pre><code>class MyEntity(db.Model):
dictionary_string = db.StringProperty()
payload = {{}...{}}
# Store dict
my_entity = MyEntity(key_name=your_key_here)
my_entity.dictionary_string = str(payload)
my_entity.put()
# Get dict
import ast
my_entity_k = db.Key.from_path('MyEntity', your_k... | 0 | 2013-05-15T08:54:37Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] |
Google Python Image Library - How to resize an image based on its width? | 1,717,070 | <p>I have this code to make a resize of an uploaded image as a thumbnail.</p>
<pre><code>project.thumbnail = db.Blob(images.resize(self.request.get("img"),188,96))
</code></pre>
<p>However, it does not do what I want. It always resize the image to have the fixed height of 96.</p>
<p>Instead, I want to have all the r... | 0 | 2009-11-11T18:10:18Z | 1,717,112 | <p>You can call this as <code>images.resize(data, width=188)</code></p>
| 4 | 2009-11-11T18:15:13Z | [
"python",
"google-app-engine",
"image-manipulation"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,493 | <p>Short answer: no.</p>
<p>Long answer: generally not.</p>
<p>While CPython's GIL makes single opcodes <a href="http://en.wikipedia.org/wiki/Thread%5Fsafety" rel="nofollow">thread-safe</a>, this is no general behaviour. You may not assume that even simple operations like an addition is a atomic instruction. The addi... | 3 | 2009-11-11T19:29:34Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,514 | <p>(note: you would need <code>global c</code> in each function to make your code work.)</p>
<blockquote>
<p>Is this code thread safe?</p>
</blockquote>
<p>No. Only a single bytecode instruction is âatomicâ in CPython, and a <code>+=</code> may not result in a single opcode, even when the values involved are si... | 24 | 2009-11-11T19:33:33Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,518 | <p>Single opcodes are thread-safe because of the GIL but nothing else:</p>
<pre><code>import time
class something(object):
def __init__(self,c):
self.c=c
def inc(self):
new = self.c+1
# if the thread is interrupted by another inc() call its result is wrong
time.sleep(0.001) # s... | 9 | 2009-11-11T19:34:44Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,536 | <p>Are you sure that the functions increment and decrement execute without any error?</p>
<p>I think it should raise an UnboundLocalError because you have to explicitly tell Python that you want to use the global variable named 'c'.</p>
<p>So change increment ( also decrement ) to the following:</p>
<pre><code>def i... | 0 | 2009-11-11T19:36:53Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,541 | <p>If you actually want to make your code <em>not</em> thread-safe, and have good chance of "bad" stuff actually happening without you trying like ten thousand times (or one time when you real <em>don't</em> want "bad" stuff to happen), you can 'jitter' your code with explicit sleeps:</p>
<pre><code>def Ãncrement():
... | 2 | 2009-11-11T19:37:02Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,717,552 | <p>It's easy to prove that your code is <strong>not thread safe</strong>. You can increase the likelyhood of seeing the race condition by using a sleep in the critical parts (this simply simulates a slow CPU). However if you run the code for long enough you should see the race condition eventually regardless.</p>
<pre... | 4 | 2009-11-11T19:39:29Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 1,718,843 | <p>No, this code is absolutely, demonstrably not threadsafe.</p>
<pre><code>import threading
i = 0
def test():
global i
for x in range(100000):
i += 1
threads = [threading.Thread(target=test) for t in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
assert i == 1000000, i
... | 40 | 2009-11-11T23:37:10Z | [
"python",
"thread-safety",
"increment"
] |
Is the += operator thread-safe in Python? | 1,717,393 | <p>I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.</p>
<pre><code>c = 0
def increment():
c += 1
def decrement():
c -= 1
</code></pre>
<p>Is this code thread safe?</p>
<p>If not, may I understand why it is not thread safe, and w... | 25 | 2009-11-11T19:08:46Z | 6,761,146 | <p>To be sure I recommend to use a lock:</p>
<pre><code>import threading
class ThreadSafeCounter():
def __init__(self):
self.lock = threading.Lock()
self.counter=0
def increment(self):
with self.lock:
self.counter+=1
def decrement(self):
with self.lock:
... | 10 | 2011-07-20T11:27:40Z | [
"python",
"thread-safety",
"increment"
] |
Customize HTML Output of Django ModelForm | 1,717,715 | <p>I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML.</p>
<pre><code>class LeagueForm(ModelForm):
league = forms.Mode... | 4 | 2009-11-11T20:05:51Z | 1,717,810 | <p>Just refer to each field separately.</p>
<pre><code>{{ nhl_form.league }}
</code></pre>
<p>will only show the <code>league</code> field, with no surrounding cruft.</p>
| 14 | 2009-11-11T20:22:00Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
Customize HTML Output of Django ModelForm | 1,717,715 | <p>I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML.</p>
<pre><code>class LeagueForm(ModelForm):
league = forms.Mode... | 4 | 2009-11-11T20:05:51Z | 3,847,942 | <p>see also <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets</a> </p>
| 0 | 2010-10-02T23:40:43Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
How to make a dashboard widget in mac os x using python | 1,717,782 | <p>Found that is possible to make cocoa apps with python:
<a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow">http://developer.apple.com/cocoa/pyobjc.html</a></p>
<p>My question now if it's possible to make dashboard widgets with python:
<a href="http://developer.apple.com/macosx/dashboard.html" rel=... | 1 | 2009-11-11T20:16:34Z | 1,717,827 | <p>Sorry I didn't read throughly:</p>
<blockquote>
<p>"Based on Web Kit technologies,
Dashboard Widgets are created using a
mix of HTML, JavaScript, and CSS."</p>
</blockquote>
<p>This is closed though.</p>
| 0 | 2009-11-11T20:24:50Z | [
"python",
"osx",
"dashboard",
"mac-dashboard-widget"
] |
several lexers for one parser with PLY? | 1,718,067 | <p>I'm trying to implement a python parser using PLY for the Kconfig language used to generate the configuration options for the linux kernel.</p>
<p>There's a keyword called source which performs an inclusion, so what i do is that when the lexer encounters this keyword, I change the lexer state to create a new lexer ... | 2 | 2009-11-11T21:07:15Z | 1,718,142 | <p>I don't know about the details of PLY, but in other systems like this that I've built, it made the most sense to have a single lexer which managed the stack of include files. So the lexer would return a unified stream of tokens, opening and closing include files as they were encountered.</p>
| 2 | 2009-11-11T21:18:11Z | [
"python",
"lexer",
"ply"
] |
several lexers for one parser with PLY? | 1,718,067 | <p>I'm trying to implement a python parser using PLY for the Kconfig language used to generate the configuration options for the linux kernel.</p>
<p>There's a keyword called source which performs an inclusion, so what i do is that when the lexer encounters this keyword, I change the lexer state to create a new lexer ... | 2 | 2009-11-11T21:07:15Z | 1,729,525 | <p>Ok,</p>
<p>so what i've done is building a list of all the tokens, which is built before the actual parsing.</p>
<p>The parser no longer calls the lexer because you can override the getToken function used by the parser using the tokenfunc parameter when calling the parse function.</p>
<pre><code>result = yacc.par... | 0 | 2009-11-13T14:25:47Z | [
"python",
"lexer",
"ply"
] |
several lexers for one parser with PLY? | 1,718,067 | <p>I'm trying to implement a python parser using PLY for the Kconfig language used to generate the configuration options for the linux kernel.</p>
<p>There's a keyword called source which performs an inclusion, so what i do is that when the lexer encounters this keyword, I change the lexer state to create a new lexer ... | 2 | 2009-11-11T21:07:15Z | 1,843,990 | <p>By an interesting coincidence a link from the same Google search that led me to this question explains how to <a href="http://lazypython.blogspot.com/2009/11/using-ply-for-parsing-without-using-it.html" rel="nofollow">write your own lexer for a PLY parser</a>. The post explains it simply and well, but it's a matter... | 2 | 2009-12-04T00:03:50Z | [
"python",
"lexer",
"ply"
] |
Finding the correct Python framework with cmake | 1,718,251 | <p>I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt</p>
<pre><code>include(FindPythonInterp)
include(FindPythonLibs )
</code></... | 7 | 2009-11-11T21:35:04Z | 1,724,738 | <p>I am not intimately familiar with CMake, but with the Apple version of gcc/ld, you can pass the <code>-F</code> flag to specify a new framework search path. For example, <code>-F/opt/local/Library/Frameworks</code> will search in MacPorts' frameworks directory. If you can specify such a flag using CMake, it may solv... | 1 | 2009-11-12T19:26:43Z | [
"python",
"frameworks",
"osx",
"cmake",
"macports"
] |
Finding the correct Python framework with cmake | 1,718,251 | <p>I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt</p>
<pre><code>include(FindPythonInterp)
include(FindPythonLibs )
</code></... | 7 | 2009-11-11T21:35:04Z | 1,728,003 | <p>Adding the following in <code>~/.bash_profile</code></p>
<pre><code>export DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks
</code></pre>
<p>fixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefull... | 5 | 2009-11-13T08:55:17Z | [
"python",
"frameworks",
"osx",
"cmake",
"macports"
] |
save Exceptions to file in python | 1,718,295 | <p>I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which saves all Exception to a file. Than... | 13 | 2009-11-11T21:43:51Z | 1,718,313 | <p>If you have a convenient <code>main()</code> function (whatever it's called), then you can use the <a href="http://docs.python.org/2/library/logging.html">logging module</a>:</p>
<pre><code>import logging
def main():
raise Exception("Hey!")
logging.basicConfig(level=logging.DEBUG, filename='/tmp/myapp.log')
... | 26 | 2009-11-11T21:49:19Z | [
"python",
"file",
"ubuntu",
"exception"
] |
"CSRF verification failed" when attempting to upload a file or create a folder with filebrowser for Django | 1,718,343 | <p>I have installed filebrowser for Django (not filebrowser3) and when I try to upload a file I recieve the following error:</p>
<blockquote>
<p><strong>403 Forbidden</strong></p>
<p>CSRF verification failed. Request
aborted.</p>
<p>More information is available with
DEBUG=True.</p>
</blockquote>
<p>T... | 10 | 2009-11-11T21:56:42Z | 1,718,362 | <p>You are probably using the development version of Django, which includes quite a lot of extra CRSF security. However it's not released yet so external products probably aren't compatible. You should use the 1.1 version of Django instead.</p>
| 6 | 2009-11-11T21:59:58Z | [
"python",
"django",
"upload",
"file-upload"
] |
"CSRF verification failed" when attempting to upload a file or create a folder with filebrowser for Django | 1,718,343 | <p>I have installed filebrowser for Django (not filebrowser3) and when I try to upload a file I recieve the following error:</p>
<blockquote>
<p><strong>403 Forbidden</strong></p>
<p>CSRF verification failed. Request
aborted.</p>
<p>More information is available with
DEBUG=True.</p>
</blockquote>
<p>T... | 10 | 2009-11-11T21:56:42Z | 1,761,188 | <p>The Djangodocs have more information about the new <a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="nofollow">Django CSRF requirements</a>:</p>
| 4 | 2009-11-19T06:00:50Z | [
"python",
"django",
"upload",
"file-upload"
] |
"CSRF verification failed" when attempting to upload a file or create a folder with filebrowser for Django | 1,718,343 | <p>I have installed filebrowser for Django (not filebrowser3) and when I try to upload a file I recieve the following error:</p>
<blockquote>
<p><strong>403 Forbidden</strong></p>
<p>CSRF verification failed. Request
aborted.</p>
<p>More information is available with
DEBUG=True.</p>
</blockquote>
<p>T... | 10 | 2009-11-11T21:56:42Z | 4,041,334 | <p>See here: <a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/csrf/</a> like fitzgeralsteele said.
Hugs.</p>
<p>Example:
from django.views.decorators.csrf import csrf_exempt</p>
<p>@csrf_exempt
def my_view(request):
return HttpRespons... | 1 | 2010-10-28T09:08:15Z | [
"python",
"django",
"upload",
"file-upload"
] |
"CSRF verification failed" when attempting to upload a file or create a folder with filebrowser for Django | 1,718,343 | <p>I have installed filebrowser for Django (not filebrowser3) and when I try to upload a file I recieve the following error:</p>
<blockquote>
<p><strong>403 Forbidden</strong></p>
<p>CSRF verification failed. Request
aborted.</p>
<p>More information is available with
DEBUG=True.</p>
</blockquote>
<p>T... | 10 | 2009-11-11T21:56:42Z | 4,137,086 | <p>Add to you settings.py this 2 lines:</p>
<p>âdjango.middleware.csrf.CsrfViewMiddlewareâ,
âdjango.middleware.csrf.CsrfResponseMiddlewareâ,</p>
| 4 | 2010-11-09T18:21:35Z | [
"python",
"django",
"upload",
"file-upload"
] |
"CSRF verification failed" when attempting to upload a file or create a folder with filebrowser for Django | 1,718,343 | <p>I have installed filebrowser for Django (not filebrowser3) and when I try to upload a file I recieve the following error:</p>
<blockquote>
<p><strong>403 Forbidden</strong></p>
<p>CSRF verification failed. Request
aborted.</p>
<p>More information is available with
DEBUG=True.</p>
</blockquote>
<p>T... | 10 | 2009-11-11T21:56:42Z | 10,776,270 | <p>it work adding</p>
<pre><code>{% csrf_token %}
</code></pre>
<p>my forms looks like this: </p>
<pre><code><form method="post" action="">
{% csrf_token %}
{{ form.non_field_errors }}
{{formulario}}
<input type="submit" value="Guardar">
</form>
</code></pre>
<p>in to the tags on your template f... | 0 | 2012-05-27T18:29:53Z | [
"python",
"django",
"upload",
"file-upload"
] |
limiting number of optional, positional arguments to a function/method | 1,718,442 | <p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of a... | 1 | 2009-11-11T22:15:37Z | 1,718,493 | <p>Your solution seems reasonable to me.</p>
| 1 | 2009-11-11T22:23:51Z | [
"python"
] |
limiting number of optional, positional arguments to a function/method | 1,718,442 | <p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of a... | 1 | 2009-11-11T22:15:37Z | 1,718,527 | <p>It looks good to me.</p>
<p>If you want to abstract that logic out of the body of the function you can put it in a decorator:</p>
<pre><code>def validate_num_args(num_args=None, num_kwargs=None):
def entangle(f):
def inner(*args, **kwargs):
if not num_args is None and len(args) > num_arg... | 0 | 2009-11-11T22:29:35Z | [
"python"
] |
limiting number of optional, positional arguments to a function/method | 1,718,442 | <p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of a... | 1 | 2009-11-11T22:15:37Z | 1,718,534 | <p>this works:</p>
<pre><code>>>> def foo(a, b, c=3, **kwargs):
print(a, b, c, kwargs)
>>> foo(3, 4, 2)
3 4 2 {}
>>> foo(3, 4)
3 4 3 {}
</code></pre>
| 2 | 2009-11-11T22:30:15Z | [
"python"
] |
limiting number of optional, positional arguments to a function/method | 1,718,442 | <p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of a... | 1 | 2009-11-11T22:15:37Z | 1,718,558 | <p>You can write a decorator:</p>
<pre><code>class TooManyArgumentsException(Exception):
pass
def limit_args(n):
def limit_decorator(f):
def new_f(*args, **kwargs):
if len(args) > n:
raise TooManyArgumentsException("%d args accepted at most, %d args passed" % (n, len(arg... | 1 | 2009-11-11T22:34:40Z | [
"python"
] |
limiting number of optional, positional arguments to a function/method | 1,718,442 | <p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of a... | 1 | 2009-11-11T22:15:37Z | 1,718,563 | <p>One way to find out what is consider "pythonic" is to search for examples in the python source code itself.</p>
<pre><code>find '/usr/lib/python2.6' -name '*.py' -exec egrep 'len\(args\)' {} + | wc
156 867 12946
</code></pre>
<p>If you peruse the results of the above command (without the wc), you'll find... | 2 | 2009-11-11T22:35:36Z | [
"python"
] |
Understanding an error message while writing code for a Fibonacci program | 1,718,681 | <p>My apologies in advance should I butcher any Python vocabulary, this is my first programming class and we are not permitted to post or share our code. I will do my best to explain the problem.</p>
<p>I am defining my function as variable one and variable two. I then gave values to both variables. I used a for sta... | 1 | 2009-11-11T22:55:54Z | 1,718,688 | <p>To invoke your function, you have to use parens: <code>appendNextFib()</code>. It looks like you simply used <code>appendNextFib</code>, which would show you its value, which is that function object.</p>
| 3 | 2009-11-11T22:58:10Z | [
"python",
"fibonacci"
] |
Understanding an error message while writing code for a Fibonacci program | 1,718,681 | <p>My apologies in advance should I butcher any Python vocabulary, this is my first programming class and we are not permitted to post or share our code. I will do my best to explain the problem.</p>
<p>I am defining my function as variable one and variable two. I then gave values to both variables. I used a for sta... | 1 | 2009-11-11T22:55:54Z | 1,718,732 | <p>While I personally think you may be stressing too much about the sharing of your code, a recursive solution to the problem is a lot more logical and would help you out if your issue is caught up in the declaration of variables.</p>
<p>the recursive solution would look like</p>
<pre><code>def fib(n):
base case:... | 0 | 2009-11-11T23:08:57Z | [
"python",
"fibonacci"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 1,719,136 | <p>Looks like you're not uploading the whole <code>zoneinfo</code> subtree of <code>pytz</code> -- 570 files in 22 directories, in the version of pytz I have at hand. Not sure why -- by default if they're in your app dir they should get uploaded. Try appcfg.py --verbose update (or even --noisy) after touching a few ... | 2 | 2009-11-12T00:45:42Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 1,719,177 | <p>Actually that blog post is incorrect and makes a note to look at the new post, which is here: <a href="http://takashi-matsuo.blogspot.com/2008/07/using-newest-zipped-pytz-on-gae.html" rel="nofollow">Using the newest zipped pytz on GAE</a></p>
| 3 | 2009-11-12T00:56:59Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 1,719,470 | <p>I figured it out and it was more embarrassing than I anticipated.</p>
<p>The problem was that (as I specified in the question) I had made PyTZ a <strong>sibling</strong> of <code>webapp</code>. However, in order for GAE to be able to load it, it needs to be a <strong>child</strong> of <code>webapp</code>. This is n... | 1 | 2009-11-12T02:12:50Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 1,891,083 | <p>Based on the title of the question, I would like (but don't have the so reputation yet) to vote up jgeewax's answer since it's what I used when I found this question from a search. However, I'll also add that after following the instructions mentioned there, I created a minimal project on github which illustrates ... | 3 | 2009-12-11T21:48:13Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 3,513,463 | <p>An alternative is to use the packaged version of gae-pytz that includes further optimizations:
<a href="http://pypi.python.org/pypi/gaepytz" rel="nofollow">http://pypi.python.org/pypi/gaepytz</a></p>
<p>You only need the pytz folder in the zipped archive,
Using it in your gae project is as easy as:</p>
<pre><code... | 1 | 2010-08-18T15:00:22Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
How to properly add PyTZ to a Google App Engine application? | 1,718,724 | <p>This is a little embarrassing, but I have not been able to find good resources on this topic.</p>
<p>I'm working on a Google App Engine application that requires sophisticated time zone conversions. Since I am nowhere near the imposed quotas, I have opted to go with PyTZ. However, I must be doing something wrong. W... | 2 | 2009-11-11T23:07:24Z | 15,485,575 | <p>In response to this problem, went a different tact from <code>gae-pytz</code> and I created <a href="https://github.com/brianmhunt/pytz-appengine" rel="nofollow">pytz-appengine</a>. In particular pytz-appengine puts all the timezone information into the <code>ndb</code> datastore.</p>
<p>The unit tests for pytz pas... | 3 | 2013-03-18T19:48:23Z | [
"python",
"google-app-engine",
"datetime",
"timezone",
"pytz"
] |
Haystack Whoosh Spelling Suggestion too greedy | 1,718,758 | <p>This questions is about Django Haystack, with Whoosh backend.
I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much.</p>
<p>Say I have two models:
Apples and Oranges.</p>
<p>If I have somethine like this:</p>
<pre><code>result = SearchQuerySet().models(Apples).filter(... | 1 | 2009-11-11T23:12:37Z | 1,722,114 | <p>This is the problem because Haystack creates spelling suggestions based on the fields which have <strong>document=True</strong> (which in my case are the primary search field in all models and they have the same name). So it does not care about models at all and alway searches across all the knowledgebase.</p>
<p>I... | 2 | 2009-11-12T13:17:16Z | [
"python",
"django",
"django-haystack",
"whoosh"
] |
Render page initially and update via AJAX using the same template HTML | 1,718,784 | <p>Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list.... | 10 | 2009-11-11T23:18:28Z | 1,718,808 | <p>I think option 2 is best. It's incremental (only renders one more comment when a comment is added), and re-uses the rendering. If you don't like returning just HTML from an Ajax request, then have the response be a JSON structure which includes the HTML as just one component. Then you can also carry status (or wh... | 3 | 2009-11-11T23:24:52Z | [
"javascript",
"python",
"ajax",
"django"
] |
Render page initially and update via AJAX using the same template HTML | 1,718,784 | <p>Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list.... | 10 | 2009-11-11T23:18:28Z | 1,720,384 | <p>Here is what you should do:</p>
<p>view_story.html:</p>
<pre><code>bla bla bla
Comments:
<ul id="comments">
{% for comment in comments %}
<li>{% include "comment_item.html" %}</li>
{% endfor %}
</ul>
<from>Ajax form here</form>
</code></pre>
<p>than you need to create view ... | 6 | 2009-11-12T06:54:28Z | [
"javascript",
"python",
"ajax",
"django"
] |
Render page initially and update via AJAX using the same template HTML | 1,718,784 | <p>Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list.... | 10 | 2009-11-11T23:18:28Z | 3,067,371 | <p>There is also option 4:</p>
<p>Copy an existing element in the list and change its values. This is of course less flexible than templates. You can copy a hidden element instead to handle the case where the list is empty.</p>
<p>You could also try option 2b: </p>
<p>Generate the HTML on the server like option 2, b... | 1 | 2010-06-18T05:24:52Z | [
"javascript",
"python",
"ajax",
"django"
] |
In the MVC pattern, what goes in the model and what goes in the view? | 1,718,813 | <p>I'm using the MVC pattern to design some data analysis software (in python). I'm not sure whether some functions should go in the model or the controller.</p>
<p>The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to f... | 0 | 2009-11-11T23:26:25Z | 1,718,841 | <p>The model should be your entity classes, or simply classes that model the problem domain you're working with. And the view anything basically having to do with how your user interacts with the system you're building. The controller marries the two.</p>
| 2 | 2009-11-11T23:36:50Z | [
"python",
"model-view-controller"
] |
In the MVC pattern, what goes in the model and what goes in the view? | 1,718,813 | <p>I'm using the MVC pattern to design some data analysis software (in python). I'm not sure whether some functions should go in the model or the controller.</p>
<p>The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to f... | 0 | 2009-11-11T23:26:25Z | 1,718,842 | <p>On your first point, the parsing should go in the model if it's part of the model class; for instance if you have a Configuration model, then the functions to load up configuration belong in the Model. If it's more of a service (e.g. I'm going to import this file in, and then something else is going to do the mappi... | 0 | 2009-11-11T23:37:06Z | [
"python",
"model-view-controller"
] |
In the MVC pattern, what goes in the model and what goes in the view? | 1,718,813 | <p>I'm using the MVC pattern to design some data analysis software (in python). I'm not sure whether some functions should go in the model or the controller.</p>
<p>The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to f... | 0 | 2009-11-11T23:26:25Z | 1,722,109 | <p>to put it simply, model is your data part (the database) and view is your design part (html, css, js, etc) while a controller is contract between the model and view :)</p>
| 0 | 2009-11-12T13:16:05Z | [
"python",
"model-view-controller"
] |
Run a process and quit without waiting for it | 1,718,899 | <p>In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:</p>
<pre><code>from multiprocessing import Process
from time import sleep
def count_sheeps(number):
"""Count all them sheeps."""
for sheep in range(number):
sleep(1... | 4 | 2009-11-11T23:50:29Z | 1,718,933 | <p>Use the <code>subprocess</code> module as other subprocess control methods (os.system, os.spawn*, os.popen*, popen2.<em>, commands.</em>) are being deprecated:</p>
<pre><code>from subprocess import Popen
Popen( [ "foo.exe", "arg1", "arg2", "arg3" )
</code></pre>
<p><a href="http://docs.python.org/library/subproces... | 2 | 2009-11-11T23:57:57Z | [
"python",
"windows"
] |
Run a process and quit without waiting for it | 1,718,899 | <p>In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:</p>
<pre><code>from multiprocessing import Process
from time import sleep
def count_sheeps(number):
"""Count all them sheeps."""
for sheep in range(number):
sleep(1... | 4 | 2009-11-11T23:50:29Z | 1,719,052 | <p>Under Linux you could <code>fork</code> but this won't work on Windows. I think the easiest way is to run a new Python process, by putting your <code>count_sheeps</code> in a seperate file and <code>Popen('python count_sheeps.py')</code> </p>
| 1 | 2009-11-12T00:29:10Z | [
"python",
"windows"
] |
Run a process and quit without waiting for it | 1,718,899 | <p>In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:</p>
<pre><code>from multiprocessing import Process
from time import sleep
def count_sheeps(number):
"""Count all them sheeps."""
for sheep in range(number):
sleep(1... | 4 | 2009-11-11T23:50:29Z | 1,719,248 | <p>You can always start a new thread, and call myNewThread.daemon(True) before invoking it's start() method.</p>
<p>That thread will continue to run when the main process exits.</p>
| -2 | 2009-11-12T01:16:46Z | [
"python",
"windows"
] |
Run a process and quit without waiting for it | 1,718,899 | <p>In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:</p>
<pre><code>from multiprocessing import Process
from time import sleep
def count_sheeps(number):
"""Count all them sheeps."""
for sheep in range(number):
sleep(1... | 4 | 2009-11-11T23:50:29Z | 19,860,318 | <p>You can declare the process as daemon with <code>p.daemon = True</code>. As <a href="http://docs.python.org/2/library/threading.html#thread-objects" rel="nofollow">http://docs.python.org/2/library/threading.html#thread-objects</a> says: "The significance of this flag is that the entire Python program exits when only... | 1 | 2013-11-08T13:33:06Z | [
"python",
"windows"
] |
What do square brackets, "[]", mean in function/class documentation? | 1,718,903 | <p>I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.</p>
<p>From the docmentation:</p>
<pre><code>class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
</code></pre>
<p>I'd appr... | 13 | 2009-11-11T23:50:58Z | 1,718,913 | <p>The square brackets indicate that these arguments are <strong>optional</strong>. You can leave them out.</p>
<p>So, in this case you are only <em>required</em> to pass the <code>csvfile</code> argument to <code>csv.DictReader</code>. If you would pass a second parameter, it would be interpreted as the <code>fieldna... | 11 | 2009-11-11T23:52:51Z | [
"python"
] |
What do square brackets, "[]", mean in function/class documentation? | 1,718,903 | <p>I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.</p>
<p>From the docmentation:</p>
<pre><code>class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
</code></pre>
<p>I'd appr... | 13 | 2009-11-11T23:50:58Z | 1,718,916 | <p>Usually in api documentation square brackets mean optional. I would think they mean the same here.</p>
| 2 | 2009-11-11T23:53:13Z | [
"python"
] |
What do square brackets, "[]", mean in function/class documentation? | 1,718,903 | <p>I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.</p>
<p>From the docmentation:</p>
<pre><code>class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
</code></pre>
<p>I'd appr... | 13 | 2009-11-11T23:50:58Z | 1,718,977 | <p>To reiterate what the others have said, the arguments are optional.</p>
<p>If you leave out optional parts, the remaining <code>fieldnames=</code>, <code>restval=</code>, <code>restkey=</code> or <code>dialect=</code> keywords tell the function which parts are missing.</p>
<p>The syntax doesn't suggest it, but I w... | 1 | 2009-11-12T00:07:55Z | [
"python"
] |
What do square brackets, "[]", mean in function/class documentation? | 1,718,903 | <p>I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.</p>
<p>From the docmentation:</p>
<pre><code>class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
</code></pre>
<p>I'd appr... | 13 | 2009-11-11T23:50:58Z | 2,119,988 | <p>This is actually a subset of the widely used notation to unambiguously describe language syntax called <a href="http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form" rel="nofollow">Backus-Naur Form</a> (see Wikipedia article for details).</p>
| 2 | 2010-01-22T19:44:12Z | [
"python"
] |
Multiple rows share a value in a column, how do I put all of these rows into one single row? | 1,719,068 | <p>I'm working with a text file that looks something like this:</p>
<pre>
rs001 EEE /n
rs008 EEE /n
rs345 EEE /n
rs542 CHG /n
re432 CHG /n
</pre>
<p>I want to be able to collapse all of the rows that share the same value in column 2 into one single row (for example, <code>rs001 rs008 rs345 EEE</code>). Is ther... | 0 | 2009-11-12T00:32:00Z | 1,719,134 | <pre><code>#!/usr/bin/env python
from __future__ import with_statement
from itertools import groupby
with open('file','r') as f:
# We define "it" to be an iterator, for each line
# it yields pairs like ('rs001','EEE')
it=(line.strip().split() for line in f)
# groupby does the heave work.
# lambda p... | 2 | 2009-11-12T00:45:42Z | [
"python",
"unix",
"text",
"row"
] |
Multiple rows share a value in a column, how do I put all of these rows into one single row? | 1,719,068 | <p>I'm working with a text file that looks something like this:</p>
<pre>
rs001 EEE /n
rs008 EEE /n
rs345 EEE /n
rs542 CHG /n
re432 CHG /n
</pre>
<p>I want to be able to collapse all of the rows that share the same value in column 2 into one single row (for example, <code>rs001 rs008 rs345 EEE</code>). Is ther... | 0 | 2009-11-12T00:32:00Z | 1,719,479 | <p>One option is to build a dictionary keyed on the column 2 data:</p>
<pre><code>from collections import defaultdict #defaultdict will save a line or two of code
d = defaultdict(list) # goal is for d to look like {'EEE':['rs001', 'rs008', ...
for line in file('data.txt', 'r'):
v, k = line.strip().split()
d... | 0 | 2009-11-12T02:15:11Z | [
"python",
"unix",
"text",
"row"
] |
Multiple rows share a value in a column, how do I put all of these rows into one single row? | 1,719,068 | <p>I'm working with a text file that looks something like this:</p>
<pre>
rs001 EEE /n
rs008 EEE /n
rs345 EEE /n
rs542 CHG /n
re432 CHG /n
</pre>
<p>I want to be able to collapse all of the rows that share the same value in column 2 into one single row (for example, <code>rs001 rs008 rs345 EEE</code>). Is ther... | 0 | 2009-11-12T00:32:00Z | 1,719,567 | <p>here's gawk for you</p>
<pre><code>$ awk '{a[$2]=a[$2]FS$1}END{for(i in a)print i,a[i]}' file
EEE rs001 rs008 rs345
CHG rs542 re432
</code></pre>
| 0 | 2009-11-12T02:46:44Z | [
"python",
"unix",
"text",
"row"
] |
Python website convert into Adobe Dreamweaver CS3 | 1,719,127 | <p>I am comfortable in Adobe Dreamweaver CS3. Is there a way to convert a website written in the Python language into Dreamweaver for those who aren't familiar with writing in code?</p>
| 0 | 2009-11-12T00:44:11Z | 1,719,141 | <p>Assuming that any functionality needs to remain intact⦠no.</p>
| 1 | 2009-11-12T00:46:51Z | [
"python",
"dreamweaver"
] |
Python website convert into Adobe Dreamweaver CS3 | 1,719,127 | <p>I am comfortable in Adobe Dreamweaver CS3. Is there a way to convert a website written in the Python language into Dreamweaver for those who aren't familiar with writing in code?</p>
| 0 | 2009-11-12T00:44:11Z | 1,719,178 | <p>Well, you can simply copy the HTML that Python generates to make a static copy of the website, but you'll lose any interactivity. In other words, you won't be able to use the website's administrative panel to modify anything. It will let you modify the style of the website, however.</p>
| 0 | 2009-11-12T00:57:59Z | [
"python",
"dreamweaver"
] |
Python website convert into Adobe Dreamweaver CS3 | 1,719,127 | <p>I am comfortable in Adobe Dreamweaver CS3. Is there a way to convert a website written in the Python language into Dreamweaver for those who aren't familiar with writing in code?</p>
| 0 | 2009-11-12T00:44:11Z | 1,719,759 | <p>If you mean a tool which can convert a python site into dreamweaver, not possible yet, such intelligent machines are not yet invented, but evolution has produced you,<br>
so what you can do is see the site page by page, and make it again in dreamweaver. If you have specs and designs of python site handy that would s... | 1 | 2009-11-12T03:48:48Z | [
"python",
"dreamweaver"
] |
javascript error: "data.getElementsByTagName is not a function" | 1,719,161 | <p>I've spent hours on this stupid error, so any help would be appreciated!</p>
<p>I'm using Jquery to request xml from a python file hosted on google appengine. I'm then trying to process the xml.</p>
<p>Here's the response to the post request obtained from firebug:</p>
<pre><code><?xml version="1.0" encoding="I... | 0 | 2009-11-12T00:52:48Z | 1,719,225 | <p>Try to force jQuery to recognize the returned data as xml by using</p>
<pre><code>jQuery.post(toLoad, formInput,
function(data, textStatus) {
// now check if data is set and what the status is
alert(data);
alert(textStatus);
//alert(data.getElementsByTagName("building"));
},
'xml'
);
</code></... | 1 | 2009-11-12T01:09:59Z | [
"javascript",
"python",
"xml"
] |
javascript error: "data.getElementsByTagName is not a function" | 1,719,161 | <p>I've spent hours on this stupid error, so any help would be appreciated!</p>
<p>I'm using Jquery to request xml from a python file hosted on google appengine. I'm then trying to process the xml.</p>
<p>Here's the response to the post request obtained from firebug:</p>
<pre><code><?xml version="1.0" encoding="I... | 0 | 2009-11-12T00:52:48Z | 1,719,232 | <p>Well, Time to go through a checklist of sorts.</p>
<p>I'm going to assume that data is properly assigned and that you have verified that it contains you "data". Now since it is giving you an error that the function does not exist we then know that it truly hasn't been found for some reason, because otherwise the fu... | 0 | 2009-11-12T01:11:37Z | [
"javascript",
"python",
"xml"
] |
javascript error: "data.getElementsByTagName is not a function" | 1,719,161 | <p>I've spent hours on this stupid error, so any help would be appreciated!</p>
<p>I'm using Jquery to request xml from a python file hosted on google appengine. I'm then trying to process the xml.</p>
<p>Here's the response to the post request obtained from firebug:</p>
<pre><code><?xml version="1.0" encoding="I... | 0 | 2009-11-12T00:52:48Z | 1,719,438 | <p>The response from the GAE server is wrong. It has the headers <em>below</em> the XML data, as part of the response body. That wouldn't be a valid XML document; without the headers appearing properly at the top, there's no active Content-Type header to tell jQuery that the incoming document is XML. Consequently it is... | 0 | 2009-11-12T02:05:26Z | [
"javascript",
"python",
"xml"
] |
Jython exception handling within loops | 1,719,262 | <p>I am using Marathon 2.0b4 to automate tests for an application.</p>
<p>A shortcoming of <code>wait_p</code>, one of the script elements provided by Marathon, is that its default timeout is <strong>hardcoded</strong> to be 60 seconds. I needed a larger timeout due to the long loading times in my application.<br>
[I ... | 2 | 2009-11-12T01:21:11Z | 1,719,271 | <p>Two things:</p>
<ul>
<li><code>range(1, times)</code> should almost certainly be <code>range(times)</code>; what you wrote is equivalent to <code>for (int i=1; i < times; i++)</code></li>
<li>Because of what I just explained, <code>if (i < times)</code> will always be <code>True</code> in your <code>except</c... | 2 | 2009-11-12T01:24:42Z | [
"python",
"exception-handling",
"jython",
"automated-tests"
] |
Jython exception handling within loops | 1,719,262 | <p>I am using Marathon 2.0b4 to automate tests for an application.</p>
<p>A shortcoming of <code>wait_p</code>, one of the script elements provided by Marathon, is that its default timeout is <strong>hardcoded</strong> to be 60 seconds. I needed a larger timeout due to the long loading times in my application.<br>
[I ... | 2 | 2009-11-12T01:21:11Z | 1,719,660 | <p>@Hank's explanation is correct, but I would suggest a different approach:</p>
<pre><code>def wait_p_long(times, compID_name, ppty_name, ppty_value, compID_cell=None):
from marathon.playback import *
for i in range(times-1):
try:
wait_p(compID_name, ppty_name, ppty_value, compID_cell)... | 3 | 2009-11-12T03:15:14Z | [
"python",
"exception-handling",
"jython",
"automated-tests"
] |
Are there database testing tools for python (like sqlunit)? | 1,719,279 | <p>Are there database testing tools for python (like sqlunit)? I want to test the DAL that is built using sqlalchemy</p>
| 4 | 2009-11-12T01:27:17Z | 1,719,347 | <p>Follow the design pattern that Django uses.</p>
<ol>
<li><p>Create a disposable copy of the database. Use SQLite3 in-memory, for example.</p></li>
<li><p>Create the database using the SQLAlchemy table and index definitions. This should be a fairly trivial exercise.</p></li>
<li><p>Load the test data fixture into ... | 4 | 2009-11-12T01:44:58Z | [
"python",
"database",
"testing",
"sqlalchemy"
] |
Python decorators and class methods and evaluation -- django memoize | 1,719,527 | <p>I have a working memoize decorator which uses Django's cache backend to remember the result of a function for a certain amount of time. I am specifically applying this to a class method.</p>
<p>My decorator looks like:</p>
<pre><code>def memoize(prefix='mysite', timeout=300, keygenfunc=None):
# MUST SPECIFY A... | 3 | 2009-11-12T02:32:57Z | 1,719,639 | <p>Descriptors must always be set on the class, not on the instance (see <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">the how-to guide</a> for all details). Of course, in this case you're not even setting it on the instance, but rather on another function (and fetching it as an attribut... | 2 | 2009-11-12T03:09:49Z | [
"python",
"class",
"scope",
"methods",
"decorator"
] |
Python decorators and class methods and evaluation -- django memoize | 1,719,527 | <p>I have a working memoize decorator which uses Django's cache backend to remember the result of a function for a certain amount of time. I am specifically applying this to a class method.</p>
<p>My decorator looks like:</p>
<pre><code>def memoize(prefix='mysite', timeout=300, keygenfunc=None):
# MUST SPECIFY A... | 3 | 2009-11-12T02:32:57Z | 1,719,919 | <p>While I agree with AlexM, I did have some spare time and thought this would be interesting:</p>
<pre><code># from django.whereever import cache
class memoize(object):
def __init__(self,prefix='mysite', timeout=300, keygenfunc=None):
class memo_descriptor(object):
def __init__(self,func):
... | -1 | 2009-11-12T04:39:55Z | [
"python",
"class",
"scope",
"methods",
"decorator"
] |
Python organizing data with multiple dictionaries | 1,719,742 | <p>I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: <code>connected[socket] = account_data</code>. Bas... | 3 | 2009-11-12T03:42:50Z | 1,719,755 | <p>Maybe one of the publish/subscribe modules for Python can help you here?
See <a href="http://stackoverflow.com/questions/115844/recommended-python-publish-subscribe-dispatch-module">this question</a>.</p>
| 0 | 2009-11-12T03:47:52Z | [
"python",
"dictionary",
"grouping"
] |
Python organizing data with multiple dictionaries | 1,719,742 | <p>I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: <code>connected[socket] = account_data</code>. Bas... | 3 | 2009-11-12T03:42:50Z | 1,719,757 | <p>If you have references to dictionaries, an update to the dictionary will be reflected to everything with a reference.</p>
<p>A customer connects and retains a socket, <code>sock</code>. You load his account and stick it in <code>connections[sock]</code>. Then you keep a dictionary of account IDs (the other way) wi... | 0 | 2009-11-12T03:48:44Z | [
"python",
"dictionary",
"grouping"
] |
Python organizing data with multiple dictionaries | 1,719,742 | <p>I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: <code>connected[socket] = account_data</code>. Bas... | 3 | 2009-11-12T03:42:50Z | 1,719,762 | <p>First off, the data, needn't be be replicated. You can well have 3 dictionaries each using a different key, but having the same reference as its value.</p>
<p>Doing so you only need to change the value object once and this will be reflected in all dictionaries (or more precisely since the the dictionaries only sto... | 2 | 2009-11-12T03:48:58Z | [
"python",
"dictionary",
"grouping"
] |
Python organizing data with multiple dictionaries | 1,719,742 | <p>I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: <code>connected[socket] = account_data</code>. Bas... | 3 | 2009-11-12T03:42:50Z | 1,719,782 | <p>Just do something like:</p>
<pre><code>connected[socket] = accountids[account_data.accountid] = account_data
</code></pre>
<p>assuming <code>account_data</code> is a mutable object with attributes, this will reference that same object as a value in both dicts, with different keys of course. It doesn't <em>have</e... | 1 | 2009-11-12T03:56:39Z | [
"python",
"dictionary",
"grouping"
] |
Euler #26, how to convert rational number to string with better precision? | 1,719,776 | <p>I want to get <code>1/7</code> with better precision, but it got truncated. How can I get better precision when I convert a rational number?</p>
<pre><code>>>> str(1.0/7)[:50]
'0.142857142857'
</code></pre>
| 7 | 2009-11-12T03:54:10Z | 1,719,806 | <p>You could multiply the numerator by a large 10^N and stick with arbitrary-precision integers.</p>
<p><b>EDIT</b></p>
<p>i mean:</p>
<pre><code>> def digits(a,b,n=50): return a*10**n/b
.
> digits(1,7)
14285714285714285714285714285714285714285714285714L
</code></pre>
<p>Python's integers are arbitrary precis... | 6 | 2009-11-12T04:04:13Z | [
"python",
"floating-point",
"floating-point-precision"
] |
Euler #26, how to convert rational number to string with better precision? | 1,719,776 | <p>I want to get <code>1/7</code> with better precision, but it got truncated. How can I get better precision when I convert a rational number?</p>
<pre><code>>>> str(1.0/7)[:50]
'0.142857142857'
</code></pre>
| 7 | 2009-11-12T03:54:10Z | 1,719,817 | <p>Using Perl (because I can't write Python ;-):</p>
<pre><code>use strict; use warnings;
use integer;
my $x = 1;
my $y = 7;
for (1 .. 50) {
$x *= 10 if $x < $y;
my $q = $x / $y;
$x -= $q * $y;
print $q;
}
print "\n";
</code></pre>
<pre>
14285714285714285714285714285714285714285714285714
</pre>... | 3 | 2009-11-12T04:08:13Z | [
"python",
"floating-point",
"floating-point-precision"
] |
Euler #26, how to convert rational number to string with better precision? | 1,719,776 | <p>I want to get <code>1/7</code> with better precision, but it got truncated. How can I get better precision when I convert a rational number?</p>
<pre><code>>>> str(1.0/7)[:50]
'0.142857142857'
</code></pre>
| 7 | 2009-11-12T03:54:10Z | 1,719,825 | <p>With <a href="http://code.google.com/p/gmpy/" rel="nofollow">gmpy</a>:</p>
<pre><code>>>> import gmpy
>>> thefraction = gmpy.mpq(1, 7)
>>> hiprecfloat = gmpy.mpf(thefraction, 256)
>>> hiprecfloat.digits(10, 50, -10, 10)
'0.14285714285714285714285714285714285714285714285714'
>&... | 2 | 2009-11-12T04:10:08Z | [
"python",
"floating-point",
"floating-point-precision"
] |
Euler #26, how to convert rational number to string with better precision? | 1,719,776 | <p>I want to get <code>1/7</code> with better precision, but it got truncated. How can I get better precision when I convert a rational number?</p>
<pre><code>>>> str(1.0/7)[:50]
'0.142857142857'
</code></pre>
| 7 | 2009-11-12T03:54:10Z | 1,719,903 | <p>Python has a built-in library for arbitrary-precision calculations: Decimal. For example:</p>
<pre><code>>>>from decimal import Decimal, getcontext
>>>getcontext().prec = 50
>>>x = Decimal(1)/Decimal(7)
>>>x
Decimal('0.14285714285714285714285714285714285714285714285714')
>>... | 9 | 2009-11-12T04:34:44Z | [
"python",
"floating-point",
"floating-point-precision"
] |
Classify array of strings based on commonalities | 1,719,865 | <p>I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this</p>
<p>"<strong>AB 500</strong>"<br>
"Bus <strong>AB 500</strong>"<br>
"<strong>News CA</strong>"<br>
"<strong>Ne... | 1 | 2009-11-12T04:22:55Z | 1,719,979 | <p>Do you mean something like this?</p>
<pre><code>>>> from collections import defaultdict
>>> L=["AB 500",
... "Bus AB 500",
... "News CA",
... "News CA BLAH"]
>>> d=defaultdict(list)
>>> for s in L:
... for w in s.split():
... d[w].append(s)
...
>>> print d["... | 1 | 2009-11-12T04:57:51Z | [
"python",
"string",
"algorithm",
"classification"
] |
Classify array of strings based on commonalities | 1,719,865 | <p>I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this</p>
<p>"<strong>AB 500</strong>"<br>
"Bus <strong>AB 500</strong>"<br>
"<strong>News CA</strong>"<br>
"<strong>Ne... | 1 | 2009-11-12T04:22:55Z | 1,719,984 | <p>200000 is not that much, you can do this</p>
<ol>
<li>Split each string to get tokens
e.g. "News CA BLAH" -> ["Blah", "CA", "News"]</li>
<li>create a dict entry each length of list e.g. in case of ["Blah", "CA", "News"] all combinations in order</li>
<li>Now just loop thru the dict and see the groups</li>
</ol>
<p... | 2 | 2009-11-12T04:58:55Z | [
"python",
"string",
"algorithm",
"classification"
] |
Classify array of strings based on commonalities | 1,719,865 | <p>I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this</p>
<p>"<strong>AB 500</strong>"<br>
"Bus <strong>AB 500</strong>"<br>
"<strong>News CA</strong>"<br>
"<strong>Ne... | 1 | 2009-11-12T04:22:55Z | 1,720,092 | <p>Unless repetition of words is an important feature for your use case, I suggest sets. I.e.:</p>
<pre><code>thestrings = [
"AB 500",
"Bus AB 500",
"News CA",
"News CA BLAH",
]
thesets = dict((s, set(s.split())) for s in thestrings)
similarities = dict()
for s in thestrings:
for o in thestrings:
if s>=o: ... | 1 | 2009-11-12T05:30:10Z | [
"python",
"string",
"algorithm",
"classification"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.