title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Something wrong with output from list in Python | 743,248 | <p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p>
<pre><code>A Alfa
B Betta
C Charlie
</code></pre>
<p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie... | 2 | 2009-04-13T07:16:48Z | 744,098 | <p>Slightly meta-answer(?) to <a href="http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743313#743313">Autoplectic's</a> suggestion of using <code>zip()</code></p>
<p>With 3 lines in the input file (from the supplied data in the question):</p>
<p>The <code>zip()</code> method ... | 1 | 2009-04-13T14:37:42Z | [
"python",
"list",
"text"
] |
how to convert string representation bytes back to bytes? | 743,374 | <p>I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[].</p>
<p>its type in SOAP is:</p>
<pre><code><s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" />
</code></pre>
<p>sample client codes:</p>
<... | 1 | 2009-04-13T08:42:41Z | 743,381 | <p>As the SOAP element says, the bytes are <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">base64-encoded</a>.</p>
<p>To decode, use the python module
<a href="http://docs.python.org/library/base64.html" rel="nofollow"><code>base64</code></a>.</p>
| 3 | 2009-04-13T08:47:05Z | [
"python",
"web-services"
] |
how to convert string representation bytes back to bytes? | 743,374 | <p>I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[].</p>
<p>its type in SOAP is:</p>
<pre><code><s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" />
</code></pre>
<p>sample client codes:</p>
<... | 1 | 2009-04-13T08:42:41Z | 743,410 | <p>I need to convert it back to string with the binascii module, like:</p>
<pre><code>>>> btxt = binascii.a2b_base64(page.rawByte)
</code></pre>
<p>then btxt can be treated as a normal string.</p>
| 2 | 2009-04-13T09:07:06Z | [
"python",
"web-services"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 743,807 | <p>Splits the string in <code>text</code> on delimiter: <code>" "</code>.</p>
<pre><code>words = text.split()
</code></pre>
<p>Split the string in <code>text</code> on delimiter: <code>","</code>.</p>
<pre><code>words = text.split(",")
</code></pre>
<p>The words variable will be a list datatype and contain... | 196 | 2009-04-13T12:50:21Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 743,823 | <pre><code>text.split()
</code></pre>
<p>This should be enough to store each word in a list. <code>words</code> is already a list of the words from the sentence, so there is no need for the loop.</p>
<p>Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it wo... | 178 | 2009-04-13T12:54:16Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 743,824 | <p><a href="https://docs.python.org/2/library/stdtypes.html#str.split">str.split()</a></p>
<blockquote>
<p>Return a <strong>list of the words</strong> in the string, using sep as the delimiter
... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are re... | 47 | 2009-04-13T12:54:58Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 743,865 | <p>I think you are confused because of a typo. </p>
<p>Replace <code>print(words)</code> with <code>print(word)</code> inside your loop to have every word printed on a different line</p>
| 1 | 2009-04-13T13:17:13Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 743,922 | <blockquote>
<p>I want my python function to split a sentence (input) and store each word in a list</p>
</blockquote>
<p>The <code>str().split()</code> method does this, it takes a string, splits it into a list:</p>
<pre><code>>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")... | 9 | 2009-04-13T13:46:06Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 744,046 | <p>Depending on what you plan to do with your sentence-as-a-list, you may want to look at the <a href="http://www.nltk.org/">Natural Language Took Kit</a>. It deals heavily with text processing and evaluation. You can also use it to solve your problem:</p>
<pre><code>import nltk
words = nltk.word_tokenize(raw_sentenc... | 35 | 2009-04-13T14:24:18Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 17,951,315 | <p>How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as <code>we're</code>.</p>
<pre><code>>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're m... | 16 | 2013-07-30T15:32:43Z | [
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python | 743,806 | <p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
... | 217 | 2009-04-13T12:48:44Z | 20,270,958 | <p><a href="https://docs.python.org/library/shlex.html" rel="nofollow">shlex</a> has a <a href="https://docs.python.org/library/shlex.html#shlex.split" rel="nofollow"><code>.split()</code></a> function. It differs from <code>str.split()</code> in that it does not preserve quotes and treats a quoted phrase as a single w... | 6 | 2013-11-28T16:33:44Z | [
"python",
"list",
"split",
"text-segmentation"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 744,170 | <p>The random class is quite powerful in python. You can generate a list with the characters desired at the appropriate weights and then use random.choice to obtain a selection. </p>
<p>First, make sure you do an import random.</p>
<p>For example, let's say you wanted a truly random string from A,B,C, or D.
1. Genera... | 2 | 2009-04-13T15:00:50Z | [
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 744,201 | <p>For four letters, here's something quick off the top of my head:</p>
<pre><code>from random import random
def randABCD(n, pA, pB, pC, pD):
# assumes pA + pB + pC + pD == 1
cA = pA
cB = cA + pB
cC = cB + pC
def choose():
r = random()
if r < cA:
return 'A'
el... | 2 | 2009-04-13T15:11:11Z | [
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 744,222 | <p>Here is a rough idea of what might suit you</p>
<pre><code>import random as r
def distributed_choice(probs):
r= r.random()
cum = 0.0
for pair in probs:
if (r < cum + pair[1]):
return pair[0]
cum += pair[1]
</code></pre>
<p>The parameter <code>probs</code> takes a list of pair... | 0 | 2009-04-13T15:16:33Z | [
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 744,233 | <p>Here's the code to select a single weighted value. You should be able to take it from here. It uses <a href="http://docs.python.org/library/bisect.html#bisect.bisect" rel="nofollow">bisect</a> and <a href="http://docs.python.org/library/random.html#random.random" rel="nofollow">random</a> to accomplish the work.</... | 4 | 2009-04-13T15:20:34Z | [
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 744,240 | <p>Hmm, something like:</p>
<pre><code>import random
class RandomDistribution:
def __init__(self, kv):
self.entries = kv.keys()
self.where = []
cnt = 0
for x in self.entries:
self.where.append(cnt)
cnt += kv[x]
self.where.append(cnt)
def find(... | 0 | 2009-04-13T15:21:31Z | [
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters | 744,127 | <p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working prog... | 2 | 2009-04-13T14:48:24Z | 747,392 | <p>Thank you all for your help, I was able to figure something out, mostly with this info.
For my particular need, I did something like this:</p>
<pre><code>import random
#Create a function to randomize a given string
def makerandom(seq):
return ''.join(random.sample(seq, len(seq)))
def randomDNA(n, probA=0.25, p... | 0 | 2009-04-14T12:50:06Z | [
"python",
"random"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,269 | <p>I would use memory-maping: <a href="http://docs.python.org/library/mmap.html" rel="nofollow">http://docs.python.org/library/mmap.html</a>.<br />
This way you can use the file as if it's stored in memory, but the OS decides which pages should actually be read from the file.</p>
| 3 | 2009-04-13T15:32:40Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,272 | <p>It's not clear what "list[pointer]" is all about. Consider this, however.</p>
<pre><code>from collections import defaultdict
keyValues= defaultdict(list)
targetKeys= # some list of keys
for line in fin:
key, value = map( int, line.split())
if key in targetKeys:
keyValues[key].append( value )
</code... | 4 | 2009-04-13T15:33:48Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,284 | <p>If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up.</p>
| 11 | 2009-04-13T15:37:33Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,296 | <p>One possible optimization is to do a bit of buffering using the <code>sizehint</code> option in <a href="http://docs.python.org/library/stdtypes.html#file.readlines" rel="nofollow">file.readlines(..)</a>. This allows you to load multiple lines in memory totaling to approximately <code>sizehint</code> bytes.</p>
| 0 | 2009-04-13T15:40:51Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,309 | <p>Slight optimization of S.Lotts answer:</p>
<pre><code>from collections import defaultdict
keyValues= defaultdict(list)
targetKeys= # some list of keys as strings
for line in fin:
key, value = line.split()
if key in targetKeys:
keyValues[key].append( value )
</code></pre>
<p>Since we're using a dict... | 7 | 2009-04-13T15:46:13Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,332 | <p>If you have any control over the format of the file, the "sort and binary search" responses are correct. The detail is that this only works with records of a fixed size and offset (well, I should say it only works easily with fixed length records).</p>
<p>With fixed length records, you can easily seek() around the ... | 2 | 2009-04-13T15:53:55Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,342 | <p>You need to implement binary search using seek()</p>
| 0 | 2009-04-13T15:56:12Z | [
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python | 744,256 | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more e... | 12 | 2009-04-13T15:28:04Z | 744,487 | <p>Here is a recursive binary search on the text file</p>
<pre><code>import os, stat
class IntegerKeyTextFile(object):
def __init__(self, filename):
self.filename = filename
self.f = open(self.filename, 'r')
self.getStatinfo()
def getStatinfo(self):
self.statinfo = os.stat(sel... | 2 | 2009-04-13T16:35:18Z | [
"python",
"performance",
"file-io",
"large-files"
] |
email whitelist/blacklist in python/django | 744,308 | <p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specifi... | 1 | 2009-04-13T15:46:11Z | 744,334 | <p>[Please start All Class Names With Upper Case Letters.]</p>
<p>Your code doesn't make use of your class distinction very well. </p>
<p>Specifically, your classes don't have any different behavior. Since both classes have all the same methods, it isn't clear <em>why</em> these are two different classes in the fir... | 3 | 2009-04-13T15:54:41Z | [
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
email whitelist/blacklist in python/django | 744,308 | <p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specifi... | 1 | 2009-04-13T15:46:11Z | 745,599 | <p>I would restructure it so both lists were contained in one model.</p>
<pre><code>class PermissionList(models.Model):
setter = models.ManyToManyField(User)
email = models.EmailField(unique=True) #don't want conflicting results
permission = models.BooleanField()
</code></pre>
<p>Then, your lists would ju... | 5 | 2009-04-13T22:17:36Z | [
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
email whitelist/blacklist in python/django | 744,308 | <p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specifi... | 1 | 2009-04-13T15:46:11Z | 28,287,010 | <p>This class compares an email address with a blacklist of email domains. If you preffer you can download this module using <a href="https://pypi.python.org/pypi?:action=display&name=django-email-blacklist&version=1.0.1" rel="nofollow">pip install django-email-blacklist</a>.</p>
<pre><code>from django.conf im... | 0 | 2015-02-02T21:22:17Z | [
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
Imports in python are static, any solution? | 744,325 | <p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4 | 2009-04-13T15:52:59Z | 744,343 | <p>You could call a function instead of referencing a global variable. </p>
| 0 | 2009-04-13T15:56:22Z | [
"python"
] |
Imports in python are static, any solution? | 744,325 | <p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4 | 2009-04-13T15:52:59Z | 744,369 | <p>What Ross is saying is to restucture foo like so:</p>
<pre><code>_i = 10
def getI():
return _i
def fi():
global _i
_i = 99
</code></pre>
<p>Then you will see it works the way you want:</p>
<pre><code>>>> import foo
>>> print foo.getI()
10
>>> foo.fi()
>>> print fo... | 8 | 2009-04-13T16:05:56Z | [
"python"
] |
Imports in python are static, any solution? | 744,325 | <p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4 | 2009-04-13T15:52:59Z | 744,407 | <p>What <code>import</code> does in <code>bar.py</code> is set up an identifier called <code>i</code> in the <code>bar.py</code> module namespace that points to the same address as the identifier called <code>i</code> in the <code>foo.py</code> module namespace.</p>
<p>This is an important distinction... <code>bar.i</... | 7 | 2009-04-13T16:15:33Z | [
"python"
] |
Imports in python are static, any solution? | 744,325 | <p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4 | 2009-04-13T15:52:59Z | 744,615 | <p><code>i</code> inside <code>foo.py</code> is a <strong>different</strong> <code>i</code> from the one in <code>bar.py</code>. When in <code>bar.py</code> you do:</p>
<pre><code>from foo import i
</code></pre>
<p>That creates a new <code>i</code> in <code>bar.py</code> that <em>refers to the same object</em> as the... | 3 | 2009-04-13T17:10:17Z | [
"python"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 744,403 | <p>There was a really good discussion on this over at <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d80a1c6db2b867c">comp.lang.python</a> last year. It answers your question pretty thoroughly.</p>
<blockquote>
<p>Imports are pretty straightforward really. Just remember the following:... | 183 | 2009-04-13T16:15:00Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 744,410 | <p>Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.</p>
<p>Consider the following files:</p>
<p>a.py:</p>
<pre><code>print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"
</code></pre>
<p>b.py:</p>
... | 63 | 2009-04-13T16:16:23Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 746,067 | <p>If you do <code>import foo</code> inside <code>bar</code> and <code>import bar</code> inside <code>foo</code>, it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.</p>
<p>The problem is when instead you do <code>from foo import abc</code> a... | 155 | 2009-04-14T02:03:43Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 746,655 | <p>I got an example here that struck me!</p>
<p><strong>foo.py</strong></p>
<pre><code>import bar
class gX(object):
g = 10
</code></pre>
<p><strong>bar.py</strong></p>
<pre><code>from foo import gX
o = gX()
</code></pre>
<p><strong>main.py</strong></p>
<pre><code>import foo
import bar
print "all done"
</co... | 3 | 2009-04-14T07:30:51Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 28,356,950 | <p>Ok, I think I have a pretty cool solution.
Let's say you have file <code>a</code> and file <code>b</code>.
You have a <code>def</code> or a <code>class</code> in file <code>b</code> that you want to use in module <code>a</code>, but you have something else, either a <code>def</code>, <code>class</code>, or variable ... | -3 | 2015-02-06T01:07:27Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python | 744,373 | <p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197 | 2009-04-13T16:07:07Z | 33,547,682 | <p>As other answers describe this pattern is acceptable in python:</p>
<pre><code>def dostuff(self):
from foo import bar
...
</code></pre>
<p>Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.</p>... | 11 | 2015-11-05T14:51:51Z | [
"python",
"circular-dependency",
"cyclic-reference"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 744,439 | <p>If the order doesn't matter, use a dict.</p>
| 0 | 2009-04-13T16:24:46Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 744,454 | <blockquote>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
</blockquote>
<p>That's exactly what I would do if you were locked into your current structure of making several queries. Then a simply <code>dictionary.values()</code> will return yo... | 6 | 2009-04-13T16:27:26Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 744,586 | <p>You can use a set if you add the <code>__hash__</code> function to your model definition so that it returns the id (assuming this doesn't interfere with other hash behaviour you may have in your app):</p>
<pre><code>class MyModel(models.Model):
def __hash__(self):
return self.pk
</code></pre>
| 3 | 2009-04-13T16:58:21Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 744,745 | <p>Remove "duplicates" depends on how you define "duplicated".</p>
<p>If you want EVERY column (except the PK) to match, that's a pain in the neck -- it's a lot of comparing.</p>
<p>If, on the other hand, you have some "natural key" column (or short set of columns) than you can easily query and remove these.</p>
<pr... | 0 | 2009-04-13T17:44:12Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 747,611 | <p>In general it's better to combine all your queries into a single query if possible. Ie.</p>
<pre><code>q = Model.objects.filter(Q(field1=f1)|Q(field2=f2))
</code></pre>
<p>instead of</p>
<pre><code>q1 = Models.object.filter(field1=f1)
q2 = Models.object.filter(field2=f2)
</code></pre>
<p>If the first query is re... | 12 | 2009-04-14T13:40:00Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | <p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instea... | 6 | 2009-04-13T16:20:47Z | 2,313,391 | <p>I use this one:</p>
<pre><code>dict(zip(map(lambda x: x.pk,items),items)).values()
</code></pre>
| 0 | 2010-02-22T19:08:06Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] |
Getting TTFB (time till first byte) for an HTTP Request | 744,532 | <p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is ... | 5 | 2009-04-13T16:44:06Z | 744,560 | <p>Using your current <code>open</code> / <code>read</code> pair there's only one other timing point possible - between the two.</p>
<p>The <code>open()</code> call should be responsible for actually sending the HTTP request, and should (AFAIK) return as soon as that has been sent, ready for your application to actual... | 2 | 2009-04-13T16:51:11Z | [
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request | 744,532 | <p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is ... | 5 | 2009-04-13T16:44:06Z | 744,677 | <p>By default, the implementation of HTTP opening in urllib2 has no callbacks when read is performed. The OOTB opener for the HTTP protocol is <code>urllib2.HTTPHandler</code>, which uses <code>httplib.HTTPResponse</code> to do the actual reading via a socket.</p>
<p>In theory, you could write your own subclasses of H... | 1 | 2009-04-13T17:27:51Z | [
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request | 744,532 | <p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is ... | 5 | 2009-04-13T16:44:06Z | 11,030,969 | <p>To get a good proximity you have to do read(1). And messure the time.</p>
<p>It works pretty well for me.
The ony thing you should keep in mind: python might load more than one byte on the call of read(1). Depending on it's internal buffers. But i think the most tools will behave alike inaccurate.</p>
<pre><code>i... | 1 | 2012-06-14T10:12:53Z | [
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request | 744,532 | <p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is ... | 5 | 2009-04-13T16:44:06Z | 38,915,617 | <p>you should use <code>pycurl</code>, not <code>urllib2</code></p>
<ol>
<li><p>install <code>pyCurl</code>:<br>
you can use pip / easy_install, or install it from source.</p>
<p>easy_install pyCurl</p>
<p>maybe you should be a superuser. </p></li>
<li><p>usage: </p>
<pre><code>import pycurl
import sys
import j... | 1 | 2016-08-12T10:21:47Z | [
"python",
"http",
"urllib2"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,632 | <pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
eval(f+'()')
</code></pre>
<p><em>Edited to add:</em></p>
<p>Yes, eval() generally is a bad idea, but this is what the OP was looking for.</p>
| 2 | 2009-04-13T17:14:58Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,634 | <p>how do you not know the name of the function to call? Store the functions instead of the name:</p>
<pre><code>functions_to_call = [int, str, float]
value = 33.5
for function in functions_to_call:
print "calling", function
print "result:", function(value)
</code></pre>
| 15 | 2009-04-13T17:15:39Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,635 | <p>See the <a href="http://docs.python.org/library/functions.html" rel="nofollow">eval and compile</a> functions.</p>
<blockquote>
<p>This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been... | 1 | 2009-04-13T17:16:03Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,647 | <p>Something like that...when i was looking at function pointers in python..</p>
<pre><code>def myfunc(x):
print x
dict = {
"myfunc": myfunc
}
dict["myfunc"]("hello")
func = dict.get("myfunc")
if callable(func):
func(10)
</code></pre>
| 8 | 2009-04-13T17:17:50Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,686 | <p>You can use the python builtin locals() to get local declarations, eg:</p>
<pre><code>def f():
print "Hello, world"
def g():
print "Goodbye, world"
for fname in ["f", "g"]:
fn = locals()[fname]
print "Calling %s" % (fname)
fn()
</code></pre>
<p>You can use the "imp" module to load functions f... | 19 | 2009-04-13T17:31:15Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 744,687 | <p>Have a look at the getattr function:</p>
<p><a href="http://docs.python.org/library/functions.html?highlight=getattr#getattr" rel="nofollow">http://docs.python.org/library/functions.html?highlight=getattr#getattr</a></p>
<pre><code>import sys
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_... | 6 | 2009-04-13T17:31:22Z | [
"python"
] |
Calling unknown Python functions | 744,626 | <p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6 | 2009-04-13T17:12:47Z | 748,002 | <p>Don't use eval! It's almost never required, functions in python are just attributes like everything else, and are accessible either using <code>getattr</code> on a class, or via <code>locals()</code>:</p>
<pre><code>>>> print locals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': No... | 1 | 2009-04-14T14:56:09Z | [
"python"
] |
Google App Engine--Dynamically created templates | 744,828 | <p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with ... | 0 | 2009-04-13T18:05:52Z | 745,809 | <p>I saw this open source project a while back:
<a href="http://code.google.com/p/gae-django-dbtemplates/" rel="nofollow">http://code.google.com/p/gae-django-dbtemplates/</a></p>
<p>Using a template to generate a template should be fine. Just render the template to a string. Here some code i use so i can stick some... | 1 | 2009-04-13T23:40:59Z | [
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Google App Engine--Dynamically created templates | 744,828 | <p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with ... | 0 | 2009-04-13T18:05:52Z | 747,519 | <p>Yes, instead of doing <code>template.writes</code>, you can generate the next template - since <code>template.render(...)</code> just returns text. You can then store the text returned and put it into the DataStore, then retrieve it later and call <code>.render(Context(...))</code> on it to return the html you wan... | 1 | 2009-04-14T13:19:06Z | [
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Google App Engine--Dynamically created templates | 744,828 | <p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with ... | 0 | 2009-04-13T18:05:52Z | 872,022 | <p>Other option, that in my opinion simplifies writing apps for GAE a lot, is using user other templating language, like <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, that allows you to embed Python code in the template, thus no fiddling required.
You would pass model data to the template (as simple ... | 0 | 2009-05-16T09:08:46Z | [
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Do Python regular expressions allow embedded options? | 744,885 | <p>In particular, I'd like to know if I can specify an embedded option in the pattern string that will enable multiline mode. That is, typically with Python regular expressions multiline mode is enabled like this:</p>
<pre><code>pattern = re.compile(r'foo', re.MULTILINE)
</code></pre>
<p>I'd like a way to get multil... | 4 | 2009-04-13T18:25:02Z | 744,895 | <p>yes.</p>
<p>From the <a href="http://docs.python.org/library/re.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p><strong><code>(?iLmsux)</code></strong> (One or more letters from the set 'i',
'L', 'm', 's', 'u', 'x'.) </p>
<p>The group
matches the empty string; the letters
set the corresponding flag... | 6 | 2009-04-13T18:28:37Z | [
"python",
"regex"
] |
adding comments to pot files automatically | 744,894 | <p>I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>to this pot file:</p>
... | 0 | 2009-04-13T18:27:22Z | 748,267 | <p>I was going to suggest the <code>compiler</code> module, but it ignores comments:</p>
<p>f.py:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>..and the compiler module:</p>
<pre><code>>>> import compiler
>>> m = compiler.p... | 1 | 2009-04-14T16:00:27Z | [
"python",
"localization",
"internationalization"
] |
adding comments to pot files automatically | 744,894 | <p>I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>to this pot file:</p>
... | 0 | 2009-04-13T18:27:22Z | 748,543 | <p>After much pissing about I found the best way to do this:</p>
<pre><code>#. Translators:
# Blah blah blah
_("String")
</code></pre>
<p>Then search for comments with a . like so:</p>
<pre><code>xgettext --language=Python --keyword=_ --add-comments=. --output=test.pot *.py
</code></pre>
| 2 | 2009-04-14T17:15:16Z | [
"python",
"localization",
"internationalization"
] |
Python/Django Modeling Question | 744,921 | <p>What is the best way to have many children records pointing to one parent record in the same model/table in Django?</p>
<p>Is this implementation correct?:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey("TABLE", unique=False)
</code></pre>
| 1 | 2009-04-13T18:36:36Z | 744,936 | <p>Django has a special syntax for ForeignKey for self-joins:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey('self')
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey" rel="nofollow">Source</a> (second par... | 10 | 2009-04-13T18:40:42Z | [
"python",
"database",
"django",
"model"
] |
Python/Django Modeling Question | 744,921 | <p>What is the best way to have many children records pointing to one parent record in the same model/table in Django?</p>
<p>Is this implementation correct?:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey("TABLE", unique=False)
</code></pre>
| 1 | 2009-04-13T18:36:36Z | 744,949 | <p>Two things:</p>
<p>First, you need to allow the possibility of a null value for <code>parent</code>, otherwise your <code>TABLE</code> tree can have no root.</p>
<p>Second, you need to worry about the possibility of "I'm my own grandpa." For a lively discussion, see <a href="http://stackoverflow.com/questions/401... | 2 | 2009-04-13T18:45:15Z | [
"python",
"database",
"django",
"model"
] |
Create function through MySQLdb | 745,538 | <p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 T... | 10 | 2009-04-13T21:54:10Z | 745,575 | <p>The <code>DELIMITER</code> command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use <code>DELIMITER</code> if you execute SQL statements directly through an API.</p>
<p>The purpose of <code>DELIMITER</code> is to help you avoid ambiguity... | 15 | 2009-04-13T22:10:30Z | [
"python",
"mysql"
] |
Create function through MySQLdb | 745,538 | <p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 T... | 10 | 2009-04-13T21:54:10Z | 16,950,944 | <p>To add to the answer by Bill Karwin, the following python code sample can be used to properly execute a string where DELIMITER is used, such as a database creation script.</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
cursor = db.cursor()
dbString = """DELIMITER //
CREATE FUNCTION trivial_func ... | 3 | 2013-06-05T22:27:33Z | [
"python",
"mysql"
] |
Create function through MySQLdb | 745,538 | <p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 T... | 10 | 2009-04-13T21:54:10Z | 28,368,193 | <p>Based on the comment from @AaronS. This script will read in an SQL file, split it into discrete SQL commands and cope with whatever delimiters it finds.</p>
<pre><code> queries = []
delimiter = ';'
query = ''
with open('import.sql', 'r') as f:
for line in f.readlines():
line = lin... | 0 | 2015-02-06T14:39:21Z | [
"python",
"mysql"
] |
semantic markup for Python's difflib.HtmlDiff | 745,600 | <p>It appears Python's <code>difflib.HtmlDiff</code>, rather than using <code>INS</code> and <code>DEL</code>, uses <code>SPAN</code> elements with custom classes:</p>
<pre><code>python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.... | 1 | 2009-04-13T22:17:39Z | 831,443 | <p>The python bug tracker is here: <a href="http://bugs.python.org/" rel="nofollow">http://bugs.python.org/</a></p>
<p>There's no open bug on this issue, which I guess is because most people would not care what sort of html it is as long as it works. If it's important to you, file a bug and submit a patch.</p>
| 2 | 2009-05-06T19:56:07Z | [
"python",
"diff",
"semantics"
] |
semantic markup for Python's difflib.HtmlDiff | 745,600 | <p>It appears Python's <code>difflib.HtmlDiff</code>, rather than using <code>INS</code> and <code>DEL</code>, uses <code>SPAN</code> elements with custom classes:</p>
<pre><code>python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.... | 1 | 2009-04-13T22:17:39Z | 1,976,803 | <p><a href="http://www.aaronsw.com/2002/diff/" rel="nofollow">This script</a> by Aaron Swartz uses difflib to output <code>ins</code>/<code>del</code>.</p>
| 3 | 2009-12-29T20:34:10Z | [
"python",
"diff",
"semantics"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 745,745 | <p>Yes, Python is interpreted, but you can also run them as long-running applications.</p>
| 1 | 2009-04-13T23:16:19Z | [
"python"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 745,749 | <p>There's multiple questions here:</p>
<ol>
<li>No, Python is not interpreted. The standard implementation compiles to bytecode, and then executes in a virtual machine. Many modern JavaScript engines also do this.</li>
<li>Regardless of implementation (interpreter, VM, machine code), anything you want can run in the ... | 47 | 2009-04-13T23:17:31Z | [
"python"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 745,751 | <p>Python is an interpreted language but it is the bytecode which is interpreted at run time. There are also many tools out there that can assist you in making your programs run as a windows service / UNIX daemon.</p>
| 2 | 2009-04-13T23:19:12Z | [
"python"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 745,752 | <p>Yes, it's interpreted, its main implementation compiles bytecode first and then runs it though (kind of if you took a java source and the JVM compiled it before running it). Still, you can run your application in background. Actually, you can run pretty much anything in background.</p>
| 1 | 2009-04-13T23:20:23Z | [
"python"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 745,789 | <p>Technically, Python is compiled to bytecode and then interpreted in a <a href="http://en.wikipedia.org/wiki/Virtual_machine">virtual machine</a>. If the Python compiler is able to write out the bytecode into a .pyc file, it will (usually) do so.</p>
<p>On the other hand, there's no explicit compilation step in Pyth... | 19 | 2009-04-13T23:30:23Z | [
"python"
] |
Is Python interpreted (like Javascript or PHP)? | 745,743 | <p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28 | 2009-04-13T23:15:37Z | 749,218 | <p>As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was when such terms were coined. In fact, it's also something of a mistake to consider <em>languages</em> as being either interpreted or compiled, as different <em>implementations</em> of languages may do di... | 64 | 2009-04-14T20:23:11Z | [
"python"
] |
How to write ampersand in node attribude? | 746,602 | <p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate... | 0 | 2009-04-14T06:57:22Z | 746,618 | <p>You should try storing the actual characters (ASCII 13 and ASCII 10) in the attribute value, instead of their already-escaped counterparts.</p>
<p><hr /></p>
<p>EDIT: It looks like minidom does not handle newlines in attribute values correctly. </p>
<p>Even though a literal line break in an attribute value is all... | 1 | 2009-04-14T07:04:48Z | [
"python",
"xml"
] |
How to write ampersand in node attribude? | 746,602 | <p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate... | 0 | 2009-04-14T06:57:22Z | 746,621 | <p>An ampersand is a special character in XML and as such most xml parsers require valid xml in order to function. Let minidom escape the ampersand for you (really it should already be escaped) and then when you need to display the escaped value, unescape it.</p>
| 0 | 2009-04-14T07:06:42Z | [
"python",
"xml"
] |
How to write ampersand in node attribude? | 746,602 | <p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate... | 0 | 2009-04-14T06:57:22Z | 747,260 | <blockquote>
<p>I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like 
</p>
</blockquote>
<p>Well, you can't specify that you want hex escapes specifically, but according to the DOM LS standard, implementations should change \r\n in attribute values to chara... | 1 | 2009-04-14T12:16:00Z | [
"python",
"xml"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 746,783 | <p>Some quick points:</p>
<ul>
<li>You should not name Python source files ".txt", you should use ".py".</li>
<li>Your indents look wrong, but that might just be Stack Overflow.</li>
<li>You need to call the <code>autoparts()</code> function to set up the dictionary.</li>
<li>The <code>autoparts()</code> function shou... | 4 | 2009-04-14T08:50:01Z | [
"python"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 746,813 | <p>Don't bother creating the lists first, just go straight to the dictionary:</p>
<pre><code>parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
</code></pre>
<p>Also, are these keys unique? Because if not some of the values wil... | 1 | 2009-04-14T08:58:36Z | [
"python"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 746,844 | <p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to <em>return</em> something.</p>
<p>When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give s... | 2 | 2009-04-14T09:21:19Z | [
"python"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 746,891 | <p>There are a lot of problems with what you've written so far, but your question was how to call the auto parts function. Here's how; first, rename your files to functiondocs.py and program.py - they're python so make them python files.</p>
<p>Next, to call the autoparts function, you simply change your main program ... | 0 | 2009-04-14T09:38:21Z | [
"python"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 747,451 | <p>Here's about the simplest way you could do this:</p>
<pre><code>def filetodict(filename):
return dict(line.split() for line in open(filename))
parts = filetodict("list_of_parts.txt")
print parts
</code></pre>
<p>Here's the output:</p>
<pre><code>{'a': 'apple', 'c': 'cheese', 'b': 'bacon', 'e': 'egg', 'd': 'd... | 0 | 2009-04-14T13:06:47Z | [
"python"
] |
Basic python. Quick question regarding calling a function | 746,774 | <p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt... | 1 | 2009-04-14T08:45:40Z | 747,855 | <p>As people have pointed out, you need to use the <code>py</code> extension for python source files. Your files would become "functiondoc.py" and "program.py". This will make your <code>import functiondoc</code> work correctly (as long as they are in the same directory)</p>
<p>The biggest problem with the <code>autop... | 3 | 2009-04-14T14:27:04Z | [
"python"
] |
Adding a user supplied property (at runtime) to an instance of Expando class in google app engine? | 746,942 | <p>By creating datastore models that inherit from the Expando class I can
make my model-entities/instances have dynamic properties. That is
great! But what I want is the names of these dynamic properties to be
determined at runtime. Is that possible?</p>
<p>For example,</p>
<pre><code>class ExpandoTest (db.Expando):
... | 0 | 2009-04-14T09:56:27Z | 746,978 | <p>Just found the solution to my own question. It was really simple but as I am a python noob I ended up posting the question that you see above.</p>
<p>For the code sample that I had used, this is what needs to be done: </p>
<pre><code>entity_two.__setattr(some_variable, some_value) #where some_variable is populated... | 0 | 2009-04-14T10:09:51Z | [
"python",
"google-app-engine"
] |
Adding a user supplied property (at runtime) to an instance of Expando class in google app engine? | 746,942 | <p>By creating datastore models that inherit from the Expando class I can
make my model-entities/instances have dynamic properties. That is
great! But what I want is the names of these dynamic properties to be
determined at runtime. Is that possible?</p>
<p>For example,</p>
<pre><code>class ExpandoTest (db.Expando):
... | 0 | 2009-04-14T09:56:27Z | 747,028 | <p>Usually, we use the setattr function directly.</p>
<pre><code>setattr( entity_two, 'some_variable', some_value )
</code></pre>
| 3 | 2009-04-14T10:35:10Z | [
"python",
"google-app-engine"
] |
wxPython: Calling an event manually | 747,781 | <p>How can I call a specific event manually from my own code?</p>
| 16 | 2009-04-14T14:14:27Z | 747,805 | <p>You mean you want to have an event dispatch?</p>
<blockquote>
<p>::wxPostEvent void
wxPostEvent(wxEvtHandler *dest,
wxEvent& event)</p>
<p>In a GUI application, this function
posts event to the specified dest
object using
wxEvtHandler::AddPendingEvent.
Otherwise, it dispatches event
immedia... | 0 | 2009-04-14T14:19:36Z | [
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually | 747,781 | <p>How can I call a specific event manually from my own code?</p>
| 16 | 2009-04-14T14:14:27Z | 748,801 | <p>I think you want <a href="http://www.wxpython.org/docs/api/wx-module.html#PostEvent">wx.PostEvent</a>.</p>
<p>There's also some info about posting events from other thread for <a href="http://wiki.wxpython.org/LongRunningTasks">long running tasks on the wxPython wiki</a>.</p>
| 8 | 2009-04-14T18:28:22Z | [
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually | 747,781 | <p>How can I call a specific event manually from my own code?</p>
| 16 | 2009-04-14T14:14:27Z | 841,045 | <p>Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help.</p>
<p>To manually post an event, you can use</p>
<pre><code>self.GetEventHandler().ProcessEvent(event)
</code></pre>
<p>(wxWidgets docs <a ... | 45 | 2009-05-08T17:55:39Z | [
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually | 747,781 | <p>How can I call a specific event manually from my own code?</p>
| 16 | 2009-04-14T14:14:27Z | 4,189,924 | <p>There's a simple, straightforward way to do it with recent versions of wxPython (see <a href="http://wiki.wxpython.org/CustomEventClasses" rel="nofollow">http://wiki.wxpython.org/CustomEventClasses</a>):</p>
<pre><code> # create event class
import wx.lib.newevent
SomeNewEvent, EVT_SOME_NEW_EVENT = wx.lib.ne... | 4 | 2010-11-15T23:38:17Z | [
"python",
"user-interface",
"events",
"wxpython"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 747,881 | <p>The problem appears to be that init() is resetting myvalue to an empty string. When I remove that line I get the expected output.</p>
| 1 | 2009-04-14T14:32:26Z | [
"python",
"design-patterns"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 747,888 | <p>It looks like it's working rather too well :-)</p>
<p>The issue is that the assignment <code>self.__myvalue = ""</code> in <code>__init__</code> will always clobber the value of <code>myvalue</code> every time a new Borg is, er, created. You can see this if you add some additional print statements to your test:</p>... | 13 | 2009-04-14T14:33:32Z | [
"python",
"design-patterns"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 747,940 | <p>Combining the removal of <code>self.__myvalue = ""</code> with the <a href="http://code.activestate.com/recipes/66531/#c20" rel="nofollow">new-style Borg</a> and the suggestions to avoid <code>__</code> in variable names, we get:</p>
<pre><code>class Config(object):
"""
Borg singleton config object
"""
... | 4 | 2009-04-14T14:43:16Z | [
"python",
"design-patterns"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 4,857,198 | <pre><code>class Borg(object):
"""Demonstrating the Borg-pattern: All the instances of a class already
know what one of them learned... Scary, isn't it?"""
def __init__(self, name):
self.name = name
@classmethod
def borg_knowledge(cls, who_is_it):
if hasattr(cls, "b_knowledge"):
... | 1 | 2011-01-31T23:12:20Z | [
"python",
"design-patterns"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 5,602,852 | <pre><code>> The problem appears to be that init() is resetting myvalue to an
> empty string. When You remove that
> line ('self.__myvalue = ""') then you will get the expected
> output.
</code></pre>
| 0 | 2011-04-09T04:21:28Z | [
"python",
"design-patterns"
] |
Python borg pattern problem | 747,793 | <p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config o... | 6 | 2009-04-14T14:17:36Z | 27,284,610 | <p>I tried implementing this using the "old-style" as well as the "new-style" and I cannot see a difference between them. Is there an advantage to one over the other? Or are these basically equivalent?</p>
<pre><code>class Borg(object):
shared_state = {'a_value': True}
def __init__(self):
self.__dict__... | 0 | 2014-12-04T01:11:39Z | [
"python",
"design-patterns"
] |
How to get output of exe in python script? | 748,028 | <p>When I call an external <code>.exe</code> program in Python, how can I get <code>printf</code> output from the <code>.exe</code> application and print it to my Python IDE?</p>
| 4 | 2009-04-14T15:02:33Z | 748,058 | <p>To call an external program from Python, use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess">subprocess</a> module.</p>
<blockquote>
<p>The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. </p>
</blockquot... | 14 | 2009-04-14T15:09:02Z | [
"python",
"ide",
"executable",
"redirect"
] |
How to get output of exe in python script? | 748,028 | <p>When I call an external <code>.exe</code> program in Python, how can I get <code>printf</code> output from the <code>.exe</code> application and print it to my Python IDE?</p>
| 4 | 2009-04-14T15:02:33Z | 748,170 | <p>I am pretty sure that you are talking about Windows here (based on the phrasing of your question), but in a Unix/Linux (including Mac) environment, the commands module is also available:</p>
<pre><code>import commands
( stat, output ) = commands.getstatusoutput( "somecommand" )
if( stat == 0 ):
print "Command... | 5 | 2009-04-14T15:38:55Z | [
"python",
"ide",
"executable",
"redirect"
] |
benchmarking django apps | 748,130 | <p>I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?</p>
<p><strong>note</strong>: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django ... | 13 | 2009-04-14T15:26:16Z | 748,177 | <p>There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.</p>
<ol>
<li><p>Django in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data.... | 7 | 2009-04-14T15:39:50Z | [
"python",
"django",
"profiling"
] |
benchmarking django apps | 748,130 | <p>I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?</p>
<p><strong>note</strong>: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django ... | 13 | 2009-04-14T15:26:16Z | 748,251 | <p>One way to get line by line performance data (profiling) your Django app is to use a WSGI middleware component like <strong><a href="http://pypi.python.org/pypi/repoze.profile/0.8">repoze.profile</a></strong>.</p>
<p>Assuming you are using mod_wsgi with Apache you can insert repoze.profile into your app like this:<... | 5 | 2009-04-14T15:57:17Z | [
"python",
"django",
"profiling"
] |
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS | 748,324 | <p>I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: <a href="http://www.longurlplease.com">http://www.longurlplease.com</a> </p>
<p>For example: </p>
<p><a href="http://bit.ly/rgCbf">http://bit.ly/rgCbf</a> can be converted to:<... | 12 | 2009-04-14T16:14:04Z | 748,340 | <p>Enter <a href="http://docs.python.org/library/urllib2.html"><code>urllib2</code></a>, which offers the easiest way of doing this:</p>
<pre><code>>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-ic... | 32 | 2009-04-14T16:17:56Z | [
"python",
"bit.ly",
"tinyurl"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.