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 |
|---|---|---|---|---|---|---|---|---|---|
raw escape in python except last char | 1,764,291 | <p>Why in python I can't use:</p>
<pre><code>r"c:\"
</code></pre>
| 0 | 2009-11-19T15:52:30Z | 6,034,727 | <p>found in Design and History FAQ <a href="http://docs.python.org/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash" rel="nofollow">http://docs.python.org/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash</a></p>
<blockquote>
<p>Raw strings were designed to ease
creating inp... | 0 | 2011-05-17T17:29:18Z | [
"python"
] |
Conditional counting in Python | 1,764,309 | <p>not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have</p>
<pre><code>class A:
def __init__(self, a, b):
self.a = a
... | 16 | 2009-11-19T15:54:25Z | 1,764,335 | <pre><code>print sum(1 for e in L if e.b == 1)
</code></pre>
| 10 | 2009-11-19T15:57:23Z | [
"python",
"arrays",
"list",
"count"
] |
Conditional counting in Python | 1,764,309 | <p>not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have</p>
<pre><code>class A:
def __init__(self, a, b):
self.a = a
... | 16 | 2009-11-19T15:54:25Z | 1,764,347 | <p>I would prefer the second one as it's only looping over the list once.</p>
<p>If you use <code>count()</code> you're looping over the list once to get the <code>b</code> values, and then looping over it again to see how many of them equal 1.</p>
<p>A neat way may to use <code>reduce()</code>:</p>
<pre><code>reduc... | 2 | 2009-11-19T15:58:37Z | [
"python",
"arrays",
"list",
"count"
] |
Conditional counting in Python | 1,764,309 | <p>not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have</p>
<pre><code>class A:
def __init__(self, a, b):
self.a = a
... | 16 | 2009-11-19T15:54:25Z | 1,764,391 | <pre><code>sum(x.b == 1 for x in L)
</code></pre>
<p>A boolean (as resulting from comparisons such as <code>x.b == 1</code>) is also an <code>int</code>, with a value of <code>0</code> for <code>False</code>, <code>1</code> for <code>True</code>, so arithmetic such as summation works just fine.</p>
<p>This is the sim... | 28 | 2009-11-19T16:03:10Z | [
"python",
"arrays",
"list",
"count"
] |
Conditional counting in Python | 1,764,309 | <p>not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have</p>
<pre><code>class A:
def __init__(self, a, b):
self.a = a
... | 16 | 2009-11-19T15:54:25Z | 27,665,780 | <p>To hide <code>reduce</code> details, you may define a <code>count</code> function:</p>
<pre><code>def count(condition, stuff):
return reduce(lambda s, x: \
s + (1 if condition(x) else 0), stuff, 0)
</code></pre>
<p>Then you may use it by providing the condition for counting:</p>
<pre><code>n... | 0 | 2014-12-27T08:57:30Z | [
"python",
"arrays",
"list",
"count"
] |
Python os.getcwd paths | 1,764,322 | <p>I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now ... | 0 | 2009-11-19T15:56:05Z | 1,764,375 | <p>You have to call <code>os.getcwd()</code> with the trailing parens.</p>
<p>What you probably actually want here though is <code>os.path.join()</code></p>
| 0 | 2009-11-19T16:01:50Z | [
"python"
] |
Python os.getcwd paths | 1,764,322 | <p>I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now ... | 0 | 2009-11-19T15:56:05Z | 1,764,379 | <p>This line of yours:</p>
<pre><code>f.writelines([os.getcwd %s % (f) for f in myDirectory])
</code></pre>
<p>is invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when <code>myDirectory</code> lists, not files in the current d... | 1 | 2009-11-19T16:02:09Z | [
"python"
] |
Python os.getcwd paths | 1,764,322 | <p>I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now ... | 0 | 2009-11-19T15:56:05Z | 1,764,384 | <p>os.getcwd is a function you need to call... also I'm not sure what you're doing with the string escape % - but they only work inside strings... I'm guessing you want something like this:</p>
<pre><code>f.writelines([os.path.join(os.getcwd(),f) for f in myDirectory])
</code></pre>
<p>[Edit: os.path.join from Alex M... | 0 | 2009-11-19T16:02:43Z | [
"python"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,539 | <p>I don't think the question asks for the powerset of the inputs, I think it asks for (part of) the Cartesian product of the input sets. I expect someone will correct me if I'm wrong.</p>
<p>And, as for an algorithm, well now that you know what it is you are looking for, Google will be your friend.</p>
<p>In your s... | 2 | 2009-11-19T16:20:29Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,541 | <p>You're looking for the Cartesian product. In Python, if you want tuples:</p>
<pre><code>c = [(x, y) for x in a for y in b]
r = [(vv, ww, xx, yy, zz)
for vv in v for ww in w for xx in x for yy in y for zz in z]
</code></pre>
| 0 | 2009-11-19T16:20:35Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,569 | <p>Perhaps you are looking for itertools.product:</p>
<pre><code>#!/usr/bin/env python
import itertools
a=[1,2]
b=['a','b']
c=[str(s)+str(t) for s,t in itertools.product(a,b)]
print(c)
['1a', '1b', '2a', '2b']
v=[1,'a']
w=[1,'b']
x=[1,'c']
y=[1,'d']
z=[1,'e']
r=[''.join([str(elt) for elt in p]) for p in itertools.pr... | 8 | 2009-11-19T16:23:55Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,572 | <p>I'm assuming that you want the Cartesian product - all possible lists created by choosing exactly one element from each list. You can implement it recursively, like this:</p>
<pre><code>def cartesian_product(l):
if l:
for b in cartesian_product(l[1:]):
for a in l[0]:
yield [a] + b
else:
... | 1 | 2009-11-19T16:24:17Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,616 | <p>Since you need a <strong>cartesian product</strong>, use that of <strong>itertools</strong> !</p>
<pre><code>>>> import itertools
>>> v = [1, 'a']
>>> w = [1, 'b']
>>> x = [1, 'c']
>>> y = [1, 'd']
>>> z = [1, 'e']
>>> p = [''.join(str(x) for x in c) f... | 1 | 2009-11-19T16:29:59Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,708 | <p>Might that do the trick?</p>
<pre><code>def getAllCombinations(listOfLists):
if len(listOfLists) == 1:
return [str(x) for x in listOfLists[0]]
result = set()
head, tail = listOfLists[0], listOfLists[1:]
tailCombs = getAllCombinations(tail)
for elem in head:
for tc in tailCombs:... | 1 | 2009-11-19T16:42:08Z | [
"php",
"python",
"algorithm"
] |
Is there an algorithm to find unique combinations of 2 lists? 5 lists? | 1,764,464 | <p>I have <strong>N</strong> Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data struc... | 1 | 2009-11-19T16:10:57Z | 1,764,979 | <p>I think another answer is in order, to respond to this:</p>
<blockquote>
<p>I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet.</p>
</blockquote>
<p>There <em>is</em> a pattern.</p>
<p>Suppose you have just two lists to combine. You can find all the combinations... | 2 | 2009-11-19T17:13:51Z | [
"php",
"python",
"algorithm"
] |
Python type long vs C 'long long' | 1,764,548 | <p>I would like to represent a value as a 64bit signed <code>long</code>, such that values larger than (2**63)-1 are represented as negative, however Python <code>long</code> has infinite precision. Is there a 'quick' way for me to achieve this?</p>
| 10 | 2009-11-19T16:21:15Z | 1,764,621 | <p>The quickest thing is probably to truncate the result to 64 bits yourself:</p>
<pre><code>def to_int64(n):
n = n & ((1 << 64) - 1)
if n > (1 << 63) - 1:
n -= 1 << 64
return n
</code></pre>
<p>You can of course define your own numeric type that automatically does this ev... | 3 | 2009-11-19T16:30:22Z | [
"python",
"64bit",
"long-integer"
] |
Python type long vs C 'long long' | 1,764,548 | <p>I would like to represent a value as a 64bit signed <code>long</code>, such that values larger than (2**63)-1 are represented as negative, however Python <code>long</code> has infinite precision. Is there a 'quick' way for me to achieve this?</p>
| 10 | 2009-11-19T16:21:15Z | 1,764,630 | <p>Have a look at the ctypes module, it is used to call foreign DLLs/libraries from python.
There a some data types that correspond to C types, for example </p>
<blockquote>
<p>class c_longlong</p>
</blockquote>
| 1 | 2009-11-19T16:31:37Z | [
"python",
"64bit",
"long-integer"
] |
Python type long vs C 'long long' | 1,764,548 | <p>I would like to represent a value as a 64bit signed <code>long</code>, such that values larger than (2**63)-1 are represented as negative, however Python <code>long</code> has infinite precision. Is there a 'quick' way for me to achieve this?</p>
| 10 | 2009-11-19T16:21:15Z | 1,764,637 | <p>You could use <a href="http://docs.python.org/3.1/library/ctypes.html#ctypes.c%5Flonglong"><code>ctypes.c_longlong</code></a>:</p>
<pre><code>>>> from ctypes import c_longlong as ll
>>> ll(2 ** 63 - 1)
c_longlong(9223372036854775807L)
>>> ll(2 ** 63)
c_longlong(-9223372036854775808L)
>... | 13 | 2009-11-19T16:32:07Z | [
"python",
"64bit",
"long-integer"
] |
Python type long vs C 'long long' | 1,764,548 | <p>I would like to represent a value as a 64bit signed <code>long</code>, such that values larger than (2**63)-1 are represented as negative, however Python <code>long</code> has infinite precision. Is there a 'quick' way for me to achieve this?</p>
| 10 | 2009-11-19T16:21:15Z | 1,767,591 | <p>Can you use <a href="http://numpy.scipy.org/">numpy</a>? It has an int64 type that does exactly what you want.</p>
<pre><code>In [1]: import numpy
In [2]: numpy.int64(2**63-1)
Out[2]: 9223372036854775807
In [3]: numpy.int64(2**63-1)+1
Out[3]: -9223372036854775808
</code></pre>
<p>It's transparent to users, unli... | 9 | 2009-11-20T00:28:00Z | [
"python",
"64bit",
"long-integer"
] |
How to execute Javascript from Python on Windows? | 1,764,674 | <p>how can I execute Javascript from Python on Windows?</p>
<p>I want to get python-spidermonkey functionality. Just like this:</p>
<pre><code>>>> class Foo:
... def hello(self):
... print "Hello, Javascript world!"
>>> cx.bind_class(Foo, bind_constructor=True)
>>> cx.eval_script("var... | 4 | 2009-11-19T16:37:11Z | 1,764,683 | <p>You could call <a href="http://pypi.python.org/pypi/python-spidermonkey" rel="nofollow">SpiderMonkey</a>.</p>
| 1 | 2009-11-19T16:38:34Z | [
"javascript",
"python"
] |
How to execute Javascript from Python on Windows? | 1,764,674 | <p>how can I execute Javascript from Python on Windows?</p>
<p>I want to get python-spidermonkey functionality. Just like this:</p>
<pre><code>>>> class Foo:
... def hello(self):
... print "Hello, Javascript world!"
>>> cx.bind_class(Foo, bind_constructor=True)
>>> cx.eval_script("var... | 4 | 2009-11-19T16:37:11Z | 1,787,560 | <p>How about pyv8: <a href="http://code.google.com/p/pyv8/" rel="nofollow">http://code.google.com/p/pyv8/</a></p>
| 4 | 2009-11-24T03:15:52Z | [
"javascript",
"python"
] |
How to omit using python coverage lib? | 1,764,806 | <p>I would like to omit some module that are in some particular directory : eggs and bin</p>
<pre><code>coverage -r -i --omit=/usr/lib/,/usr/share/,eggs,bin
Name Stmts Exec Cover
-------------------------------------------------------------------------... | 3 | 2009-11-19T16:54:26Z | 1,766,859 | <p>To tell you the truth, I think this might just be a bug in coverage.py. I'll look into it soon.</p>
<p>UPDATED: OK, I've fixed this bug (I hope), and posted new kits: <a href="http://pypi.python.org/pypi/coverage/3.2b2" rel="nofollow">Coverage.py 3.2b2</a>. Please let me know if it still is no good.</p>
| 4 | 2009-11-19T21:57:37Z | [
"python",
"code-coverage",
"coverage.py",
"python-coverage"
] |
Width and Precision using * | 1,764,812 | <p>I'm learning Python from a book and came across this example:</p>
<pre><code>>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
</code></pre>
<p>Don't quite understand what's happening here, especially the '4' in between.</p>
| 1 | 2009-11-19T16:55:49Z | 1,764,874 | <p>There are two syntax errors in the line you posted. 1.3.0 isn't a valid number, and the string isn't closed.</p>
<p>This is a valid version of said string format.</p>
<pre><code>'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
</code></pre>
<p>and outputs: </p>
<pre><code>'0.333333, 0.33, 0.3333'
</code></pre>
<p>... | 1 | 2009-11-19T17:01:39Z | [
"python",
"string-formatting"
] |
Width and Precision using * | 1,764,812 | <p>I'm learning Python from a book and came across this example:</p>
<pre><code>>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
</code></pre>
<p>Don't quite understand what's happening here, especially the '4' in between.</p>
| 1 | 2009-11-19T16:55:49Z | 1,764,885 | <p>I think you meant something like this:</p>
<pre><code>>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)
'0.333333, 1, 0.3333'
</code></pre>
<p><code>4</code> is a wild card value that is used in place of asterisk <code>*</code>. When expanded it would be equivalent to:</p>
<pre><code>>>> '%f, %2.f,... | 3 | 2009-11-19T17:03:08Z | [
"python",
"string-formatting"
] |
How to compute laplacian of a field? | 1,764,859 | <p>I'm trying to compute the laplacian of a 2d field <strong>A</strong> using <em>scipy.ndimage.convolve</em>.</p>
<pre><code>stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
scipy.ndimage.convolve(A, stencil, mode='wrap')
</code></pre>
<p>This doesn't seem to give me the right answer though. Any ideas where ... | 0 | 2009-11-19T17:00:16Z | 1,764,972 | <p>did you try another laplace convolution kernel, like <code>[[1,1,1][1,-8,1][1,1,1]]</code> ?</p>
| 1 | 2009-11-19T17:13:11Z | [
"python",
"numpy",
"scipy"
] |
How to compute laplacian of a field? | 1,764,859 | <p>I'm trying to compute the laplacian of a 2d field <strong>A</strong> using <em>scipy.ndimage.convolve</em>.</p>
<pre><code>stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
scipy.ndimage.convolve(A, stencil, mode='wrap')
</code></pre>
<p>This doesn't seem to give me the right answer though. Any ideas where ... | 0 | 2009-11-19T17:00:16Z | 1,766,879 | <p>I tried your example, and it does work with the latest SciPy on my machine.</p>
<p>I would suggest that you plot <code>image-ndimage.convolve(â¦)</code> in order to see how the convolution changes your image.</p>
<p>Example:</p>
<pre><code>image = vstack(arange(-10, 10)**2 for _ in range(20))
ndimage.convolve(im... | 0 | 2009-11-19T22:01:10Z | [
"python",
"numpy",
"scipy"
] |
How to compute laplacian of a field? | 1,764,859 | <p>I'm trying to compute the laplacian of a 2d field <strong>A</strong> using <em>scipy.ndimage.convolve</em>.</p>
<pre><code>stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
scipy.ndimage.convolve(A, stencil, mode='wrap')
</code></pre>
<p>This doesn't seem to give me the right answer though. Any ideas where ... | 0 | 2009-11-19T17:00:16Z | 1,770,788 | <p>I got another idea: did you take into account that your stencil, in order to approximate the Laplacian, should be divided by step**2, where step is the step size of your grid? Only then can you compare the ndimage.convolve result with the analytical result.</p>
<p>In fact, with a Gaussian, I obtain results that in... | 1 | 2009-11-20T14:30:14Z | [
"python",
"numpy",
"scipy"
] |
How to compute laplacian of a field? | 1,764,859 | <p>I'm trying to compute the laplacian of a 2d field <strong>A</strong> using <em>scipy.ndimage.convolve</em>.</p>
<pre><code>stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
scipy.ndimage.convolve(A, stencil, mode='wrap')
</code></pre>
<p>This doesn't seem to give me the right answer though. Any ideas where ... | 0 | 2009-11-19T17:00:16Z | 33,130,679 | <p>5 years ago I wonder anyone still cares...</p>
<p>I think it's because the convolution method is just an approximation, the stencil is basically approximating the 2nd order derivative by finite discrete differentiation. The smaller the increment, the closer the numerical approximation will be.</p>
<p>I've done som... | 1 | 2015-10-14T16:23:03Z | [
"python",
"numpy",
"scipy"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 1,765,093 | <p>You could try using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module (<code>subprocess.Popen</code>, <code>subprocess.call</code> or whatever) with the argument <code>shell=True</code> if you want to avoid starting a console window.</p>
| 5 | 2009-11-19T17:31:08Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 12,964,900 | <p>You should use <a href="http://docs.python.org/library/subprocess.html#popen-constructor"><code>subprocess.Popen</code></a> class passing as <code>startupinfo</code> parameter's value instance of <a href="http://docs.python.org/library/subprocess.html#subprocess.STARTUPINFO"><code>subprocess.STARTUPINFO</code></a> c... | 10 | 2012-10-18T22:44:40Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 16,057,764 | <p>The solution that Piotr describes is actually not as complicated as it may sound. Here is an example where a <code>startupinfo</code> is passed to a <code>check_call</code> invocation to suppress the console window:</p>
<pre><code>startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESH... | 12 | 2013-04-17T10:33:53Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 16,778,489 | <p>It seems that 'os.popen' doesn't produce console window. Script is running under 'pythonw'. Not sure about all cases but in my case it works well.</p>
<pre><code>os.popen(command)
</code></pre>
| 1 | 2013-05-27T18:12:55Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 19,205,020 | <p>People are a bit lazy... I would thx <strong>@Piotr Dobrogost</strong> and <strong>@Frank S. Thomas</strong> for their answers.</p>
<p>I came with this code who is runinng on Linux and Windows:</p>
<pre><code>import platform
import subprocess
startupinfo = None
if platform.system() == 'Windows':
import _subpro... | 6 | 2013-10-06T03:11:04Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | <p>If I save my code files as <code>.pyw</code>, no console window appears - which is what I want - but if the code includes a call to <code>os.system</code>, I still get a pesky console window. I assume it's caused by the call to <code>os.system</code>. Is there a way to execute other files from within my <code>.pyw</... | 9 | 2009-11-19T17:28:40Z | 24,793,676 | <p>Similar to what <strong>@firsthand</strong> said, I've read on the wxPython-user forums that you "replace" the current running application, that would be "command.com" or "CMD.exe", with pyw.exe or pythonw.exe when you use something like the following:</p>
<pre><code>os.execl(sys.executable, *([sys.executable]+sys.... | 0 | 2014-07-17T01:55:48Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] |
Troubles with python list and file saving | 1,765,394 | <p>I really don't know why my code is not saving for me the readings from the adc and gps receiver to the file I already open it in the first line in the code. it save only one record from both adc and gps receiver.</p>
<p>this is my code:</p>
<pre><code>import MDM
f = open("cord+adc.txt", 'w')
def getADC():
res ... | 0 | 2009-11-19T18:14:11Z | 1,765,585 | <p>If your modem connection is a <a href="http://docs.python.org/library/socket.html#module-socket" rel="nofollow">socket</a>,
make sure your socket is functioning by calling <code>getADC()</code> and <code>AcquiredPosition()</code> directly from the interactive interpreter. Just drop the <code>while(1)</code> loop in ... | 1 | 2009-11-19T18:38:55Z | [
"python"
] |
Troubles with python list and file saving | 1,765,394 | <p>I really don't know why my code is not saving for me the readings from the adc and gps receiver to the file I already open it in the first line in the code. it save only one record from both adc and gps receiver.</p>
<p>this is my code:</p>
<pre><code>import MDM
f = open("cord+adc.txt", 'w')
def getADC():
res ... | 0 | 2009-11-19T18:14:11Z | 1,765,587 | <p>Because you never explicitly flush() or close() your file, there's no guarantee <em>at all</em> about what will wind up in it. You should probably flush() it after each packet, and you must explicitly close() it when you wish your program to exit.</p>
| 1 | 2009-11-19T18:39:10Z | [
"python"
] |
Troubles with python list and file saving | 1,765,394 | <p>I really don't know why my code is not saving for me the readings from the adc and gps receiver to the file I already open it in the first line in the code. it save only one record from both adc and gps receiver.</p>
<p>this is my code:</p>
<pre><code>import MDM
f = open("cord+adc.txt", 'w')
def getADC():
res ... | 0 | 2009-11-19T18:14:11Z | 1,765,633 | <p>I don't see you closing the file anywhere. Add this as the last line of your code:</p>
<pre><code>f.close()
</code></pre>
<p>That should contribute to fixing your problem. I don;t know much about sockets, etc, so I can't help you there.</p>
| 0 | 2009-11-19T18:45:24Z | [
"python"
] |
Troubles with python list and file saving | 1,765,394 | <p>I really don't know why my code is not saving for me the readings from the adc and gps receiver to the file I already open it in the first line in the code. it save only one record from both adc and gps receiver.</p>
<p>this is my code:</p>
<pre><code>import MDM
f = open("cord+adc.txt", 'w')
def getADC():
res ... | 0 | 2009-11-19T18:14:11Z | 1,765,983 | <p>You have two problems here, you are not closing you file. There is a bigger problem in your program though your <code>while</code> loop will go forever (or until something else goes wrong in your program) there is no terminating condition. You are looping while 1 but never explicitly breaking out of the loop. I assu... | 3 | 2009-11-19T19:39:56Z | [
"python"
] |
Troubles with python list and file saving | 1,765,394 | <p>I really don't know why my code is not saving for me the readings from the adc and gps receiver to the file I already open it in the first line in the code. it save only one record from both adc and gps receiver.</p>
<p>this is my code:</p>
<pre><code>import MDM
f = open("cord+adc.txt", 'w')
def getADC():
res ... | 0 | 2009-11-19T18:14:11Z | 6,226,617 | <p>When you write a line into a file, it is actualy buffered into memory first (this is the C way of handling files). When the maximum size for the buffer is hit or you close the file, the buffer is emptyed into the specified file.</p>
<p>From the explanation so far i think you got the scary image of file manipulation... | 0 | 2011-06-03T11:37:11Z | [
"python"
] |
What are the differences in variable scoping between Python and Scheme? | 1,765,560 | <p>Refering to Variable Scoping.</p>
<p>I'm trying to figure out what are the differences between those 2.</p>
<p>For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?</p>
<p>Thanks!</p>
| 1 | 2009-11-19T18:36:42Z | 1,765,610 | <p>Yes, Python has the ability to access variables that are local to an anonymous function (in Python, this is called a lambda function) within that function.</p>
<p>I'm not entirely sure if that answered you question, so if it didn't, please post some more detail</p>
| 0 | 2009-11-19T18:41:39Z | [
"python",
"scheme"
] |
What are the differences in variable scoping between Python and Scheme? | 1,765,560 | <p>Refering to Variable Scoping.</p>
<p>I'm trying to figure out what are the differences between those 2.</p>
<p>For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?</p>
<p>Thanks!</p>
| 1 | 2009-11-19T18:36:42Z | 1,765,688 | <p>In Python variable scope can be either global or function. In Scheme, the scope can be any block.</p>
<p>For example, in Scheme you could define a variable inside a loop, and it wouldn't be accessible from outside the loop. In Python, the scope being the whole function, this variable would 'leak' out of the loop ... | 3 | 2009-11-19T18:54:38Z | [
"python",
"scheme"
] |
What are the differences in variable scoping between Python and Scheme? | 1,765,560 | <p>Refering to Variable Scoping.</p>
<p>I'm trying to figure out what are the differences between those 2.</p>
<p>For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?</p>
<p>Thanks!</p>
| 1 | 2009-11-19T18:36:42Z | 1,765,692 | <p>Scheme and Python are both lexically scoped, in the way that you seem to be asking.</p>
<pre><code>def make_adder(n):
when = datetime.now()
def adder(k):
print "The adder you created at %s has been called!" % when
return k + n
return adder
</code></pre>
| 0 | 2009-11-19T18:55:20Z | [
"python",
"scheme"
] |
What are the differences in variable scoping between Python and Scheme? | 1,765,560 | <p>Refering to Variable Scoping.</p>
<p>I'm trying to figure out what are the differences between those 2.</p>
<p>For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?</p>
<p>Thanks!</p>
| 1 | 2009-11-19T18:36:42Z | 1,766,025 | <p>Subtle question. Yes, Python lambdas close on variables in the enclosing function. Both languages have lexical scoping. But the details are quite different.</p>
<p>In Scheme, you usually introduce a variable with <code>(let)</code> or <code>(letrec)</code> or <code>(lambda)</code> and it's pretty explicit what the ... | 2 | 2009-11-19T19:45:36Z | [
"python",
"scheme"
] |
To have two Pg queries in one Python method | 1,765,630 | <p>Thank you for Denis who solves the first bug!</p>
<p><strong>How can you have two Postgres queries in one Python method?</strong></p>
<p><strong>Example where the 2nd query is not run</strong></p>
<pre><code>def comp_func(pgmasi):
pgmasi.query("""CREATE TABLE courses (
course_id SERIAL PRIMA... | 0 | 2009-11-19T18:44:52Z | 1,765,820 | <p>Probably you missed closing parentheses in the line as error message says:</p>
<pre><code>pgmasi.query("INSERT INTO files('binf','file_name') VALUES(file,file_name)"
</code></pre>
| 2 | 2009-11-19T19:15:31Z | [
"python",
"postgresql"
] |
Python nested classes scope | 1,765,677 | <p>I'm trying to understand scope in nested classes in python. Here is my example code :</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
</code></pre>
<p>The creation of class does not complete and I get the error :</p>
<pre><code><type 'exceptions.NameE... | 81 | 2009-11-19T18:53:05Z | 1,765,716 | <pre><code>class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
</code></pre>
<p>This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to <code>outer_var</code>. (If you chan... | 76 | 2009-11-19T18:58:53Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] |
Python nested classes scope | 1,765,677 | <p>I'm trying to understand scope in nested classes in python. Here is my example code :</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
</code></pre>
<p>The creation of class does not complete and I get the error :</p>
<pre><code><type 'exceptions.NameE... | 81 | 2009-11-19T18:53:05Z | 1,765,849 | <p>You might be better off if you just don't use nested classes. If you must nest, try this:</p>
<pre><code>x = 1
class OuterClass:
outer_var = x
class InnerClass:
inner_var = x
</code></pre>
<p>Or declare both classes before nesting them:</p>
<pre><code>class OuterClass:
outer_var = 1
class Inn... | 19 | 2009-11-19T19:19:33Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] |
Python nested classes scope | 1,765,677 | <p>I'm trying to understand scope in nested classes in python. Here is my example code :</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
</code></pre>
<p>The creation of class does not complete and I get the error :</p>
<pre><code><type 'exceptions.NameE... | 81 | 2009-11-19T18:53:05Z | 8,366,758 | <p>I think you can simply do:</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
pass
InnerClass.inner_var = outer_var
</code></pre>
<p>The problem you encountered is due to this:</p>
<blockquote>
<p>A block is a piece of Python program text that is executed as a unit.
The foll... | 35 | 2011-12-03T09:26:51Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] |
Python nested classes scope | 1,765,677 | <p>I'm trying to understand scope in nested classes in python. Here is my example code :</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
</code></pre>
<p>The creation of class does not complete and I get the error :</p>
<pre><code><type 'exceptions.NameE... | 81 | 2009-11-19T18:53:05Z | 20,806,933 | <p>Easiest solution:</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
def __init__(self):
self.inner_var = OuterClass.outer_var
</code></pre>
<p>It requires you to be explicit, but doesn't take much effort. </p>
| 4 | 2013-12-27T19:51:34Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] |
Python nested classes scope | 1,765,677 | <p>I'm trying to understand scope in nested classes in python. Here is my example code :</p>
<pre><code>class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
</code></pre>
<p>The creation of class does not complete and I get the error :</p>
<pre><code><type 'exceptions.NameE... | 81 | 2009-11-19T18:53:05Z | 38,438,185 | <p>In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.</p>
<pre><code>class OuterClass:
def __init__(self):
self.outer_var = 1
self.inner_class = OuterClass.InnerClass(self)
print('Inner variable in OuterClass = %d' % self.in... | 1 | 2016-07-18T13:37:22Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 1,766,136 | <p>Try adding <code>blank=True</code> to the model fields (assuming that's the behavior you want), then changing the form to a ModelForm and removing the field definitions. Note that any fields for which you set <code>blank=True</code> won't be required when validating <em>or saving</em> the model. Again, this may not ... | 4 | 2009-11-19T20:01:21Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 1,783,734 | <p>I've found a solution that works the way I want it to without violating the DRY principle. Not very clean, but it'll have to do I suppose.</p>
<p>According to <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#choices">the documentation</a> choices don't have to be a tuple:</p>
<blockquote>
<p>Fina... | 31 | 2009-11-23T15:13:06Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 2,216,679 | <p>Better choice is to update field choices in form <strong>init</strong> method</p>
<pre><code>COMPETITION_TYPE_CHOICES = (
(1, 'Olympic Games'),
(2, 'ISU Championships'),
(3, 'Grand Prix Series'),
)
class CompetitionSearchForm(forms.Form):
name = forms.CharField(required=False)
type = forms.Cho... | 7 | 2010-02-07T10:31:52Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 4,407,932 | <p>Just a small change to <a href="http://stackoverflow.com/questions/1765757/choicefield-doesnt-display-an-empty-label-when-using-a-tuple-am-i-doing-someth/2216679#2216679">Evgeniy's answer</a> that checks if the blank alternative is not already added.</p>
<p>Without the check (at least when running the builtin runse... | 5 | 2010-12-10T10:34:19Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 14,229,013 | <p>Why don't you use ModelForm if you are already have model class?</p>
<p>Best solution:</p>
<p><strong>forms.py</strong></p>
<pre><code>class CompetitionSearchForm(ModelForm):
class Meta:
model = Competition
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Competition(models.Model):
... | 0 | 2013-01-09T05:49:59Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 21,357,946 | <p>I tried both Monika's and Evgeniy's solutions with no success, but Monika has a good point in that the choices do not need to be tuples. Therefore, the easiest (and DRYest) solution is to simply do what Django does already in the Model Field. Simply add the blank choice and the tuples together after converting them ... | 21 | 2014-01-26T00:10:34Z | [
"python",
"django",
"django-forms"
] |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | <h2>What I'm trying to do</h2>
<p>I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.</p>
<h2>About competition types</h2>
<p>Competition types are kept in a tuple. A slightly shortened example:</p>
<pre><... | 32 | 2009-11-19T19:05:26Z | 26,978,452 | <p>According to the documentation:</p>
<blockquote>
<p>Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. (<a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/form... | 3 | 2014-11-17T17:33:32Z | [
"python",
"django",
"django-forms"
] |
Using Jython From Eclipse Plugin | 1,765,802 | <p>I am having a tough time getting jython to work properly when run from an Eclipse plugin. I have a simple object factory that loads a python module conforming to a Java Interface. All of this works fine in standalone mode. However, when I package this as an eclipse plugin, I get a different error based on a few v... | 2 | 2009-11-19T19:13:32Z | 1,772,701 | <p>Finally figure this one out. Here is what I had to do:</p>
<p>1) I used the JSR223 ScriptEngine instead of PythonInterpreter:<br></p>
<p><code>engine.get(module_name); //gets the class object of the module
getConstructors[0].newInstance(null) on the class to get an object<br>
//cast it to your interface!</code><... | 4 | 2009-11-20T19:22:40Z | [
"java",
"python",
"jython"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 1,766,002 | <p>You'll presumably have to move tag's children to be children of tag's parent before you remove the tag -- is that what you mean?</p>
<p>If so, then, while inserting the contents in the right place is tricky, something like this should work:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
VALID_TAGS = 'div'... | 6 | 2009-11-19T19:42:02Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 1,768,210 | <p>I have a simpler solution but I don't know if there's a drawback to it.</p>
<p><strong>UPDATE:</strong> there's a drawback, see Jesse Dhillon's comment. Also, another solution will be to use Mozilla's <a href="https://github.com/jsocol/bleach" rel="nofollow">Bleach</a> instead of BeautifulSoup.</p>
<pre><code>from... | 8 | 2009-11-20T03:43:13Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 3,225,671 | <p>The strategy I used is to replace a tag with its contents if they are of type <code>NavigableString</code> and if they aren't, then recurse into them and replace their contents with <code>NavigableString</code>, etc. Try this:</p>
<pre><code>from BeautifulSoup import BeautifulSoup, NavigableString
def strip_tags(h... | 46 | 2010-07-12T03:25:02Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 8,439,761 | <p>Current versions of the BeautifulSoup library have an undocumented method on Tag objects called replaceWithChildren(). So, you could do something like this:</p>
<pre><code>html = "<p>Good, <b>bad</b>, and <i>ug<b>l</b><u>y</u></i></p>"
invalid_tags = ['b... | 41 | 2011-12-09T00:47:21Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 12,989,845 | <p>Although this has already been mentoned by other people in the comments, I thought I'd post a full answer showing how to do it with Mozilla's Bleach. Personally, I think this is a lot nicer than using BeautifulSoup for this.</p>
<pre><code>import bleach
html = "<b>Bad</b> <strong>Ugly</strong&g... | 8 | 2012-10-20T15:22:36Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 16,144,379 | <p>None of the proposed answered seemed to work with BeautifulSoup for me. Here's a version that works with BeautifulSoup 3.2.1, and also inserts a space when joining content from different tags instead of concatenating words. </p>
<pre><code>def strip_tags(html, whitelist=[]):
"""
Strip all HTML tags except f... | 2 | 2013-04-22T10:04:54Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 20,737,874 | <p>you can use soup.text</p>
<p>.text removes all tags and concatenate all text.</p>
| 6 | 2013-12-23T06:08:05Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 29,000,615 | <p>This is an old question, but just to say of a better ways to do it. First of all, BeautifulSoup 3* is no longer being developed, so you should rather use BeautifulSoup 4*, so called <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">bs4</a>. </p>
<p>Also, lxml has just function that you ... | -1 | 2015-03-12T01:51:11Z | [
"python",
"beautifulsoup"
] |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | <p>Currently I have code that does something like this:</p>
<pre><code>soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
</code></pre>
<p>Except I don't want to throw away the contents inside the invalid tag. How do I get rid of ... | 27 | 2009-11-19T19:19:28Z | 39,689,614 | <p>Here is the better solution without any hassles and boilerplate code to filter out the tags keeping the content.Lets say you want to remove any children tags within the parent tag and just want to keep the contents/text then,you can simply do:</p>
<pre><code>for p_tags in div_tags.find_all("p"):
print(p_tags.g... | 0 | 2016-09-25T17:13:35Z | [
"python",
"beautifulsoup"
] |
Python: Binding method | 1,765,922 | <p>In following example I am trying to bind a method object via <em>types.MethodType(...)</em>. It does not seem to work. Any suggestions? Thanks in advance.</p>
<pre><code>import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived... | 0 | 2009-11-19T19:30:29Z | 1,765,954 | <p>Because you passed Base's payload (not Drvd's) to iter!</p>
<p>Hint:</p>
<pre><code>print "%s: Base:payload"%repr(self)
</code></pre>
<p>Kudos for creating an accursed chimera of a thing, though!</p>
| 1 | 2009-11-19T19:34:25Z | [
"python",
"binding",
"types",
"methods",
"bind"
] |
Python: Binding method | 1,765,922 | <p>In following example I am trying to bind a method object via <em>types.MethodType(...)</em>. It does not seem to work. Any suggestions? Thanks in advance.</p>
<pre><code>import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived... | 0 | 2009-11-19T19:30:29Z | 1,765,966 | <p>I don't really understand what you're trying to do - but to me it's working as I'd expect. You are binding Base.payload to Drvd - from your print out you can see it is binding correctly to your Drvd instance. I'm not sure why you are then expecting it to call Drvd.payload - you have bound the function object Base.pa... | 0 | 2009-11-19T19:36:28Z | [
"python",
"binding",
"types",
"methods",
"bind"
] |
Python: Binding method | 1,765,922 | <p>In following example I am trying to bind a method object via <em>types.MethodType(...)</em>. It does not seem to work. Any suggestions? Thanks in advance.</p>
<pre><code>import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived... | 0 | 2009-11-19T19:30:29Z | 1,765,986 | <p>You're specifically requesting the use of the underlying function (<code>im_func</code>) of <code>Base.payload</code>, with a fake <code>im_class</code> of <code>Drvd</code>. Add after the existing <code>print</code> in <code>iter</code>:</p>
<pre><code> print "w/class:", derived_func.im_class
print "w/func... | 2 | 2009-11-19T19:40:24Z | [
"python",
"binding",
"types",
"methods",
"bind"
] |
Python, removing the \'s before getting them processed | 1,766,510 | <p>I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace func... | 1 | 2009-11-19T21:02:37Z | 1,766,531 | <p>No, the backslash is not interpreted as an escape sequence except in Python <em>source code</em>. Unless you're eval()ing the path, which would be Wrong, I'm not sure why you'd have a problem.</p>
| 6 | 2009-11-19T21:04:47Z | [
"python",
"escaping",
"backslash"
] |
Python, removing the \'s before getting them processed | 1,766,510 | <p>I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace func... | 1 | 2009-11-19T21:02:37Z | 1,766,537 | <p>If you are asking for the user for input, then a \ will go into a string as a \ correctly. Only if you then eval the user's string in some way will the backslash count as an escape char. You really only need to worry about escaping when you are writing strings within the code.</p>
| 3 | 2009-11-19T21:05:56Z | [
"python",
"escaping",
"backslash"
] |
Python, removing the \'s before getting them processed | 1,766,510 | <p>I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace func... | 1 | 2009-11-19T21:02:37Z | 1,766,545 | <p>Use double \</p>
<pre><code>str = 'c:\\dir\\file.txt'
print str.replace('\\','/')
print str
</code></pre>
<p>here us the output</p>
<pre><code>c:/dir/file.txt
c:\dir\file.txt
</code></pre>
| 3 | 2009-11-19T21:06:44Z | [
"python",
"escaping",
"backslash"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,753 | <p>Are you running this program in a Windows cmd.exe box? If so, try running it in IDLE and see if you get the same errors. The Cmd.exe box doesn't do unicode, only ascii. </p>
| 1 | 2009-11-19T21:38:56Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,775 | <p>You are trying to perform some action (e.g., print) on unicode string that contains non-ASCII characters, and the string is being converted to ascii by default. You will need specify the encoding to correctly represent the string.<br/>
It would help significantly, if you post some sample code of what you are trying ... | 2 | 2009-11-19T21:42:24Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,776 | <p>Some unicode items:</p>
<ul>
<li>putting <code># encoding: utf-8</code> at the top of the file sometimes help (if your editor uses UTF-8 to save your file ...)</li>
<li><code>s = "i'm a string"</code></li>
<li><code>u = u"i'm unicode, at least in python < Û³"</code></li>
<li>If your work with files try to look i... | 1 | 2009-11-19T21:43:17Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,804 | <p>We can't guess what you are trying to do, nor what's in your code, not what "setting many different codecs" means, nor what u"string" is supposed to do for you.</p>
<p>Please change your code to its initial state so that it reflects as best you can what you are trying to do, run it again, and then edit your questio... | 13 | 2009-11-19T21:47:46Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,944 | <pre><code>u"%s" % f
</code></pre>
<p>In various places you're doing something similar to the above code. This is exactly the wrong way to convert a str object to a unicode object as the conversion is done using sys.getdefaultencoding() (ascii), which is almost guaranteed to be wrong.</p>
<p>You should be using the ... | 1 | 2009-11-19T22:10:56Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,766,989 | <p>instead of doing:</p>
<pre><code>print "Error reading file %s"%u"%s/%s"%(folder, f)
</code></pre>
<p>Try this:</p>
<pre><code>print "Error reading file %s"%u"%s/%s"%(folder.encode('ascii','ignore'), f.encode('ascii','ignore'))
</code></pre>
<p>Since the console can't print unicode chars, you can's see the correc... | -2 | 2009-11-19T22:20:43Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 1,773,509 | <p>I've had the misfortune of working in some codebases that weren't consistent with their encoding.</p>
<p>This is a function we used to help clean it up:</p>
<pre><code>def to_unicode(value):
if isinstance(value, unicode):
return value
elif isinstance(value, str):
try:
if value.s... | 0 | 2009-11-20T21:58:27Z | [
"python",
"unicode"
] |
Python, UnicodeDecodeError | 1,766,669 | <p>I get this error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
</code></pre>
<p>I tried setting many different codecs (in the header, like <code># -*- coding: utf8 -*-</code>), or even using u"string", but it still appears.</p>
<p>How do I fix th... | 6 | 2009-11-19T21:22:54Z | 4,631,545 | <p>Python uses ASCII encoding by default, which is annoying. If you want to change it permanently, find and edit <strong>site.py</strong> file, search for <code>def setencoding()</code> and few lines below change <code>encoding = "ascii"</code> to <code>encoding = "utf-8"</code>. Bye, bye default ASCII encoding.</p>
| 5 | 2011-01-08T00:27:39Z | [
"python",
"unicode"
] |
How can I generate RSS with arbitrary tags and enclosures | 1,766,823 | <p>Right now, I'm using PyRSS2Gen to generate an RSS document (resyndicating a modification of an rss feed that was parsed with feedparser), but I can't figure out how to add uncommon tags to the item.</p>
<pre><code>items = [
PyRSS2Gen.RSSItem(
title = x.title,
link = x.link,
description = x.summary,
... | 1 | 2009-11-19T21:51:20Z | 1,766,972 | <p><a href="http://www.dalkescientific.com/Python/PyRSS2Gen.html" rel="nofollow">The documentation explains:</a></p>
<blockquote>
<p>To add your
own attributes (needed for namespace
declarations), redefine
<code>element_attrs</code> or <code>rss_attrs</code> in your
subclass [of <code>RSS</code> and <code>RS... | 1 | 2009-11-19T22:16:44Z | [
"python",
"rss",
"feedparser"
] |
How can I generate RSS with arbitrary tags and enclosures | 1,766,823 | <p>Right now, I'm using PyRSS2Gen to generate an RSS document (resyndicating a modification of an rss feed that was parsed with feedparser), but I can't figure out how to add uncommon tags to the item.</p>
<pre><code>items = [
PyRSS2Gen.RSSItem(
title = x.title,
link = x.link,
description = x.summary,
... | 1 | 2009-11-19T21:51:20Z | 1,795,116 | <p>There are two ways. First, you could change the code directly. Edit 'publish' and put whatever you want wherever you want it.</p>
<p>But if you want to take the suggestion from the documentation, derive from RSS2 and implement your own publish_extensions, like this:</p>
<pre><code>class YourRSS2Item(PyRSS2Gen.RSSI... | 1 | 2009-11-25T06:58:28Z | [
"python",
"rss",
"feedparser"
] |
To understand Python's optparse | 1,767,210 | <p>Thank you for quack in pointing out the off-by-one!</p>
<p>The following code is my first attempt in writing code with Optparse.</p>
<p><strong>How can you fix the following bug in getting the help by Optparse?</strong></p>
<pre><code>#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
... | 0 | 2009-11-19T23:07:13Z | 1,767,256 | <p>The bug is that your arguments array includes the name of the script as <code>sys.argv[0]</code>. Thus your <code>if</code> is off-by-one:</p>
<pre><code># python sys.argv[0] sys.argv[1] sys.argv[2] sys.argv[3]
if len(sys.argv) < 4:
sys.exit(usage)
</code></pre>
| 6 | 2009-11-19T23:13:52Z | [
"python",
"debugging",
"arguments"
] |
To understand Python's optparse | 1,767,210 | <p>Thank you for quack in pointing out the off-by-one!</p>
<p>The following code is my first attempt in writing code with Optparse.</p>
<p><strong>How can you fix the following bug in getting the help by Optparse?</strong></p>
<pre><code>#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
... | 0 | 2009-11-19T23:07:13Z | 1,767,660 | <p>Constructor for <code>class optparse.OptionParser(...)</code> has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own.
<br/>
<br/>
<code>parser = OptionParser(usage, add_help_option=False)</code></p>... | 7 | 2009-11-20T00:52:09Z | [
"python",
"debugging",
"arguments"
] |
To understand Python's optparse | 1,767,210 | <p>Thank you for quack in pointing out the off-by-one!</p>
<p>The following code is my first attempt in writing code with Optparse.</p>
<p><strong>How can you fix the following bug in getting the help by Optparse?</strong></p>
<pre><code>#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
... | 0 | 2009-11-19T23:07:13Z | 1,767,776 | <p>This should do what you require, based on your example above:</p>
<pre><code>#!/usr/bin/env python
from optparse import OptionParser
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
(options, args) = parser.parse_args()
i... | 1 | 2009-11-20T01:30:48Z | [
"python",
"debugging",
"arguments"
] |
To understand Python's optparse | 1,767,210 | <p>Thank you for quack in pointing out the off-by-one!</p>
<p>The following code is my first attempt in writing code with Optparse.</p>
<p><strong>How can you fix the following bug in getting the help by Optparse?</strong></p>
<pre><code>#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
... | 0 | 2009-11-19T23:07:13Z | 1,767,884 | <p>For using optparse here's what I normally do:</p>
<ol>
<li><p>separate command line parsing from your main code base for better modularization.
(Put the processing right after "if __name__ == "__main__"")</p></li>
<li><p>Let optparse handle your help.
(Use parser.print_help())</p></li>
<li><p>Use the optparse const... | 1 | 2009-11-20T02:06:52Z | [
"python",
"debugging",
"arguments"
] |
Separating Business Layer Errors from API errors | 1,767,504 | <p>The title is horrible, i know; I'm terrible at titles on SO here.</p>
<p>I'm wondering what would be the best way to present unified error responses in a webapi when errors could be raised deep inside the application.</p>
<p>The errors deep down in the app don't know anything about the web layer (nor should they),... | 1 | 2009-11-20T00:06:30Z | 1,767,830 | <p>I like option 1. It may be a little more verbose, but it's also very clear. </p>
<p>Option 2 separates the point at which the exception is thrown from where the decision about what to do with it is made. In reality, that likely wouldn't be too much of an issue, but why split it up if you don't have to? </p>
<p>I... | 1 | 2009-11-20T01:49:13Z | [
"python",
"error-handling"
] |
how to insert a infomation on a table in Django | 1,767,506 | <p>This is my form on models.py</p>
<pre><code>class ItemForm(forms.Form):
itemname = forms.CharField(max_length=100)
itemwording = forms.CharField(max_length=100)
notes = forms.CharField()
abundance = forms.IntegerField(max_value=10)
collunit = forms.CharField(max_length=50)
litref = forms.Ch... | 0 | 2009-11-20T00:06:51Z | 1,767,667 | <p>The data you've posted doesn't indicate the source of the problem. Did you clear your database and run <code>syncdb</code> when you last changed your models?</p>
<p>The error you're seeing relates to trying to introduce a duplicate value into a column which must be unique, constrained at the database level. You hav... | 1 | 2009-11-20T00:54:57Z | [
"python",
"django",
"django-models",
"django-forms",
"django-views"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 1,767,589 | <pre><code>with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
</code></pre>
<p>Here's another way</p>
<pre><code>from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print head
</code></pre>
| 81 | 2009-11-20T00:27:18Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 1,767,590 | <p>There is no specific method to read number of lines exposed by file object. </p>
<p>I guess the easiest way would be following: <br/></p>
<pre><code>lines =[]
with open(file_name) as f:
lines.extend(f.readline() for i in xrange(N))
</code></pre>
| 3 | 2009-11-20T00:27:39Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 1,767,869 | <p>If you want something that obviously (without looking up esoteric stuff in manuals) works without imports and try/except and works on a fair range of Python 2.x versions (2.2 to 2.6):</p>
<pre><code>def headn(file_name, n):
"""Like *x head -N command"""
result = []
nlines = 0
assert n >= 1
fo... | 1 | 2009-11-20T02:00:36Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 1,767,879 | <pre><code>N=10
f=open("file")
for i in range(N):
line=f.next().strip()
print line
f.close()
</code></pre>
| 11 | 2009-11-20T02:04:36Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 4,751,768 | <p>Based on gnibbler top voted answer (Nov 20 '09 at 0:27): this class add head() and tail() method to file object.</p>
<pre><code>class File(file):
def head(self, lines_2find=1):
self.seek(0) #Rewind file
return [self.next() for x in xrange(lines_2find)]
def tail(se... | 2 | 2011-01-20T19:42:58Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 8,412,297 | <p>most convinient way on my own:</p>
<pre><code>LINE_COUNT = 3
print [s for (i, s) in enumerate(open('test.txt')) if i < LINE_COUNT]
</code></pre>
<p>Solution based on <a href="http://www.python.org/dev/peps/pep-0202/" rel="nofollow">List Comprehension</a>
The function open() supports an iteration interface. The ... | 1 | 2011-12-07T08:26:17Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 13,749,715 | <p>Starting at Python 2.6, you can take advantage of more sophisticated functions in the IO base clase. So the top rated answer above can be rewritten as:</p>
<pre><code> with open("datafile") as myfile:
head = myfile.readlines(N)
print head
</code></pre>
<p>(You don't have to worry about your file hav... | 1 | 2012-12-06T18:02:26Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 20,441,641 | <p>If you want to have the first lines in a list, the simple thing is to use <code>.readlines()</code> which returns list object.</p>
<p>E.g. for the first 5 lines:</p>
<pre><code>with open("pathofmyfileandfileandname") as myfile:
firstNlines=myfile.readlines()[0:5] #put here the interval you want
print firstNlin... | 4 | 2013-12-07T12:59:02Z | [
"python",
"file",
"head"
] |
Read first N lines of a file in python | 1,767,513 | <p>We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.</p>
<p>How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the imp... | 55 | 2009-11-20T00:09:32Z | 27,119,129 | <p>If you have a really big file, and assuming you want the output to be a numpy array, using np.genfromtxt will freeze your computer. This is so much better in my experience:</p>
<pre><code>def load_big_file(fname,maxrows):
'''only works for well-formed text file of space-separated doubles'''
rows = [] # unknown nu... | 0 | 2014-11-25T05:00:10Z | [
"python",
"file",
"head"
] |
Plotting Histogram: How can I do it from scratch using data stored in a database? | 1,767,565 | <p>I have some data stored in a database like this:</p>
<p>TableName: faults
Table:</p>
<pre><code>+------------+--------------+
| fault_type | total |
+------------+--------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 8 |
| 4 | 2 |
........ | 2 | 2009-11-20T00:22:07Z | 1,767,569 | <p>The solution below assumes that you have MySQL, Python and GNUPlot. The specific details can be fine tuned if necessary. Posting it so that it could be a baseline for other peers.</p>
<p><strong>Step #1: Decide the type of graph.</strong></p>
<p>If it is a frequency plot of some kind, then a simple SQL query shoul... | 2 | 2009-11-20T00:22:23Z | [
"python",
"mysql",
"graph",
"gnuplot",
"histogram"
] |
Plotting Histogram: How can I do it from scratch using data stored in a database? | 1,767,565 | <p>I have some data stored in a database like this:</p>
<p>TableName: faults
Table:</p>
<pre><code>+------------+--------------+
| fault_type | total |
+------------+--------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 8 |
| 4 | 2 |
........ | 2 | 2009-11-20T00:22:07Z | 7,454,327 | <p><a href="http://gnuplot-surprising.blogspot.com/2011/09/statistic-analysis-and-histogram.html" rel="nofollow">This blog article</a> may help you! It talks about statistic using gnuplot and plot the result into histogram.</p>
| 0 | 2011-09-17T11:16:26Z | [
"python",
"mysql",
"graph",
"gnuplot",
"histogram"
] |
Are there any libraries for Python to simulate keyboard action? | 1,767,575 | <p>The problem I have is that I have this Python script to launch a application. After the application is launched (the GUI is shown on screen), I want to make it de-activated. It can be done manually by activating another window, or minimizing this app, or pressing the Show Desktop key for WindowsXP.</p>
<p>So is the... | 2 | 2009-11-20T00:24:03Z | 1,767,614 | <p>Take a look at <a href="http://www.rutherfurd.net/python/sendkeys/" rel="nofollow">SendKeys</a>. It is in the <a href="http://pypi.python.org/pypi/SendKeys/0.3" rel="nofollow">pypi</a>, so you can install it via <code>easy_install</code>.</p>
| 4 | 2009-11-20T00:34:21Z | [
"python",
"windows",
"keyboard"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.