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 |
|---|---|---|---|---|---|---|---|---|---|
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,314 | <p>Sample Python code:</p>
<pre><code>L = ['foo', 'bar', 'baz'] # Your list
s = set(L) # Converted to Set
print 'foo' in s # True
print 'blah' in s # False
</code></pre>
| 4 | 2009-05-16T12:12:37Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,353 | <p>Two things: </p>
<p>The Python 'mutable set' type has an 'add' method ( s.add(item) ), so you could go right from reading (a line) from your big file straight into a set without using a list as an intermediate data structure. </p>
<p>Python lets you 'pickle' a data structure, so you could save your big set to a file and save the time of reinitiating the set.</p>
<p>Second, I've been looking for a list of all the single-syllable words in English for my own amusement, but the ones I've found mentioned seem to be proprietary. If it isn't being intrusive, could I ask whether your list of English words can be obtained by others?</p>
| 2 | 2009-05-16T12:34:01Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,391 | <p>Converting the list to a set will only be helpful if you repeatedly run this kind of query against the data, as will sorting the list and doing a binary search. If you're only going to pull data out of the list once, a plain old linear search is your best bet:</p>
<pre><code>if 'foo' in some_list:
do_something()
</code></pre>
<p>Otherwise, your best bet is to use either a set as has been mentioned or a binary search. Which one you should choose depends largely on how big the data is and how much memory you can spare. I'm told that really large lists tend to benefit more from hashing, although the amount of memory that's taken up can be prohibitively expensive.</p>
<p>Finally, a third option is that you can import the data into a sqlite database and read directly from it. Sqlite is very fast and it may save you the trouble of loading the <em>whole</em> list from file. Python has a very good built-in <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">sqlite library</a>.</p>
| 0 | 2009-05-16T13:01:05Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,481 | <p>Others have given you the in-memory way using set(), and this is generally going to be the fastest way, and should not tax your memory for a 60k word dataset (a few MiBs at most). You should be able to construct your set with:</p>
<pre><code>f=open('words.txt')
s = set(word.strip() for word in f)
</code></pre>
<p>However, it does require some time to load the set into memory. If you are checking lots of words, this is no problem - the lookup time will more than make up for it. However if you're only going to be checking one word per command execution (eg. this is a commandline app like "checkenglish [word]" ) the startup time will be longer than it would have taken you just to search through the file line by line.</p>
<p>If this is your situation, or you have a much bigger dataset, using an on-disk format may be better. The simplest way would be using the <a href="http://docs.python.org/library/dbm.html" rel="nofollow">dbm</a> module. Create such a database from a wordlist with:</p>
<pre><code>import dbm
f=open('wordlist.txt')
db = dbm.open('words.db','c')
for word in f:
db[word] = '1'
f.close()
db.close()
</code></pre>
<p>Then your program can check membership with:</p>
<pre><code>db = dbm.open('words.db','r')
if db.has_key(word):
print "%s is english" % word
else:
print "%s is not english" % word
</code></pre>
<p>This will be slower than a set lookup, since there will be disk access, but will be faster than searching, have low memory use and no significant initialisation time.</p>
<p>There are also other alternatives, such as using a SQL database (eg sqlite).</p>
| 2 | 2009-05-16T13:59:46Z | [
"python",
"string"
] |
port python code to javascript | 872,366 | <pre><code>indices[i:] = indices[i+1:] + indices[i:i+1]
</code></pre>
<p>Hope someone helps.</p>
| 0 | 2009-05-16T12:45:33Z | 872,371 | <p>You will want to look at <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Array/slice" rel="nofollow">Array.slice()</a></p>
<pre><code>var temp=indices.slice(i+1).concat(indices.slice(i, i+1));
var arr=[];
for (var j=0; j<temp.length; j++){
arr[j+i]=temp[i];
}
</code></pre>
| 1 | 2009-05-16T12:49:51Z | [
"javascript",
"python",
"porting"
] |
port python code to javascript | 872,366 | <pre><code>indices[i:] = indices[i+1:] + indices[i:i+1]
</code></pre>
<p>Hope someone helps.</p>
| 0 | 2009-05-16T12:45:33Z | 873,737 | <p>I'm fairly new to Python but if I understand the code correctly, it reconstructs a list from a given offset into every item following offset+1 and the item at the offset.</p>
<p>Running it seems to confirm this:</p>
<pre><code>>>> indices = ['one','two','three','four','five','six']
>>> i = 2
>>> indices[i:] = indices[i+1:] + indices[i:i+1]
>>> indices
['one', 'two', 'four', 'five', 'six', 'three']
</code></pre>
<p>In Javascript can be written:</p>
<pre><code>indices = indices.concat( indices.splice( i, 1 ) );
</code></pre>
<p>Same entire sequence would go:</p>
<pre><code>>>> var indices = ['one','two','three','four','five','six'];
>>> var i = 2;
>>> indices = indices.concat( indices.splice( i, 1 ) );
>>> indices
["one", "two", "four", "five", "six", "three"]
</code></pre>
<p>This works because <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Array/splice" rel="nofollow">splice</a> is destructive to the array but returns removed elements, which may then be handed to <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Array/concat" rel="nofollow">concat</a>. </p>
| 6 | 2009-05-17T02:02:09Z | [
"javascript",
"python",
"porting"
] |
numpy linear algebra basic help | 872,376 | <p>This is what I need to do-</p>
<p>I have this equation-</p>
<p>Ax = y</p>
<p>Where A is a rational m*n matrix (m<=n), and x and y are vectors of
the right size. I know A and y, I don't know what x is equal to. I
also know that there is no x where Ax equals exactly y.
I want to find the vector x' such that Ax' is as close as possible to
y. Meaning that (Ax' - y) is as close as possible to (0,0,0,...0).</p>
<p>I know that I need to use either the lstsq function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq</a></p>
<p>or the svd function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd</a></p>
<p>I don't understand the documentation at all. Can someone please show
me how to use these functions to solve my problem.</p>
<p>Thanks a lot!!!</p>
| 2 | 2009-05-16T12:53:23Z | 872,445 | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq" rel="nofollow">updated documentation</a> may be a bit more helpful... looks like you want</p>
<pre><code>numpy.linalg.lstsq(A, y)
</code></pre>
| 2 | 2009-05-16T13:33:44Z | [
"python",
"numpy",
"scipy",
"linear-algebra",
"svd"
] |
numpy linear algebra basic help | 872,376 | <p>This is what I need to do-</p>
<p>I have this equation-</p>
<p>Ax = y</p>
<p>Where A is a rational m*n matrix (m<=n), and x and y are vectors of
the right size. I know A and y, I don't know what x is equal to. I
also know that there is no x where Ax equals exactly y.
I want to find the vector x' such that Ax' is as close as possible to
y. Meaning that (Ax' - y) is as close as possible to (0,0,0,...0).</p>
<p>I know that I need to use either the lstsq function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq</a></p>
<p>or the svd function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd</a></p>
<p>I don't understand the documentation at all. Can someone please show
me how to use these functions to solve my problem.</p>
<p>Thanks a lot!!!</p>
| 2 | 2009-05-16T12:53:23Z | 872,447 | <p>SVD is for the case of m < n, because you don't really have enough degrees of freedom.</p>
<p>The docs for lstsq don't look very helpful. I believe that's least square fitting, for the case where m > n.</p>
<p>If m < n, you'll want <a href="http://web.mit.edu/be.400/www/SVD/Singular%5FValue%5FDecomposition.htm" rel="nofollow">SVD</a>. </p>
| 0 | 2009-05-16T13:34:35Z | [
"python",
"numpy",
"scipy",
"linear-algebra",
"svd"
] |
numpy linear algebra basic help | 872,376 | <p>This is what I need to do-</p>
<p>I have this equation-</p>
<p>Ax = y</p>
<p>Where A is a rational m*n matrix (m<=n), and x and y are vectors of
the right size. I know A and y, I don't know what x is equal to. I
also know that there is no x where Ax equals exactly y.
I want to find the vector x' such that Ax' is as close as possible to
y. Meaning that (Ax' - y) is as close as possible to (0,0,0,...0).</p>
<p>I know that I need to use either the lstsq function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#lstsq</a></p>
<p>or the svd function:
<a href="http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd" rel="nofollow">http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html#svd</a></p>
<p>I don't understand the documentation at all. Can someone please show
me how to use these functions to solve my problem.</p>
<p>Thanks a lot!!!</p>
| 2 | 2009-05-16T12:53:23Z | 872,452 | <p>The SVD of matrix A gives you orthogonal matrices U and V and diagonal matrix Σ such that </p>
<p><strong>A</strong> = <strong>U</strong> <strong>Σ</strong> <strong>V</strong> <sup>T</sup></p>
<p>where
<strong>U</strong> <strong>U</strong><sup>T</sup> = <strong>I</strong> ;
<strong>V</strong> <strong>V</strong><sup>T</sup> = <strong>I</strong></p>
<p>Hence, if</p>
<p><strong>x</strong> <strong>A</strong> = <strong>y</strong></p>
<p>then</p>
<p><strong>x</strong> <strong>U</strong> <strong>Σ</strong> <strong>V</strong> <sup>T</sup> = <strong>y</strong></p>
<p><strong>x</strong> <strong>U</strong> <strong>Σ</strong> <strong>V</strong> <sup>T</sup> <strong>V</strong> = <strong>y</strong> <strong>V</strong></p>
<p><strong>x</strong> <strong>U</strong> <strong>Σ</strong> = <strong>y</strong> <strong>V</strong></p>
<p><strong>U</strong> <sup>T</sup> <strong>x</strong> <strong>Σ</strong> = <strong>y</strong> <strong>V</strong></p>
<p><strong>x</strong> <strong>Σ</strong> = <strong>U</strong> <strong>y</strong> <strong>V</strong></p>
<p><strong>x</strong> = <strong>Σ</strong> <sup>-1</sup> <strong>U</strong> <sup>T</sup> <strong>y</strong> <strong>V</strong> </p>
<p><strong>x</strong> = <strong>V</strong> <sup>T</sup> <strong>Σ</strong> <sup>-1</sup> <strong>U</strong> <sup>T</sup> <strong>y</strong> </p>
<p>So given SVD of <strong>A</strong> you can get <strong>x</strong>.</p>
<p><hr></p>
<p>Although for general matrices <strong>A B</strong> != <strong>B A</strong>, it is true for vector <strong>x</strong> that <strong>x U</strong> == <strong>U</strong> <sup>T</sup> <strong>x</strong>.</p>
<p>For example, consider <strong>x</strong> = ( x, y ), <strong>U</strong> = ( a, b ; c, d ): </p>
<p><strong>x</strong> <strong>U</strong> = ( x, y ) ( a, b ; c, d )</p>
<p>= ( xa+yc, xb+yd ) </p>
<p>= ( ax+cy, bx+dy ) </p>
<p>= ( a, c; b, d ) ( x; y )</p>
<p>= <strong>U</strong> <sup>T</sup> <strong>x</strong></p>
<p>It's fairly obvious when you look at the values in <strong>x</strong> <strong>U</strong> being the dot products of <strong>x</strong> and the columns of <strong>U</strong>, and the values in <strong>U</strong><sup>T</sup><strong>x</strong> being the dot products of the <strong>x</strong> and the rows of <strong>U</strong><sup>T</sup>, and the relation of rows and columns in transposition </p>
| 0 | 2009-05-16T13:37:08Z | [
"python",
"numpy",
"scipy",
"linear-algebra",
"svd"
] |
Some help with some Python code | 872,566 | <p>Can anyone tell me why num_chars and num_rows have to be the same?</p>
<pre><code>from ctypes import *
num_chars = 8
num_rows = 8
num_cols = 6
buffer = create_string_buffer (num_chars*num_rows*num_cols+num_chars)
for char in range(num_chars):
for row in range(num_rows):
for col in range(num_cols):
if char == num_chars-1 and col == num_cols-1:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = '|'
buffer[row*num_rows*num_cols+char*num_cols+col+row+1] = '\n'
elif col == num_cols-1:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = '|'
else:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = ('.', '*')[char>row]
print buffer.value
</code></pre>
<p>The output</p>
<pre><code>.....|*****|*****|*****|*****|*****|*****|*****|
.....|.....|*****|*****|*****|*****|*****|*****|
.....|.....|.....|*****|*****|*****|*****|*****|
.....|.....|.....|.....|*****|*****|*****|*****|
.....|.....|.....|.....|.....|*****|*****|*****|
.....|.....|.....|.....|.....|.....|*****|*****|
.....|.....|.....|.....|.....|.....|.....|*****|
.....|.....|.....|.....|.....|.....|.....|.....|
</code></pre>
<p>And now changing num_chars to 15.</p>
<pre><code>.....|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
.....|*****|*****|*****|*****|*****|*****|*****|
</code></pre>
| -3 | 2009-05-16T14:49:34Z | 872,633 | <p>You said you are using ctypes because you want mutable char buffer for this. But you can get the output you want from list comprehension</p>
<pre><code>num_chars = 5
num_rows = 8
empty = ['.' * num_chars]
full = ['*' * num_chars]
print '\n'.join(
'|'.join(empty * (i + 1) + (num_rows - i - 1) * full)
for i in xrange(num_rows)
)
.....|*****|*****|*****|*****|*****|*****|*****
.....|.....|*****|*****|*****|*****|*****|*****
.....|.....|.....|*****|*****|*****|*****|*****
.....|.....|.....|.....|*****|*****|*****|*****
.....|.....|.....|.....|.....|*****|*****|*****
.....|.....|.....|.....|.....|.....|*****|*****
.....|.....|.....|.....|.....|.....|.....|*****
.....|.....|.....|.....|.....|.....|.....|.....
</code></pre>
<p><strong>EDIT</strong></p>
<p>I'll show you how you can use list comprehensions to draw whatever char bitmap you want to draw. The idea is simple. Build a boolean array with True in the places you want to print the character and False otherwise. And just use the 'or' trick to print the right character. This example will build a chess like board. You can use the same concept to draw any shape you want.</p>
<pre><code>rows = 5
cols = 6
char = '#'
empty = '.'
bitmap = [[ (i + j)%2 == 0 for i in xrange(cols)] for j in xrange(rows)]
print '\n'.join(
'|'.join(bitmap[j][i] * char or empty for i in xrange(cols))
for j in xrange(rows)
)
</code></pre>
| 5 | 2009-05-16T15:26:44Z | [
"python",
"ctypes"
] |
Some help with some Python code | 872,566 | <p>Can anyone tell me why num_chars and num_rows have to be the same?</p>
<pre><code>from ctypes import *
num_chars = 8
num_rows = 8
num_cols = 6
buffer = create_string_buffer (num_chars*num_rows*num_cols+num_chars)
for char in range(num_chars):
for row in range(num_rows):
for col in range(num_cols):
if char == num_chars-1 and col == num_cols-1:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = '|'
buffer[row*num_rows*num_cols+char*num_cols+col+row+1] = '\n'
elif col == num_cols-1:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = '|'
else:
buffer[row*num_rows*num_cols+char*num_cols+col+row] = ('.', '*')[char>row]
print buffer.value
</code></pre>
<p>The output</p>
<pre><code>.....|*****|*****|*****|*****|*****|*****|*****|
.....|.....|*****|*****|*****|*****|*****|*****|
.....|.....|.....|*****|*****|*****|*****|*****|
.....|.....|.....|.....|*****|*****|*****|*****|
.....|.....|.....|.....|.....|*****|*****|*****|
.....|.....|.....|.....|.....|.....|*****|*****|
.....|.....|.....|.....|.....|.....|.....|*****|
.....|.....|.....|.....|.....|.....|.....|.....|
</code></pre>
<p>And now changing num_chars to 15.</p>
<pre><code>.....|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
*****|*****|*****|*****|*****|*****|*****|*****|
.....|*****|*****|*****|*****|*****|*****|*****|
</code></pre>
| -3 | 2009-05-16T14:49:34Z | 872,742 | <p>There we go. I had row*num_rows instead of row*num_chars I must need a Dr Pepper. And by the way, this wasn't homework. It's for an LCD project.</p>
<pre><code>num_chars = 10
num_rows = 8
num_cols = 6
buffer = create_string_buffer (num_chars*num_rows*num_cols+num_chars)
for char in range(num_chars):
for row in range(num_rows):
for col in range(num_cols):
if char == num_chars-1 and col == num_cols-1:
buffer[row*num_chars*num_cols+char*num_cols+col+row] = '|'
buffer[row*num_chars*num_cols+char*num_cols+col+row+1] = '\n'
elif col == num_cols-1:
buffer[row*num_chars*num_cols+char*num_cols+col+row] = '|'
else:
buffer[row*num_chars*num_cols+char*num_cols+col+row] = ('.', '*')[char>row]
print repr(buffer.raw)
print buffer.value
</code></pre>
| 1 | 2009-05-16T16:20:43Z | [
"python",
"ctypes"
] |
Python generates an IO error while interleaving open/close/readline/write on the same file | 872,680 | <p>I'm learning Python-this gives me an IO error-</p>
<pre><code>f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Thanks!</p>
| 1 | 2009-05-16T15:53:13Z | 872,690 | <p>You close your file only if the IF condition is satisfied, otherwise you attempt to reopen it after the IF block. Depending on the result you want to achieve you will want to either remove the f.close call, or add an ELSE branch and remove the second f.open call. Anyway let me warn you that the str(now) in your IF block is just deprecated as you're not saving the result of that call anywhere.</p>
| 0 | 2009-05-16T15:58:19Z | [
"python",
"python-3.x"
] |
Python generates an IO error while interleaving open/close/readline/write on the same file | 872,680 | <p>I'm learning Python-this gives me an IO error-</p>
<pre><code>f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Thanks!</p>
| 1 | 2009-05-16T15:53:13Z | 872,693 | <p>well theres a couple of things...</p>
<p>you <code>open(money.txt)</code> outside the while loop but you close it after the first iteration...
(technically you close, reopen & close again)</p>
<p>Put when the loop comes round the second time, <code>f</code> will be closed and f.readLine() will most likely fail</p>
| 2 | 2009-05-16T15:58:57Z | [
"python",
"python-3.x"
] |
Python generates an IO error while interleaving open/close/readline/write on the same file | 872,680 | <p>I'm learning Python-this gives me an IO error-</p>
<pre><code>f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Thanks!</p>
| 1 | 2009-05-16T15:53:13Z | 872,698 | <p>The <code>while True</code> is going to loop forever unless you break it with <code>break</code>.</p>
<p>The I/O error is probably because when you have run through the loop once the last thing you do is <code>f.close()</code>, which closes the file. When execution continues with the loop in the line <code>currentmoney = float(f.readline())</code>: <code>f</code> will be a closed filehandle that you can't read from.</p>
| 3 | 2009-05-16T16:02:47Z | [
"python",
"python-3.x"
] |
Python generates an IO error while interleaving open/close/readline/write on the same file | 872,680 | <p>I'm learning Python-this gives me an IO error-</p>
<pre><code>f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Thanks!</p>
| 1 | 2009-05-16T15:53:13Z | 872,719 | <p>You'll get an IO Error on your first line if money.txt doesn't exist.</p>
| 0 | 2009-05-16T16:12:39Z | [
"python",
"python-3.x"
] |
Python generates an IO error while interleaving open/close/readline/write on the same file | 872,680 | <p>I'm learning Python-this gives me an IO error-</p>
<pre><code>f = open('money.txt')
while True:
currentmoney = float(f.readline())
print(currentmoney, end='')
if currentmoney >= 0:
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
str(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Thanks!</p>
| 1 | 2009-05-16T15:53:13Z | 872,776 | <p>Can I piggyback a question? The following has puzzled me for some time. I always get an IOError from these 'open()' statements, so I've stopped checking for the error. (Don't like to do that!) What's wrong with my code? The 'if IOError:' test shown in comments was originally right after the statement with 'open()'.</p>
<pre><code>if __name__ == '__main__':
#get name of input file and open() infobj
infname = sys.argv[1]
print 'infname is: %s' % (sys.argv[1])
infobj = open( infname, 'rU' )
print 'infobj is: %s' % infobj
# 'if IOError:' always evals to True!?!
# if IOError:
# print 'IOError opening file tmp with mode rU.'
# sys.exit( 1)
#get name of output file and open() outfobj
outfname = sys.argv[2]
print 'outfname is: %s' % (sys.argv[2])
outfobj = open( outfname, 'w' )
print 'outfobj is: %s' % outfobj
# if IOError:
# print 'IOError opening file otmp with mode w.'
# sys.exit( 2)
</code></pre>
| 0 | 2009-05-16T16:40:00Z | [
"python",
"python-3.x"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 872,710 | <p>Perhaps I misunderstand your question, but both Python and PHP support both procedural and object-oriented programming. (Though one could argue that Python's support for OO is the stronger of the two.)</p>
| -1 | 2009-05-16T16:09:08Z | [
"php",
"python",
"mod-python"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 872,715 | <p>See <a href="http://www.php.net/zend-engine-2.php" rel="nofollow">Class and Objects in PHP 5</a></p>
| -1 | 2009-05-16T16:11:11Z | [
"php",
"python",
"mod-python"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 872,824 | <p>Because mod_python is abstracting the URL into a "RPC-like" mechanism. You can achieve the same in PHP. I always did it by hand, but I am pretty sure there are prepackaged pear modules for this.</p>
<p>Note the mod_python behavior is not forcibly "the best". It all amounts to the type of design you want to give to your application, and how it behaves to the clients. As far as I see, the mod_python approach assumes that for every URL you have a function, like mapping the module structure into a URL tree. This is technically not a particularly nice approach, because there's a tight correlation between the technology you are using (mod_python) and the URL layout of your application.</p>
<p>On the reason <em>why</em>, theres' no reason. Some people like one food, and some other like another. Design is, in some cases, a matter of taste and artistic choices, not only technical restrains. </p>
| 4 | 2009-05-16T17:05:39Z | [
"php",
"python",
"mod-python"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 872,913 | <p>I think you have some misconceptions about how HTTP works. Nothing in the http standard requires you to have a certain file as a resource. It is just the way how mod_php works, that for a given path, this path is translated to a php file on the disk of the server, which in turn is interpreted by the compiler.</p>
<p>The *mod_python* module on the other hand is much more generic, it allows you to map any resource to a call to some python object. It just happens that some configurations are available out of the box, to make it easier to start with. In most cases the dispatch of the url is managed by your framework, and how that works is up to the framework implementor.</p>
<p>Because of the generic nature of the *mod_python* module you are also able to access some apache features which are not available in the *mod_php* module, for instance you may write your own authentication handler, which my not only apply to your python webapp, but also to other apps in your apache as well.</p>
| 4 | 2009-05-16T17:54:27Z | [
"php",
"python",
"mod-python"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 873,822 | <p>Let's talk about mod_python vs. mod_php.</p>
<p>Since the Python language is NOT specifically designed for serving web pages, mod_python must do some additional work. </p>
<p>Since the PHP language IS specifically designed to serve web pages, mod_php simply starts a named PHP module.</p>
<p>In the case of mod_python (different from mod_fastcgi or mod_wsgi), the designer of mod_python decided that the best way to invoke Python is to call a method of an object defined in a module. Hopefully, that method of that object will write the headers and web page content to stdout. </p>
<p>In the case of mod_wsgi, the designer decided that the best way to invoke Python is to call a function (or callable object) in a module. Hopefully that function will use the supplied object to create header and return a list strings with the web page content.</p>
<p>In the case of mod_php, they just invoke the module because PHP modules are designed to serve web pages. The program runs and the result of that run is a page of content; usually HTML.</p>
<p>The reason mod_php works one way, mod_python works another and mod_wsgi works a third way is because they're different. Written by different people with different definitions of the way to produce a web page. </p>
<p>The php page can be object-oriented. A mod_wsgi function may be a callable object or it may be a simplef unction. Those are design choices.</p>
<p>The mod_python requirement for a class is a design choice made by the designer of mod_python.</p>
<p>The reason "why" is never useful. The reason "why" is because someone decided to design it that way.</p>
| 5 | 2009-05-17T03:02:35Z | [
"php",
"python",
"mod-python"
] |
mod_php vs mod_python | 872,695 | <p><strong>Why mod_python is oop but mod_php is not ?</strong></p>
<p><em>Example :We go to www.example.com/dir1/dir2</em></p>
<p>if you use mod_python apache opens www/dir1.py and calls dir2 method
but if you use php module apache opens www/dir1/dir2/index.php</p>
| 2 | 2009-05-16T16:01:54Z | 873,885 | <p>in PHP you can program your web pages the top-to-bottom scripts, procedural programming and function calls, OOP. this is the main reason why PHP was first created, and how it evolved. mod_php is just a module for web servers to utilize PHP as a preprocessor. so it just passes HTTP information and the PHP script to PHP interpreter.
the PHP way of web page creation is do what you want; write a top-to-bottom script, define functions in different files and include those and call functions, or write your app in OOP, you can also use many full-featured frameworks today to make sure your application design and structure meets today best practices and design patterns.</p>
<p>I'm new to Python, and am not familiar with web programming with python. but as much as I know, python was not created to make web programming easier. it was intended to be a general purpose programming language, so although it might be possible to write simple top-to-bottom scripts in python and run them as web page responses (I'm not sure if such thing is possible), it is not the pythonic way, and so I think developers of the mod_python wanted web programming in python to be in a pythonic way.</p>
| 0 | 2009-05-17T04:11:45Z | [
"php",
"python",
"mod-python"
] |
does someone know how to show content on screen (covering up any window) using Ruby or Python? | 872,737 | <p>using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).</p>
| 1 | 2009-05-16T16:19:40Z | 872,757 | <p>You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby.
Alternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure that the chosen toolkit supports 'always-on-top' options on your desired platform(s).</p>
| 4 | 2009-05-16T16:28:43Z | [
"python",
"ruby",
"user-interface"
] |
does someone know how to show content on screen (covering up any window) using Ruby or Python? | 872,737 | <p>using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).</p>
| 1 | 2009-05-16T16:19:40Z | 873,907 | <p>If you are on windows you can directly draw to desktop dc(device context) using win32api
e.g. just for fun try this :)</p>
<pre><code>>>> import win32ui
>>> import win32gui
>>> hdc = win32ui.CreateDCFromHandle( win32gui.GetDC( 0 ) )
>>> hdc.DrawText("Wow it works", (100, 100, 200, 200))
>>> hdc.LineTo(500,500)
</code></pre>
<p>but that won't be very useful ,as not erasable</p>
<p>best bet would be to use a transparent window or window with a cutout region (atleast on windows that is possible)
or even if you can't draw transparent on some system you can grab the current screen and display it as background of you window that would give a transparent effect</p>
| 2 | 2009-05-17T04:34:05Z | [
"python",
"ruby",
"user-interface"
] |
does someone know how to show content on screen (covering up any window) using Ruby or Python? | 872,737 | <p>using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).</p>
| 1 | 2009-05-16T16:19:40Z | 873,925 | <p>I would recommend PyGame.</p>
| 1 | 2009-05-17T04:49:44Z | [
"python",
"ruby",
"user-interface"
] |
pycurl: RETURNTRANSFER option doesn't exist | 872,844 | <p>I'm using pycurl to access a JSON web API, but when I try to use the following: </p>
<pre><code>ocurl.setopt(pycurl.URL, gaurl) # host + endpoint
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers
ocurl.setopt(pycurl.CUSTOMREQUEST, "POST") # HTTP POST req
ocurl.setopt(pycurl.CONNECTTIMEOUT, 2)
</code></pre>
<p>and execute the script, it fails.</p>
<pre><code>File "getdata.py", line 46, in apicall
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
AttributeError: 'module' object has no attribute 'RETURNTRANSFER'
</code></pre>
<p>I haven't a clue what's going on, and why RETURNTRANSFER doesn't appear to exist while all the other options do.</p>
| 6 | 2009-05-16T17:23:13Z | 872,861 | <p>Have you tried executing <code>print dir(pycurl)</code> and see if the option exists in the attribute list?</p>
| -1 | 2009-05-16T17:32:18Z | [
"python",
"curl",
"libcurl",
"pycurl",
"attributeerror"
] |
pycurl: RETURNTRANSFER option doesn't exist | 872,844 | <p>I'm using pycurl to access a JSON web API, but when I try to use the following: </p>
<pre><code>ocurl.setopt(pycurl.URL, gaurl) # host + endpoint
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers
ocurl.setopt(pycurl.CUSTOMREQUEST, "POST") # HTTP POST req
ocurl.setopt(pycurl.CONNECTTIMEOUT, 2)
</code></pre>
<p>and execute the script, it fails.</p>
<pre><code>File "getdata.py", line 46, in apicall
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
AttributeError: 'module' object has no attribute 'RETURNTRANSFER'
</code></pre>
<p>I haven't a clue what's going on, and why RETURNTRANSFER doesn't appear to exist while all the other options do.</p>
| 6 | 2009-05-16T17:23:13Z | 872,876 | <p>The manual shows the usage being <a href="http://pycurl.sourceforge.net/doc/curlobject.html" rel="nofollow">something like this</a>:</p>
<pre><code>>>> import pycurl
>>> import StringIO
>>> b = StringIO.StringIO()
>>> conn = pycurl.Curl()
>>> conn.setopt(pycurl.URL, 'http://www.example.org')
>>> conn.setopt(pycurl.WRITEFUNCTION, b.write)
>>> conn.perform()
>>> print b.getvalue()
<HTML>
<HEAD>
<TITLE>Example Web Page</TITLE>
</HEAD>
<body>
<p>You have reached this web page by typing &quot;example.com&quot;,
&quot;example.net&quot;,
or &quot;example.org&quot; into your web browser.</p>
<p>These domain names are reserved for use in documentation and are not availabl
e
for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC
2606</a>, Section 3.</p>
</BODY>
</HTML>
</code></pre>
<p>Seems a little roundabout, but I'm not a big fan of PycURL...</p>
| 4 | 2009-05-16T17:39:01Z | [
"python",
"curl",
"libcurl",
"pycurl",
"attributeerror"
] |
pycurl: RETURNTRANSFER option doesn't exist | 872,844 | <p>I'm using pycurl to access a JSON web API, but when I try to use the following: </p>
<pre><code>ocurl.setopt(pycurl.URL, gaurl) # host + endpoint
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers
ocurl.setopt(pycurl.CUSTOMREQUEST, "POST") # HTTP POST req
ocurl.setopt(pycurl.CONNECTTIMEOUT, 2)
</code></pre>
<p>and execute the script, it fails.</p>
<pre><code>File "getdata.py", line 46, in apicall
ocurl.setopt(pycurl.RETURNTRANSFER, 1)
AttributeError: 'module' object has no attribute 'RETURNTRANSFER'
</code></pre>
<p>I haven't a clue what's going on, and why RETURNTRANSFER doesn't appear to exist while all the other options do.</p>
| 6 | 2009-05-16T17:23:13Z | 873,206 | <p>CURLOPT_RETURNTRANSFER is not a libcurl option, it is but provided within the PHP/CURL binding</p>
| 4 | 2009-05-16T20:18:55Z | [
"python",
"curl",
"libcurl",
"pycurl",
"attributeerror"
] |
Pythonic Way to Initialize (Complex) Static Data Members | 872,973 | <p>I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this:</p>
<pre><code>def generate_data():
... do some analysis and return complex object e.g. list ...
class Coo:
data_member = generate_data()
... rest of class code ...
</code></pre>
<p>The function <code>generate_data</code> takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated.</p>
<p>Also, to verify, as long as I don't assign anything to <code>data_member</code> in <code>__init__</code>, it will remain "static"? What if a method in Coo appends some value to <code>data_member</code> (assuming it's a list) - will this addition be available to the rest of the instances?</p>
<p>Thanks</p>
| 12 | 2009-05-16T18:20:29Z | 872,989 | <p>You're right on all counts. <code>data_member</code> will be created once, and will be available to all instances of <code>coo</code>. If any instance modifies it, that modification will be visible to all other instances.</p>
<p>Here's an example that demonstrates all this, with its output shown at the end:</p>
<pre><code>def generate_data():
print "Generating"
return [1,2,3]
class coo:
data_member = generate_data()
def modify(self):
self.data_member.append(4)
def display(self):
print self.data_member
x = coo()
y = coo()
y.modify()
x.display()
# Output:
# Generating
# [1, 2, 3, 4]
</code></pre>
| 13 | 2009-05-16T18:27:32Z | [
"python",
"class"
] |
Pythonic Way to Initialize (Complex) Static Data Members | 872,973 | <p>I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this:</p>
<pre><code>def generate_data():
... do some analysis and return complex object e.g. list ...
class Coo:
data_member = generate_data()
... rest of class code ...
</code></pre>
<p>The function <code>generate_data</code> takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated.</p>
<p>Also, to verify, as long as I don't assign anything to <code>data_member</code> in <code>__init__</code>, it will remain "static"? What if a method in Coo appends some value to <code>data_member</code> (assuming it's a list) - will this addition be available to the rest of the instances?</p>
<p>Thanks</p>
| 12 | 2009-05-16T18:20:29Z | 872,994 | <p>The statement <code>data_member = generate_data()</code> will be executed only once, when <code>class coo: ...</code> is executed. In majority of cases class statements occur at module level and are executed when module is imported. So <code>data_member = generate_data()</code> will be executed only once when you import module with class <code>coo</code> for the first time.</p>
<p>All instances of <code>coo</code> class will share <code>data_member</code> and can access it by writing <code>coo.data_member</code>. Any changes made to <code>coo.data_member</code> will be immediately visible by any <code>coo</code> instance. An instance can have its own <code>data_member</code> attribute. This attribute can be set by typing <code>self.data_member = ...</code> and will be visible only to that instance. The "static" <code>data_member</code> can still be accessed by typing <code>coo.data_member</code>.</p>
| 5 | 2009-05-16T18:29:16Z | [
"python",
"class"
] |
Pythonic Way to Initialize (Complex) Static Data Members | 872,973 | <p>I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this:</p>
<pre><code>def generate_data():
... do some analysis and return complex object e.g. list ...
class Coo:
data_member = generate_data()
... rest of class code ...
</code></pre>
<p>The function <code>generate_data</code> takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated.</p>
<p>Also, to verify, as long as I don't assign anything to <code>data_member</code> in <code>__init__</code>, it will remain "static"? What if a method in Coo appends some value to <code>data_member</code> (assuming it's a list) - will this addition be available to the rest of the instances?</p>
<p>Thanks</p>
| 12 | 2009-05-16T18:20:29Z | 873,083 | <p>As others have answered you're right -- I'll add one more thing to be aware of: If an instance modifies the object <code>coo.data_member</code> itself, for example</p>
<pre><code>self.data_member.append('foo')
</code></pre>
<p>then the modification is seen by the rest of the instances. However if you do </p>
<pre><code>self.data_member = new_object
</code></pre>
<p>then a new <em>instance</em> member is created which overrides the class member and is only visible to that instance, not the others. The difference is not always easy to spot, for example <code>self.data_member += 'foo'</code> vs. <code>self.data_member = self.data_member + 'foo'</code>.</p>
<p>To avoid this you probably should always refer to the object as <code>coo.data_member</code> (not through <code>self</code>).</p>
| 11 | 2009-05-16T19:15:53Z | [
"python",
"class"
] |
How do you pass script arguments to pdb (Python)? | 873,089 | <p>I've got python script (ala #! /usr/bin/python) and I want to debug it with pdb. How can I pass arguments to the script?</p>
<p>I have a python script and would like to debug it with pdb. Is there a way that I can pass arguments to the scripts?</p>
| 8 | 2009-05-16T19:17:41Z | 873,136 | <pre><code>python -m pdb myscript.py arg1 arg2 ...
</code></pre>
<p>This invokes <code>pdb</code> as a script to debug another script. You can pass command-line arguments after the script name. See the <a href="http://docs.python.org/library/pdb.html">pdb doc page</a> for more details.</p>
| 15 | 2009-05-16T19:39:12Z | [
"python",
"debugging",
"arguments",
"pdb"
] |
How do you pass script arguments to pdb (Python)? | 873,089 | <p>I've got python script (ala #! /usr/bin/python) and I want to debug it with pdb. How can I pass arguments to the script?</p>
<p>I have a python script and would like to debug it with pdb. Is there a way that I can pass arguments to the scripts?</p>
| 8 | 2009-05-16T19:17:41Z | 32,846,913 | <p>If, like me, you prefer the more graphical <a href="https://pypi.python.org/pypi/pudb" rel="nofollow">pudb</a> debugger, you can pass the arguments of your script directly by doing:</p>
<pre><code>pudb myscript.py arg1 arg2 ...
</code></pre>
<p>Indeed, invoking:</p>
<pre><code> python -m pudb myscript.py arg1 arg2 ...
</code></pre>
<p>won't work will return with the following error:</p>
<pre><code>No module named pudb.__main__; 'pudb' is a package and cannot be directly executed
</code></pre>
| 0 | 2015-09-29T14:41:07Z | [
"python",
"debugging",
"arguments",
"pdb"
] |
Python's most efficient way to choose longest string in list? | 873,327 | <p>I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1</p>
<p>For example:</p>
<pre><code>mylist = ['123','123456','1234']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
</code></pre>
<p>I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?</p>
<p>Thanks!</p>
| 89 | 2009-05-16T21:15:30Z | 873,333 | <p>From the <a href="http://docs.python.org/whatsnew/2.5.html#other-language-changes">Python documentation</a> itself, you can use <a href="http://docs.python.org/library/functions.html#max"><code>max</code></a>:</p>
<pre><code>>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
</code></pre>
| 253 | 2009-05-16T21:19:46Z | [
"python",
"list",
"list-comprehension"
] |
Python's most efficient way to choose longest string in list? | 873,327 | <p>I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1</p>
<p>For example:</p>
<pre><code>mylist = ['123','123456','1234']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
</code></pre>
<p>I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?</p>
<p>Thanks!</p>
| 89 | 2009-05-16T21:15:30Z | 873,337 | <p><code>len(each) == max(len(x) for x in myList)</code> or just <code>each == max(myList, key=len)</code></p>
| 1 | 2009-05-16T21:20:36Z | [
"python",
"list",
"list-comprehension"
] |
Python's most efficient way to choose longest string in list? | 873,327 | <p>I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1</p>
<p>For example:</p>
<pre><code>mylist = ['123','123456','1234']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
</code></pre>
<p>I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?</p>
<p>Thanks!</p>
| 89 | 2009-05-16T21:15:30Z | 873,338 | <blockquote>
<p>To get the smallest or largest item in a list, use the built-in min and
max functions:</p>
<pre><code>lo = min(L)
hi = max(L) As with sort (see below), you can pass in a key function
</code></pre>
<p>that is used to map the list items
before they are compared:</p>
<pre><code>lo = min(L, key=int)
hi = max(L, key=int)
</code></pre>
</blockquote>
<p><a href="http://effbot.org/zone/python-list.htm" rel="nofollow">http://effbot.org/zone/python-list.htm</a></p>
<p>Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.</p>
| 0 | 2009-05-16T21:20:49Z | [
"python",
"list",
"list-comprehension"
] |
Python's most efficient way to choose longest string in list? | 873,327 | <p>I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1</p>
<p>For example:</p>
<pre><code>mylist = ['123','123456','1234']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
</code></pre>
<p>I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?</p>
<p>Thanks!</p>
| 89 | 2009-05-16T21:15:30Z | 873,345 | <p>What should happen if there are more than 1 longest string (think '12', and '01')?</p>
<p>Try that to get the longest element</p>
<pre><code>max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
</code></pre>
<p>And then regular foreach</p>
<pre><code>for st in mylist:
if len(st)==max_length:...
</code></pre>
| 2 | 2009-05-16T21:22:37Z | [
"python",
"list",
"list-comprehension"
] |
Python's most efficient way to choose longest string in list? | 873,327 | <p>I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1</p>
<p>For example:</p>
<pre><code>mylist = ['123','123456','1234']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
</code></pre>
<p>I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?</p>
<p>Thanks!</p>
| 89 | 2009-05-16T21:15:30Z | 7,856,314 | <pre><code>def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
</code></pre>
| 0 | 2011-10-21T23:21:47Z | [
"python",
"list",
"list-comprehension"
] |
How do I put a scrollbar inside of a gtk.ComboBoxEntry? | 873,328 | <p>I have a Combobox with over a hundred of entries and it is very awkward to skim through with out a scrollbar.</p>
<p><img src="http://img211.imageshack.us/img211/6972/screenshotprubapy.png" alt="alt text" /></p>
<p>I want to do exactly what is in the picture. With the scrollbar on the right so It'd be easier to move through the entries. I used gtk.Combo to make that example but the problem is that is deprecated. </p>
<p>I need an example of how would you do what is <strong>exactly</strong> the picture.</p>
| 2 | 2009-05-16T21:15:53Z | 874,475 | <pre><code>import pygtk
import gtk
import gobject
def window_delete_event(*args):
return False
def window_destroy(*args):
gtk.main_quit()
if __name__ == '__main__':
win = gtk.Window()
# combo's model
model = gtk.ListStore(gobject.TYPE_STRING)
for n in xrange(100):
model.append([str(n)])
# combo
combo = gtk.ComboBoxEntry(model)
win.add(combo)
# combo's style
style = gtk.rc_parse_string('''
style "my-style" { GtkComboBox::appears-as-list = 1 }
widget "*.mycombo" style "my-style"
''')
combo.set_name('mycombo')
combo.set_style(style)
win.show_all()
win.connect('delete-event', window_delete_event)
win.connect('destroy', window_destroy)
gtk.main()
</code></pre>
| 2 | 2009-05-17T12:06:32Z | [
"python",
"user-interface",
"pygtk"
] |
Converting to safe unicode in python | 873,419 | <p>I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error.</p>
<pre><code>Incorrect string value: '\xEF\xBF\xBDs m...'
</code></pre>
<p>My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion.</p>
<pre><code>s = unicode(content, "utf-8", errors="replace")
</code></pre>
<p>Without the above unicode conversion, the error I get is</p>
<pre><code>'utf8' codec can't decode byte 0x92 in position 31: unexpected code byte. You passed in 'Fabulous home on one of Decatur\x92s most
</code></pre>
<p>Any help is appreciated!</p>
| 2 | 2009-05-16T22:04:14Z | 873,438 | <p>The "Fabulous..." string doesn't look like utf-8: 0x92 is above 128 and as such should be a continuation of a multi-byte character. However, in that string it appears on its own (apparently representing an apostrophe).</p>
| 1 | 2009-05-16T22:17:27Z | [
"python",
"django",
"unicode"
] |
Converting to safe unicode in python | 873,419 | <p>I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error.</p>
<pre><code>Incorrect string value: '\xEF\xBF\xBDs m...'
</code></pre>
<p>My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion.</p>
<pre><code>s = unicode(content, "utf-8", errors="replace")
</code></pre>
<p>Without the above unicode conversion, the error I get is</p>
<pre><code>'utf8' codec can't decode byte 0x92 in position 31: unexpected code byte. You passed in 'Fabulous home on one of Decatur\x92s most
</code></pre>
<p>Any help is appreciated!</p>
| 2 | 2009-05-16T22:04:14Z | 873,450 | <p>0x92 is right single curly quote in windows cp1252 encoding.</p>
<p>\xEF\xBF\xBD is the UTF8 encoding of the unicode replacement character
(which was inserted instead of the erroneous cp1252 character).</p>
<p>So it looks like your database is not accepting the valid UTF8 data?</p>
<p>2 options:
1. Perhaps you should be using unicode(content,"cp1252")
2. If you want to insert UTF-8 into the DB, then you'll need to config it appropriately. I'll leave that answer to others more knowledgeable </p>
| 3 | 2009-05-16T22:25:18Z | [
"python",
"django",
"unicode"
] |
Converting to safe unicode in python | 873,419 | <p>I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error.</p>
<pre><code>Incorrect string value: '\xEF\xBF\xBDs m...'
</code></pre>
<p>My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion.</p>
<pre><code>s = unicode(content, "utf-8", errors="replace")
</code></pre>
<p>Without the above unicode conversion, the error I get is</p>
<pre><code>'utf8' codec can't decode byte 0x92 in position 31: unexpected code byte. You passed in 'Fabulous home on one of Decatur\x92s most
</code></pre>
<p>Any help is appreciated!</p>
| 2 | 2009-05-16T22:04:14Z | 873,475 | <p>What is the original encoding? I'm assuming "cp1252", from <a href="http://stackoverflow.com/questions/873419/converting-to-safe-unicode-in-python/873450#873450">pixelbeat's</a> answer. In that case, you can do</p>
<pre><code>>>> orig # Byte string, encoded in cp1252
'Fabulous home on one of Decatur\x92s most'
>>> uni = orig.decode('cp1252')
>>> uni # Unicode string
u'Fabulous home on one of Decatur\u2019s most'
>>> s = uni.encode('utf8')
>>> s # Correct byte string encoded in utf-8
'Fabulous home on one of Decatur\xe2\x80\x99s most'
</code></pre>
| 5 | 2009-05-16T22:43:42Z | [
"python",
"django",
"unicode"
] |
Timesheet Program to Track Days/Hours worked? | 873,564 | <p>Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)</p>
| 0 | 2009-05-16T23:45:59Z | 873,572 | <p>I would probably create a timesheet object for each week, or pay period. Each timesheet object might have a collection of days, with hours worked or times clocked in and out. </p>
<p>For persistent storage for a web site, I'd use a database like mysql. For an application running on a single machine I'd maybe use pickle, or a flat file system maybe.</p>
| 0 | 2009-05-16T23:50:10Z | [
"python"
] |
Timesheet Program to Track Days/Hours worked? | 873,564 | <p>Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)</p>
| 0 | 2009-05-16T23:45:59Z | 873,603 | <p>A dictionary is a good way to store the data while your program is running.</p>
<p>There are a number of ways to add some data permanence (so it's around after you close the program). The Python modules pickle and <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> are useful and easy to use. One issue with these is that you can't easily inspect the data outside of a Python program. There are also modules to read and write text files in the <a href="http://docs.python.org/library/json.html" rel="nofollow">JSON</a> and XML formats, and JSON is particularly easy to read in a text editor. If you aren't already proficient, the databases like MySQL are way more than you need for a personal program like you mention and unless you want to invest some time into learning how to use them, you should go with a simpler solution.</p>
<p>As for the Monday on week 1 vs week 2, you have many options. You could use the actual date (this seems like a good idea to me), or you could key the dictionary with tuples, like ("Monday", 1). The main rule is that dictionary keys must be immutable (ints, strings, tuples -- that contain only immutable objects, etc), but not (dictionaries, lists, etc).</p>
| 0 | 2009-05-17T00:12:15Z | [
"python"
] |
Timesheet Program to Track Days/Hours worked? | 873,564 | <p>Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)</p>
| 0 | 2009-05-16T23:45:59Z | 875,539 | <p>I took the opposite approach when designing this application for my own use.</p>
<p>In my experience, the biggest problem with timekeeping applications is data entry. So I decided to make my app use the simplest and most flexible data entry tool available: a text editor. I keep notes in a text file and intermingle timekeeping entries in them, so an excerpt looks like this:</p>
<pre><code>Monday 5/10/09
release script ok this week
open a case on the whole code-table-foreign-key thing
- CUS1 2.0 Generate and release version 1.0.45.
need to get dma to spec out the RESPRB configuration, see case 810
MH section complete - one to go!
- CUS2 4.0 Configure and test Mental Health section.
Tuesday 5/11/09
... and so on
</code></pre>
<p>I'm consistent in starting each day with the proper heading, and the format of actual timekeeping entries, as you can see, is pretty simple. A simple scanner and state machine is all it takes to extract the data - basically, I just look for lines that begin with a weekday or a hyphen, and ignore everything else.</p>
<p>So that the program doesn't get too slow when parsing the notes files, I create a new notes file every year. (Even at the end of December the parsing process doesn't take more than 1/16 of a second.)</p>
<p>I wouldn't do it this way if I had to process hundreds of peoples' timekeeping entries, because the user does have to have a bit of a clue, and the parsing time would begin to add up after a while. On the other hand, keeping this data in a human-readable text file that I can store other stuff in (and keep under version control, and diff, and so on) is just incredibly useful.</p>
| 0 | 2009-05-17T21:25:07Z | [
"python"
] |
How to install cogen python coroutine framework on Mac OS X | 873,577 | <p>I did </p>
<pre><code>sudo easy_install cogen
</code></pre>
<p>and got :</p>
<pre><code>Searching for cogen
Best match: cogen 0.2.1
Processing cogen-0.2.1-py2.5.egg
cogen 0.2.1 is already the active version in easy-install.pth
Using /Library/Python/2.5/site-packages/cogen-0.2.1-py2.5.egg
Processing dependencies for cogen
Searching for py-kqueue>=2.0
Reading http://pypi.python.org/simple/py-kqueue/
Best match: py-kqueue 2.0.1
Downloading http://pypi.python.org/packages/source/p/py-kqueue/py-kqueue-2.0.1.zip#md5=98d0c0d76c1ff827b3de33ac0073d2e7
Processing py-kqueue-2.0.1.zip
Running py-kqueue-2.0.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-M8cj_5/py-kqueue-2.0.1/egg-dist-tmp-lDR6ry
kqueuemodule.c: In function âkqueue_new_keventâ:
kqueuemodule.c:71: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_keventType_setattrâ:
kqueuemodule.c:217: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_new_keventâ:
kqueuemodule.c:71: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_keventType_setattrâ:
kqueuemodule.c:217: warning: assignment makes pointer from integer without a cast
No eggs found in /tmp/easy_install-M8cj_5/py-kqueue-2.0.1/egg-dist-tmp-lDR6ry (setup script problem?)
error: Could not find required distribution py-kqueue>=2.0
</code></pre>
<p>Would appreciate any pointers on how to get the dependencies installed on Mac OS X.</p>
| 0 | 2009-05-16T23:52:39Z | 873,592 | <p>It seems to be some problem with setuptools -- the dependencies are compiled succesfully but not installed. FWIW it works for me (OSX 10.5.6, MacPython 2.5). </p>
<p>I would try reinstalling setuptools, and if that fails downloading and "<code>python setup.py install</code>"ing cogen and py-kqueue manually. </p>
| 0 | 2009-05-17T00:02:48Z | [
"python"
] |
How to install cogen python coroutine framework on Mac OS X | 873,577 | <p>I did </p>
<pre><code>sudo easy_install cogen
</code></pre>
<p>and got :</p>
<pre><code>Searching for cogen
Best match: cogen 0.2.1
Processing cogen-0.2.1-py2.5.egg
cogen 0.2.1 is already the active version in easy-install.pth
Using /Library/Python/2.5/site-packages/cogen-0.2.1-py2.5.egg
Processing dependencies for cogen
Searching for py-kqueue>=2.0
Reading http://pypi.python.org/simple/py-kqueue/
Best match: py-kqueue 2.0.1
Downloading http://pypi.python.org/packages/source/p/py-kqueue/py-kqueue-2.0.1.zip#md5=98d0c0d76c1ff827b3de33ac0073d2e7
Processing py-kqueue-2.0.1.zip
Running py-kqueue-2.0.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-M8cj_5/py-kqueue-2.0.1/egg-dist-tmp-lDR6ry
kqueuemodule.c: In function âkqueue_new_keventâ:
kqueuemodule.c:71: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_keventType_setattrâ:
kqueuemodule.c:217: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_new_keventâ:
kqueuemodule.c:71: warning: assignment makes pointer from integer without a cast
kqueuemodule.c: In function âkqueue_keventType_setattrâ:
kqueuemodule.c:217: warning: assignment makes pointer from integer without a cast
No eggs found in /tmp/easy_install-M8cj_5/py-kqueue-2.0.1/egg-dist-tmp-lDR6ry (setup script problem?)
error: Could not find required distribution py-kqueue>=2.0
</code></pre>
<p>Would appreciate any pointers on how to get the dependencies installed on Mac OS X.</p>
| 0 | 2009-05-16T23:52:39Z | 873,644 | <p>Try downloading 'pip' (<a href="http://pypi.python.org/pypi/pip" rel="nofollow">http://pypi.python.org/pypi/pip</a>) and use that instead of easy_install. It just worked for me.</p>
| 0 | 2009-05-17T00:43:15Z | [
"python"
] |
GitPython and sending commands to the Git object | 873,740 | <p><a href="http://gitorious.org/git-python" rel="nofollow">GitPython</a> is a way of interacting with git from python. I'm trying to access the basic git commands (e.g. <code>git commit -m "message"</code>) from this module, which according to <a href="http://pysync.googlecode.com/files/GitPython.pdf" rel="nofollow">this</a> should be accessed through the Git module. Here's what I've tried so far to get these commands working:</p>
<pre><code>>>> import git
>>> foo = git.Git("~/git/GitPython")
>>> bar = "git commit -m 'message'"
>>> beef = git.Git.execute(foo,bar)
</code></pre>
<p>This shows up an error saying that there is no such file or directory. I've also tried the following as paths to my git directory:</p>
<p><code>~/git/GitPython/.git</code><br />
<code>/Users/bacon/git/gitclient/</code></p>
<p>The only other option is that the command is wrong, so I tried:
<code>commit -m "message"</code> as well, and still get "no such file or directory".</p>
<p>What do I need to do to get these git commands working properly?</p>
| 3 | 2009-05-17T02:04:40Z | 873,873 | <p>In the tutorial it says ...</p>
<pre><code>The first step is to create a ``Repo`` object to represent your repository.
>>> from git import *
>>> repo = Repo("/Users/mtrier/Development/git-python")
</code></pre>
<p>I don't see your Repo.</p>
<p>I am looking at the file named tutorial.rst in the doc directory of GitPython.</p>
| 0 | 2009-05-17T04:02:00Z | [
"python",
"git"
] |
GitPython and sending commands to the Git object | 873,740 | <p><a href="http://gitorious.org/git-python" rel="nofollow">GitPython</a> is a way of interacting with git from python. I'm trying to access the basic git commands (e.g. <code>git commit -m "message"</code>) from this module, which according to <a href="http://pysync.googlecode.com/files/GitPython.pdf" rel="nofollow">this</a> should be accessed through the Git module. Here's what I've tried so far to get these commands working:</p>
<pre><code>>>> import git
>>> foo = git.Git("~/git/GitPython")
>>> bar = "git commit -m 'message'"
>>> beef = git.Git.execute(foo,bar)
</code></pre>
<p>This shows up an error saying that there is no such file or directory. I've also tried the following as paths to my git directory:</p>
<p><code>~/git/GitPython/.git</code><br />
<code>/Users/bacon/git/gitclient/</code></p>
<p>The only other option is that the command is wrong, so I tried:
<code>commit -m "message"</code> as well, and still get "no such file or directory".</p>
<p>What do I need to do to get these git commands working properly?</p>
| 3 | 2009-05-17T02:04:40Z | 873,896 | <p>I havn't tried it to verify yet but it seems git.Git.execute expects a list of commandline arguments (if you give it a string it'll look for an executable exactly matching the string, spaces and everything - which naturally wouldn't be found), so something like this I think would work:</p>
<pre><code>import git
import os, os.path
g = git.Git(os.path.expanduser("~/git/GitPython"))
result = g.execute(["git", "commit", "-m", "'message'"])
</code></pre>
<p>other changes:</p>
<ul>
<li>I expect using a path with ~ in it wouldn't work so I used os.path.expanduser to expand ~ to your home directory</li>
<li>using instance.method(*args) instead of Class.method(instance, *args) is generally preferred so I changed that, though it'd still work with the other way</li>
</ul>
<p>There might be saner ways than manually running the commit command though (I just didn't notice any quickly looking through the source) so I suggest making sure there isn't a higher-level way before doing it that way</p>
| 9 | 2009-05-17T04:27:46Z | [
"python",
"git"
] |
GitPython and sending commands to the Git object | 873,740 | <p><a href="http://gitorious.org/git-python" rel="nofollow">GitPython</a> is a way of interacting with git from python. I'm trying to access the basic git commands (e.g. <code>git commit -m "message"</code>) from this module, which according to <a href="http://pysync.googlecode.com/files/GitPython.pdf" rel="nofollow">this</a> should be accessed through the Git module. Here's what I've tried so far to get these commands working:</p>
<pre><code>>>> import git
>>> foo = git.Git("~/git/GitPython")
>>> bar = "git commit -m 'message'"
>>> beef = git.Git.execute(foo,bar)
</code></pre>
<p>This shows up an error saying that there is no such file or directory. I've also tried the following as paths to my git directory:</p>
<p><code>~/git/GitPython/.git</code><br />
<code>/Users/bacon/git/gitclient/</code></p>
<p>The only other option is that the command is wrong, so I tried:
<code>commit -m "message"</code> as well, and still get "no such file or directory".</p>
<p>What do I need to do to get these git commands working properly?</p>
| 3 | 2009-05-17T02:04:40Z | 874,104 | <p>In general, ~ expansion is done by your shell and is not a feature of the file system, so you shouldn't expect it to work.</p>
<p>os.path.expanduser can apply the expansion for you, but in general you're better off writing out the full path (since then the script works whoever runs it, providing they have access to your files).</p>
<p>I suspect you want:</p>
<pre><code>'/Users/bacon/git/GitPython'
</code></pre>
| 0 | 2009-05-17T07:43:54Z | [
"python",
"git"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,797 | <p>What you want is String.Join, but since just saying that probably won't help you, here are some <a href="http://snippets.dzone.com/posts/show/91" rel="nofollow">Join implementations in Java</a>. Here's a <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html" rel="nofollow">string utility</a> that has a join for Java.</p>
| 1 | 2009-05-17T02:44:51Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,800 | <p>Well, in Python it will be straightforward using <strong>join</strong>:</p>
<pre><code>values = ["this", "is", "your", "array"]
result = " ".join(values)
</code></pre>
| 13 | 2009-05-17T02:47:08Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,805 | <p>Let's not forget the good old-fashioned</p>
<pre><code> for s in strArray do
print s
print " "
</code></pre>
| -3 | 2009-05-17T02:50:10Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,807 | <p>Well, I know Python has a function like this, and I'm assuming Ruby does, and Java.</p>
<p>The join function takes an array of strings (depending on the language, it can be other types) and joins them together with a character (or another string) that you choose.</p>
<p>Python code:</p>
<pre><code>wordString = " ".join(["word", "another", "word"])
</code></pre>
<p>Otherwise, you can loop through, the array, adding the word and a space, and test if it is the last element. If it is, just add the word, and not the space.</p>
<p>Python code again: (thanks to PTBNL for the suggestion)</p>
<pre><code>wordArray = ["word", "another", "word"]
wordString = ""
for i in range(0, len(wordArray) - 1):
wordString += wordArray[i] + " "
wordString += wordArray[len(wordArray) - 1]
</code></pre>
| 0 | 2009-05-17T02:50:48Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,835 | <p>Yes, this is what <code>join</code> was made for. Here is the Ruby version:</p>
<pre><code>["word", "another", "word"].join(" ")
</code></pre>
<p><code><flamebait></code> As you can see, Ruby makes <code>join</code> a method on <code>Array</code> instead of <code>String</code>, and is thus far more sensible. <code></flamebait></code></p>
| 7 | 2009-05-17T03:19:03Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,865 | <p>Straight from one of my existing utilz classes </p>
<p><strong>C:\java\home\src\krc\utilz\Arrayz.java</strong></p>
<pre><code>package krc.utilz;
/**
* A bunch of static helper methods for arrays of String's.
* @See also krc.utilz.IntArrays for arrays of int's.
*/
public abstract class Arrayz
{
/**
* Concetenates the values in the given array into a string, seperated by FS.
* @param FS String - Field Seperator - Name borrowed from awk
* @param Object[] a - array to be concatentated
* @return a string representation of the given array.
*/
public static String join(String FS, Object[] a) {
if (a==null||a.length==0) return "";
StringBuilder result = new StringBuilder(String.valueOf(a[0]));
for(int i=1; i<a.length; i++) {
result.append(FS);
result.append(String.valueOf(a[i]));
}
return result.toString();
}
....
}
</code></pre>
<p>Cheers. Keith.</p>
<p><hr /></p>
<p><strong>EDIT</strong></p>
<p>Here's a quick & dirty performance comparison, using java.util.Arrays as a baseline.</p>
<p>Note that hotspot cost is amortized over 100 iterations, and should be (more or less) the same for all three techniques... krc.utilz.RandomString and krc.utilz.Arrayz are both available upon request, just ask.</p>
<pre><code>package forums;
import java.util.Arrays;
import krc.utilz.Arrayz;
import krc.utilz.RandomString;
class ArrayToStringPerformanceTest
{
private static final int NS2MS = 1000000; // 1 millisecond (1/10^3) = 1,000,000 nanoseconds (1/10^9)
public static void main(String[] args) {
try {
String[] array = randomStrings(100*1000, 16);
long start, stop;
String result;
final int TIMES = 100;
long time1=0L, time2=0L, time3=0L;
for (int i=0; i<TIMES; i++) {
start = System.nanoTime();
result = Arrays.toString(array);
stop = System.nanoTime();
//System.out.println("Arrays.toString took "+(stop-start)+" ns");
time1 += (stop-start);
start = System.nanoTime();
result = Arrayz.join(", ", array);
stop = System.nanoTime();
//System.out.println("Arrayz.join took "+(stop-start)+" ns");
time2 += (stop-start);
start = System.nanoTime();
result = arrayToString(array, ", ");
stop = System.nanoTime();
//System.out.println("arrayToString took "+(stop-start)+" ns");
time3 += (stop-start);
}
System.out.format("java.util.Arrays.toString took "+(time1/TIMES/NS2MS)+" ms");
System.out.format("krc.utilz.Arrayz.join took "+(time2/TIMES/NS2MS)+" ms");
System.out.format("arrayToString took "+(time3/TIMES/NS2MS)+" ms");
} catch (Exception e) {
e.printStackTrace();
}
}
public static String arrayToString(String[] array, String spacer) {
StringBuffer result = new StringBuffer();
for ( int i=0; i<array.length; i++ ) {
result.append( array[i] + ((i+1<array.length)?spacer:"") );
}
return result.toString();
}
private static String[] randomStrings(int howMany, int length) {
RandomString random = new RandomString();
String[] a = new String[howMany];
for ( int i=0; i<howMany; i++) {
a[i] = random.nextString(length);
}
return a;
}
}
/*
C:\Java\home\src\forums>"C:\Program Files\Java\jdk1.6.0_12\bin\java.exe" -Xms512m -Xmx1536m -enableassertions -cp C:\Java\home\classes forums.ArrayToStringPerformanceTest
java.util.Arrays.toString took 26 ms
krc.utilz.Arrayz.join took 32 ms
arrayToString took 59 ms
*/
</code></pre>
<p>See also Doomspork's suggestion, and my comment thereon.</p>
<p>Cheers. Keith.</p>
| 1 | 2009-05-17T03:50:02Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 873,869 | <p>Java could be accomplished with something like this:</p>
<pre><code>public static String arrayToString(String[] array, String spacer) {
StringBuffer result = new StringBuffer();
for(int i = 0 ; i < array.length ; i++) {
result.append(array[i] + ((i + 1 < array.length) ? spacer : ""));
}
return result.toString();
}
</code></pre>
| 1 | 2009-05-17T03:59:10Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 874,126 | <p>In Python, you ask the <em>join string</em> to <a href="http://www.python.org/doc/current/library/stdtypes.html#str.join" rel="nofollow">join</a> an iterable of strings:</p>
<pre><code>alist= ["array", "of", "strings"]
output= " ".join(alist)
</code></pre>
<p>If this notation seems weird to you, you can do the same thing in a different syntax:</p>
<pre><code>output= str.join(" ", alist)
</code></pre>
<p>This works for any iterable (lists, tuples, dictionaries, generators, generator expressionsâ¦), as long as the items are all strings (or unicode strings).</p>
<p>You can substitute <code>unicode</code> for <code>str</code> (or <code>u' '</code> for <code>' '</code>) if you want a unicode result.</p>
| 0 | 2009-05-17T08:15:10Z | [
"java",
"python",
"ruby",
"string"
] |
Print space after each word | 873,790 | <p>what is an easy/effective way to combine an array of words together with a space in between, but no space before or after?</p>
<p>I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though.</p>
<p>Preferably code in Java, Python, or Ruby.</p>
| 2 | 2009-05-17T02:37:28Z | 874,170 | <p>This will work in Ruby as well:</p>
<pre><code>['a', 'list', 'of', 'words'] * " "
</code></pre>
| 1 | 2009-05-17T08:44:30Z | [
"java",
"python",
"ruby",
"string"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 873,886 | <p>If you want to replicate Twitter, check out <a href="http://laconi.ca/trac/" rel="nofollow">Laconica</a></p>
| 0 | 2009-05-17T04:12:27Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 873,894 | <p>I've got experience developing in LAMP, Java, and Django so I'll weigh in.</p>
<p>First and foremost, it's really dependent on the individuals abilities. If you're a Java programmer you're going have to learn Python to try and use Django so you'll have a big initial time investment just to get up to speed.</p>
<p>Skill levels aside, I'd put money on either Django/Python or CakePHP/PHP. Django has a production ready admin panel which is easily configured, but CakePHP is a clean MVC implementation in PHP and PHP is pretty dang easy.</p>
<p>Not sure if you've considered hosting but that might be worth considering. You're going to find it's much easier to get cheap PHP hosting than you might for something like Django or Java.</p>
| 2 | 2009-05-17T04:23:37Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 873,939 | <p>there is groovy and grails: "How to build Twitter in 40mins using Grails" <a href="http://europe.springone.com/europe-2009/presentation/How+to+bui" rel="nofollow">http://europe.springone.com/europe-2009/presentation/How+to+bui</a></p>
| 0 | 2009-05-17T05:06:51Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 873,961 | <p>Getting RoR running on Heroku is ridiculously easy, and they have a 100% free offering, so that's a good way to get started. Interacting with Twitter from Rails is also pretty simple, especially with things like <a href="http://www.intridea.com/2009/3/23/twitter-auth-for-near-instant-twitter-apps" rel="nofollow">TwitterAuth</a>.</p>
| 3 | 2009-05-17T05:28:00Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 2,046,945 | <p>For Java devs, Twitter4j is an excellent twitter library. Couple that with Google App engine and you can be up and running with a sample twitter app in a few hours!</p>
| 1 | 2010-01-12T05:47:32Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Rapid Prototyping Twitter Applications? | 873,868 | <p>I'm looking forward to create a bunch of Twitter applications for a website, and was wondering what solution stack worked best when trying to rapidly prototype small twitter applications? </p>
<p>Google App Engine + Python/Django?
Google App Engine + Java?
Heroku + RoR?
Good Old LAMP? </p>
<p>Also, any recommendations on particular frameworks/libraries you use that makes the process faster? </p>
<p>[Note: I'm looking to use Twitter API for it, and create applications based on Twitter itself]</p>
<p>Thanks. </p>
| 0 | 2009-05-17T03:58:28Z | 4,623,925 | <p>I use Java (via the Jetty web server) and <a href="http://www.winterwell.com/software/jtwitter.php" rel="nofollow">JTwitter</a>. It's easy to use, and easy to debug.</p>
| 2 | 2011-01-07T08:59:55Z | [
"java",
"php",
"python",
"ruby",
"twitter"
] |
Google App Engine: Production versus Development Settings | 873,949 | <p>How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?</p>
<p>For example, I would like to set up a settings file where I store the Absolute Root URL.</p>
| 8 | 2009-05-17T05:16:37Z | 874,478 | <p>It's not clear from your question if you're asking about the Java or Python runtime. I'll assume Python for now.</p>
<p>Just like any other Python webapp, the settings file can be wherever and whatever you want. I usually use a .py file called 'settings.py' or 'config.py' in the root directory of my app. For example, see <a href="http://github.com/Arachnid/bloog/blob/241fc977d310a77833eb9c61362aaa3ff4e10fe6/config.py">Bloog's settings file</a>.</p>
<p>As far as having different settings for production and development goes, you have two options: </p>
<ol>
<li>Simply keep two branches in your source code repository, one for dev and one for prod, and periodically merge from dev to prod when you want to do a release. In this case, you just don't merge config.py.</li>
<li><p>Autodetect which platform you're running on, and apply settings as appropriate. The easiest way to do this is to check the value of os.environ['SERVER_SOFTWARE'], which will start with 'Dev' if it's the development server. You can use this to set a flag like so:</p>
<p>DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')</p></li>
</ol>
| 15 | 2009-05-17T12:11:06Z | [
"python",
"google-app-engine"
] |
Google App Engine: Production versus Development Settings | 873,949 | <p>How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?</p>
<p>For example, I would like to set up a settings file where I store the Absolute Root URL.</p>
| 8 | 2009-05-17T05:16:37Z | 3,450,555 | <p>You can <a href="http://stackoverflow.com/questions/1015442/how-to-get-the-current-server-url-of-appengine-app">find out the root URL from the request</a>, and use that instead of configuring it manually. Or if you need further configuration, then use that to decide which config to use.</p>
| 1 | 2010-08-10T15:22:31Z | [
"python",
"google-app-engine"
] |
Python Django: Handling URL with Google App Engine - Post then Get | 873,966 | <p>I have something like this set up:</p>
<pre><code>class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
</code></pre>
<p>The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?</p>
| 0 | 2009-05-17T05:32:11Z | 873,980 | <pre><code>create_object(request, form_class=FormClass,
post_save_redirect=reverse('-get-url-handler-',
kwargs=dict(key='%(key)s')))
</code></pre>
<p>I use the above django shortcut from generic views where you can specify post save redirect , get in your case .
There are few more examples in this snippet .
Btw, I assumed that you are using django ( helper or patch) with app engine , based on the title of the question.
If you are using app engine patch , check out the views.py in "myapp" app sample add_person handler does what you are looking for.</p>
| 0 | 2009-05-17T05:48:58Z | [
"python",
"google-app-engine"
] |
Python Django: Handling URL with Google App Engine - Post then Get | 873,966 | <p>I have something like this set up:</p>
<pre><code>class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
</code></pre>
<p>The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?</p>
| 0 | 2009-05-17T05:32:11Z | 873,985 | <p>That's generally not a good idea as it'll cause confusion. You should really do whatever it is you want to do and then redirect them to the get method.</p>
| 0 | 2009-05-17T05:56:44Z | [
"python",
"google-app-engine"
] |
Python Django: Handling URL with Google App Engine - Post then Get | 873,966 | <p>I have something like this set up:</p>
<pre><code>class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
</code></pre>
<p>The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?</p>
| 0 | 2009-05-17T05:32:11Z | 874,225 | <p>Actually, your code isn't Django, but webapp (Google's mini-"framework"). Please read the Django documentation: <a href="http://docs.djangoproject.com/" rel="nofollow">http://docs.djangoproject.com/</a></p>
<p>Django's generic views are only available with app-engine-patch. The helper doesn't support them. You could take a look at the app-engine-patch sample project to learn more about Django on App Engine: <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">http://code.google.com/p/app-engine-patch/</a></p>
| 0 | 2009-05-17T09:20:02Z | [
"python",
"google-app-engine"
] |
Python Django: Handling URL with Google App Engine - Post then Get | 873,966 | <p>I have something like this set up:</p>
<pre><code>class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
</code></pre>
<p>The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?</p>
| 0 | 2009-05-17T05:32:11Z | 874,236 | <p>Call self.redirect(url) to redirect the user back to the same page over GET. That way, they won't accidentally re-submit the form if they hit refresh.</p>
| 1 | 2009-05-17T09:28:36Z | [
"python",
"google-app-engine"
] |
Python Django: Handling URL with Google App Engine - Post then Get | 873,966 | <p>I have something like this set up:</p>
<pre><code>class CategoryPage (webapp.RequestHandler):
def get(self):
** DO SOMETHING HERE **
def post(self):
** DO SOMETHING HERE **
** RENDER THE SAME AS get(self)
</code></pre>
<p>The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?</p>
| 0 | 2009-05-17T05:32:11Z | 880,066 | <p>A redirect, as others suggest, does have some advantage, but it's something of a "heavy" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method <code>def _Render(self):</code> and just ending both the <code>get</code> and <code>post</code> methods with a call to <code>self.Render()</code>.</p>
| 3 | 2009-05-18T22:07:59Z | [
"python",
"google-app-engine"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,022 | <pre><code>my_set = set(map(str.strip, open('filename.txt')))
</code></pre>
| 3 | 2009-05-17T06:36:03Z | [
"python",
"text-files"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,025 | <p>The strip() method of strings removes whitespace from both ends.</p>
<pre><code>set(line.strip() for line in open('filename.txt'))
</code></pre>
| 33 | 2009-05-17T06:38:20Z | [
"python",
"text-files"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,028 | <p>To remove only the right hand spaces.</p>
<pre><code>set(map(str.rstrip, open('filename.txt')))
</code></pre>
| 1 | 2009-05-17T06:40:33Z | [
"python",
"text-files"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,030 | <p>Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs</p>
<pre><code>words = set(open('filename.txt').read().split())
</code></pre>
| 9 | 2009-05-17T06:41:17Z | [
"python",
"text-files"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,190 | <pre><code>with open("filename.txt") as f:
mySet = map(str.rstrip, f)
</code></pre>
<p>If you want to use this in Python 2.5, you need</p>
<pre><code>from __future__ import with_statement
</code></pre>
| 0 | 2009-05-17T09:02:27Z | [
"python",
"text-files"
] |
Python: load words from file into a set | 874,017 | <p>I have a simple text file with several thousands of words, each in its own line, e.g.</p>
<pre><code>aardvark
hello
piper
</code></pre>
<p>I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):</p>
<pre><code>my_set = set(open('filename.txt'))
</code></pre>
<p>The above code produces a set with the following entries (each word is followed by a space and new-line character:</p>
<pre><code>("aardvark \n", "hello \n", "piper \n")
</code></pre>
<p>What's the simplest way to load the file into a set but get rid of the space and \n?</p>
<p>Thanks</p>
| 17 | 2009-05-17T06:33:54Z | 874,402 | <pre><code>with open("filename.txt") as f:
s = set([line.rstrip('\n') for line in f])
</code></pre>
| 1 | 2009-05-17T11:27:16Z | [
"python",
"text-files"
] |
Python list of objects with random attributes | 874,121 | <p>(Edit: randrange is just random.randrange, I didn't write my own RNG)</p>
<p>I'm trying to create a list of instances of a class I defined. Here's the entire class (by request):</p>
<pre><code>from random import randrange
class Poly:
points = [0] * 8
fill = 'red'
alpha = 1.0
def __init__(self, width=100, height=100):
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
self.alpha = random()
return
</code></pre>
<p>Seems to work fine:</p>
<pre><code>>>> for i in range(5):
Poly().points
[28, 64, 93, 26, 15, 31, 44, 50]
[24, 14, 47, 14, 35, 17, 63, 62]
[99, 28, 90, 29, 56, 59, 57, 33]
[62, 56, 48, 28, 40, 73, 70, 99]
[99, 32, 27, 99, 42, 57, 86, 12]
</code></pre>
<p>But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values:</p>
<pre><code>>>> p = []
>>> for i in range(5):
p.append(Poly())
>>> p
[<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>]
>>> for poly in p:
print poly.points
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
</code></pre>
<p>What's going on here? And what's the right way to do what I'm trying to do?</p>
| 1 | 2009-05-17T08:06:07Z | 874,131 | <p>Move the creation of the array into the <code>__init__</code> method.</p>
<p>You're working with a shared array among all objects.</p>
<p>The reason the first shows different is that you print the contents of that array before you construct a new Poly object and thus trample over the array contents. If you had kept them around and inspected them later they would all appear to have the same contents as the last one you generated.</p>
<p>Oh, and try not to simplify code when posting questions. Always post complete, but short, programs that reproduce the problem.</p>
<p>Here's a short, but complete, program that demonstrates the problem you're having:</p>
<pre><code>from random import randrange
class Poly:
points = [0]*8
def __init__(self, width=100, height=100):
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
return
p1 = Poly()
print "p1:", p1.points
p2 = Poly()
print "p2:", p2.points
print "p1:", p1.points
</code></pre>
<p>Sample output:</p>
<pre><code>[C:\Temp] test.py
p1: [19, 5, 1, 46, 93, 18, 18, 57]
p2: [92, 71, 42, 84, 54, 29, 27, 71]
p1: [92, 71, 42, 84, 54, 29, 27, 71]
</code></pre>
<p>Notice how p1 changed.</p>
<p>The fixed code could be as simple as:</p>
<pre><code>from random import randrange
class Poly:
def __init__(self, width=100, height=100):
self.points = [0]*8
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
return
</code></pre>
<p>although I prefer the append variant that <a href="http://stackoverflow.com/users/51305/doug">@Doug</a> posted <a href="http://stackoverflow.com/questions/874121/python-list-of-objects-with-random-attributes/874140#874140">here</a></p>
| 6 | 2009-05-17T08:17:17Z | [
"python",
"random"
] |
Python list of objects with random attributes | 874,121 | <p>(Edit: randrange is just random.randrange, I didn't write my own RNG)</p>
<p>I'm trying to create a list of instances of a class I defined. Here's the entire class (by request):</p>
<pre><code>from random import randrange
class Poly:
points = [0] * 8
fill = 'red'
alpha = 1.0
def __init__(self, width=100, height=100):
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
self.alpha = random()
return
</code></pre>
<p>Seems to work fine:</p>
<pre><code>>>> for i in range(5):
Poly().points
[28, 64, 93, 26, 15, 31, 44, 50]
[24, 14, 47, 14, 35, 17, 63, 62]
[99, 28, 90, 29, 56, 59, 57, 33]
[62, 56, 48, 28, 40, 73, 70, 99]
[99, 32, 27, 99, 42, 57, 86, 12]
</code></pre>
<p>But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values:</p>
<pre><code>>>> p = []
>>> for i in range(5):
p.append(Poly())
>>> p
[<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>]
>>> for poly in p:
print poly.points
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
</code></pre>
<p>What's going on here? And what's the right way to do what I'm trying to do?</p>
| 1 | 2009-05-17T08:06:07Z | 874,140 | <p>The points lists are all being shared. It would appear that you're declaring points to be a list on the instance or class. This isn't the way of doing things in Python if you don't want to share the list between instances. Try:</p>
<pre><code>
def __init__(self, width=100, height=100):
self.points = [] #Create a new list
for i in range(0, 8, 2):
self.points.append(randrange(width))
self.points.append(randrange(height))
return
</code></pre>
| 2 | 2009-05-17T08:24:34Z | [
"python",
"random"
] |
Python list of objects with random attributes | 874,121 | <p>(Edit: randrange is just random.randrange, I didn't write my own RNG)</p>
<p>I'm trying to create a list of instances of a class I defined. Here's the entire class (by request):</p>
<pre><code>from random import randrange
class Poly:
points = [0] * 8
fill = 'red'
alpha = 1.0
def __init__(self, width=100, height=100):
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
self.alpha = random()
return
</code></pre>
<p>Seems to work fine:</p>
<pre><code>>>> for i in range(5):
Poly().points
[28, 64, 93, 26, 15, 31, 44, 50]
[24, 14, 47, 14, 35, 17, 63, 62]
[99, 28, 90, 29, 56, 59, 57, 33]
[62, 56, 48, 28, 40, 73, 70, 99]
[99, 32, 27, 99, 42, 57, 86, 12]
</code></pre>
<p>But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values:</p>
<pre><code>>>> p = []
>>> for i in range(5):
p.append(Poly())
>>> p
[<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>]
>>> for poly in p:
print poly.points
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
</code></pre>
<p>What's going on here? And what's the right way to do what I'm trying to do?</p>
| 1 | 2009-05-17T08:06:07Z | 874,141 | <p>ok here is the culprit</p>
<p>points = [[0]] * 8</p>
<p>it assigns same list ([0]) 8 times instead you should do something like</p>
<pre><code>points = []
for i in range(8):
points.append([])
</code></pre>
| -1 | 2009-05-17T08:24:41Z | [
"python",
"random"
] |
Python list of objects with random attributes | 874,121 | <p>(Edit: randrange is just random.randrange, I didn't write my own RNG)</p>
<p>I'm trying to create a list of instances of a class I defined. Here's the entire class (by request):</p>
<pre><code>from random import randrange
class Poly:
points = [0] * 8
fill = 'red'
alpha = 1.0
def __init__(self, width=100, height=100):
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
self.alpha = random()
return
</code></pre>
<p>Seems to work fine:</p>
<pre><code>>>> for i in range(5):
Poly().points
[28, 64, 93, 26, 15, 31, 44, 50]
[24, 14, 47, 14, 35, 17, 63, 62]
[99, 28, 90, 29, 56, 59, 57, 33]
[62, 56, 48, 28, 40, 73, 70, 99]
[99, 32, 27, 99, 42, 57, 86, 12]
</code></pre>
<p>But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values:</p>
<pre><code>>>> p = []
>>> for i in range(5):
p.append(Poly())
>>> p
[<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>]
>>> for poly in p:
print poly.points
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
[75, 18, 5, 76, 6, 64, 95, 54]
</code></pre>
<p>What's going on here? And what's the right way to do what I'm trying to do?</p>
| 1 | 2009-05-17T08:06:07Z | 874,148 | <p>You have a class attribute <code>Poly.points</code>. In your <code>__init__</code> method you do <code>self.points[i] = ...</code>. Now this makes Python use <code>Poly.points</code> which is shared by all instances. But you want <code>points</code> to be an instance attribute. I'd suggest this:</p>
<pre><code>class Poly:
# you don't need this here
#points = [0] * 8
#fill = 'red'
#alpha = 1.0
def __init__(self, width=100, height=100):
self.points = [0]*8
self.fill = 'red'
self.alpha = random()
for i in range(0, 8, 2):
self.points[i] = randrange(width)
self.points[i+1] = randrange(height)
</code></pre>
| 4 | 2009-05-17T08:27:17Z | [
"python",
"random"
] |
List of non-datastore types in AppEngine? | 874,122 | <p>I'm building an AppEngine model class. I need a simple list of tuples:</p>
<pre><code>class MyTuple(object):
field1 = "string"
field2 = 3
class MyModel(db.Model):
the_list = db.ListProperty(MyTuple)
</code></pre>
<p>This does not work, since AppEngine does not accept MyTuple as a valid field.</p>
<p>Solutions I can think of:</p>
<ol>
<li><p>Make MyTuple extend db.Model. But doesn't that mean every entry in the list will be stored in a dedicated MyTuple table?</p></li>
<li><p>Make it a list of strings, which are a "serialized" form of MyTuple; add parsing (unserializing) code. Yuck.</p></li>
<li><p>Maintain two lists (one of strings, one of ints). Another yuck.</p></li>
</ol>
<p>Any other solution that I'm missing?</p>
| 2 | 2009-05-17T08:11:05Z | 874,230 | <p>In app-engine-patch there's a FakeModelListProperty and FakeModel (import both from ragendja.dbutils). Derive MyTuple from FakeModel and set fields = ('field1', 'field2'). Those fields will automatically get converted to JSON when stored in the list, so you could manually edit them in a textarea. Of course, this only works for primitive types (strings, integers, etc.). Take a look at the source if this doesn't suffice.</p>
<p><a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">http://code.google.com/p/app-engine-patch/</a></p>
| 1 | 2009-05-17T09:26:42Z | [
"python",
"google-app-engine",
"orm"
] |
Python ctypes and function pointers | 874,245 | <p>This is related to <a href="http://stackoverflow.com/questions/867850/creating-a-wrapper-for-a-c-library-in-python">my other question</a>, but I felt like I should ask it in a new question.</p>
<p>Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use <code>CFUNCTYPE</code> to prototype them, and then you use the <code>prototype()</code> function to create them. </p>
<p>The problem I have with this is that I figured that I would create my callback function as such (I am not showing the structures that I have recreated, FLAC__Frame is a Structure):</p>
<pre><code>write_callback_prototype = CFUNCTYPE(c_int, c_void_p,
POINTER(FLAC__Frame),
POINTER(c_int32), v_void_p)</code></pre>
<p>The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated.</p>
| 1 | 2009-05-17T09:33:03Z | 874,320 | <p>According to the <a href="http://docs.python.org/library/ctypes.html#callback-functions" rel="nofollow">ctypes callback docs</a> you can define python function</p>
<pre><code>def my_callback(a, p, frame, p1, p2)
pass
</code></pre>
<p>and then create a pointer to a C callable function like this:</p>
<pre><code>callback = write_callback_prototype(my_callback)
</code></pre>
<p>This function pointer can then be passed into FLAC</p>
| 4 | 2009-05-17T10:27:01Z | [
"python",
"function-pointers",
"ctypes"
] |
Python ctypes and function pointers | 874,245 | <p>This is related to <a href="http://stackoverflow.com/questions/867850/creating-a-wrapper-for-a-c-library-in-python">my other question</a>, but I felt like I should ask it in a new question.</p>
<p>Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use <code>CFUNCTYPE</code> to prototype them, and then you use the <code>prototype()</code> function to create them. </p>
<p>The problem I have with this is that I figured that I would create my callback function as such (I am not showing the structures that I have recreated, FLAC__Frame is a Structure):</p>
<pre><code>write_callback_prototype = CFUNCTYPE(c_int, c_void_p,
POINTER(FLAC__Frame),
POINTER(c_int32), v_void_p)</code></pre>
<p>The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated.</p>
| 1 | 2009-05-17T09:33:03Z | 874,384 | <blockquote>
<p>The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated.</p>
</blockquote>
<p>In that case, just use:</p>
<pre><code>import ctypes
class FLAC__Frame(ctypes.Structure):
pass
</code></pre>
<p>and pretend that it is already defined, and do not care because you only need pointer to it, which is basically position in memory.</p>
| 1 | 2009-05-17T11:16:13Z | [
"python",
"function-pointers",
"ctypes"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 874,488 | <p>Silly me. Forgot to import io...</p>
<pre><code>import scipy.io
mat = scipy.io.loadmat('file.mat')
</code></pre>
| 243 | 2009-05-17T12:16:13Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 19,340,117 | <p>scipy.io.savemat or scipy.io.loadmat does NOT work for matlab arrays --v7.3. But the good part is that matlab --v7.3 files are hdf5 datasets. So they can be read using a number of tools, including numpy.</p>
<p>For python, you will need the h5py extension, which requires HDF5 on your system.</p>
<pre><code>import numpy as np, h5py
f = h5py.File('somefile.mat','r')
data = f.get('data/variable1')
data = np.array(data) # For converting to numpy array
</code></pre>
| 61 | 2013-10-12T23:06:48Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 26,295,900 | <p>There is also the <a href="http://www.mathworks.de/de/help/matlab/matlab-engine-for-python.html" rel="nofollow">MATLAB Engine for Python</a> by MathWorks itself. If you have Matlab, this might be worth considered (I haven't tried it myself but it has a lot more functionality than just reading Matlab files). However, I don't know if it is allowed to distribute it to other users (probably no problem if those persons have Matlab, otherwise maybe NumPy is the right way to go?).</p>
<p>Also, if you want to do all the basics yourself, MathWorks <a href="http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf" rel="nofollow">provides</a> (if the link changes, try to google for <code>matfile_format.pdf</code> or its title <code>MAT-FILE Format</code>) a detailed documentation on the structure of the file format. It's not as complicated as I personally thought but obviously, this is not the easiest way to go. It also depends on, how many features of the <code>.mat</code>-files you want to support.</p>
<p>I've written a "small" (about 700 lines) Python script which can read some basic <code>.mat</code>-files. I'm neither a Python expert nor a beginner and it took me about two days to write it (using the MathWorks documentation linked above). I've learned a lot of new stuff and it was quite fun (most of the time). As I've written the Python script at work, I'm afraid I cannot publish it... But I can give a few advices here:</p>
<ul>
<li>First read the documentation</li>
<li>Use a HEX-Editor (such as <a href="http://mh-nexus.de/en/hxd/" rel="nofollow">HxD</a>) and look into a reference <code>.mat</code>-file you want to parse</li>
<li>Try to figure out the meaning of each Byte by saving the Bytes to a txt-file and annotate each line</li>
<li>Use classes to save each data element (such as <code>miCOMPRESSED</code>, <code>miMATRIX</code>, <code>mxDOUBLE</code> or <code>miINT32</code>)</li>
<li>The <code>.mat</code>-files' structure is optimal for saving the data elements in a tree data structure; each node has one class and subnodes</li>
</ul>
| 2 | 2014-10-10T09:16:28Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 28,909,094 | <p>Having Matlab 2014b or newer installed, the <a href="http://www.mathworks.com/help/matlab/matlab-engine-for-python.html">Matlab engine for Python</a> could be used:</p>
<pre><code>import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat",nargout=1)
</code></pre>
| 5 | 2015-03-06T22:58:25Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 29,686,152 | <p>hdf5 files can also be dealt with by means of PyTables. Their FAQ has an entry which compares with h5py: <a href="https://pytables.github.io/FAQ.html" rel="nofollow">https://pytables.github.io/FAQ.html</a> . PyTables also comes with the handy visualiser ViTables: <a href="http://vitables.org/galleries/Screenshots/" rel="nofollow">http://vitables.org/galleries/Screenshots/</a></p>
| 2 | 2015-04-16T21:17:15Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Read .mat files in Python | 874,461 | <p>Does anyone have successful experience reading binary Matlab .mat files in Python?</p>
<p>(I've seen that <code>scipy</code> has alleged support for reading .mat files, but I'm unsuccessful with it. I installed <code>scipy</code> version 0.7.0, and I can't find the <code>loadmat()</code> method)</p>
| 170 | 2009-05-17T12:02:04Z | 30,868,935 | <p>I've screwed half an hour even after reading the answers. Hope this answer helps</p>
<p>First save the mat file as</p>
<pre><code>save('test.mat','-v7')
</code></pre>
<p>After that in Python use the usual loadmat</p>
<pre><code>import scipy.io as sio
test = sio.loadmat('test.mat')
</code></pre>
| 7 | 2015-06-16T13:25:39Z | [
"python",
"matlab",
"file-io",
"scipy",
"mat-file"
] |
Admin privileges for script | 874,476 | <p>how can i check admin-privileges for my script during running?</p>
| 1 | 2009-05-17T12:09:47Z | 874,485 | <p>On Unix you can check whether you are root using the <a href="http://docs.python.org/3.0/library/os.html#os.getuid" rel="nofollow">os.getuid</a> function:</p>
<pre><code>os.getuid() == 0 and "root" or "not root"
</code></pre>
| 5 | 2009-05-17T12:14:17Z | [
"python",
"unix",
"root",
"sudo"
] |
Admin privileges for script | 874,476 | <p>how can i check admin-privileges for my script during running?</p>
| 1 | 2009-05-17T12:09:47Z | 874,519 | <p>The concept of "admin-privileges" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with "traditional" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough.</p>
<p>Unfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API.</p>
<p>The classic question, why do you need to find out? What if your script tries to do what it needs to do and "just" catches and properly handles failures?</p>
| 7 | 2009-05-17T12:34:19Z | [
"python",
"unix",
"root",
"sudo"
] |
Admin privileges for script | 874,476 | <p>how can i check admin-privileges for my script during running?</p>
| 1 | 2009-05-17T12:09:47Z | 875,739 | <p>If you're just trying to see if you have access to a certain file that requires administrative rights, a good way to check would be:</p>
<pre><code>import os
print os.access("/path/to/file", os.W_OK)
#replace W_OK with R_OK to test for read permissions
</code></pre>
<p>On the other hand, if you really need to know if a user is an administrative account, you can also use this code on Windows 2000 and higher:</p>
<pre><code>import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
</code></pre>
<p>Therefore, a better, cross-platform way to find out if an user is an administrator is:</p>
<pre><code>import ctypes, os
try:
is_admin = os.getuid() == 0
except:
is_admin = ctypes.windll.shell32.IsUserAnAdmin()
print is_admin
</code></pre>
<p>Of course, this method will only detect if the user is <i>root</i> on Unix, or is a member of the Administrators group on Windows. However, this is sufficient for most purposes, in my opinion.</p>
<p>Also note that this will fail on Windows versions below 2000, as well as Windows ME, since those are DOS-based versions of Windows and don't have any notion of permissions.</p>
| 3 | 2009-05-17T23:28:13Z | [
"python",
"unix",
"root",
"sudo"
] |
Python - install script to system | 874,521 | <p>how can I make setup.py file for my own script? I have to make my script global.
(add it to /usr/bin) so I could run it from console just type: scriptName arguments.
OS: Linux.
<strong>EDIT:</strong>
Now my script is installable, but how can i make it global? So that i could run it from console just name typing.</p>
| 26 | 2009-05-17T12:36:31Z | 874,539 | <p>EDIT: This answer deals only with installing executable scripts into <code>/usr/bin</code>. I assume you have basic knowledge on how <code>setup.py</code> files work.</p>
<p>Create your script and place it in your project like this:</p>
<pre><code>yourprojectdir/
setup.py
scripts/
myscript.sh
</code></pre>
<p>In your <code>setup.py</code> file do this:</p>
<pre><code>from setuptools import setup
# you may need setuptools instead of distutils
setup(
# basic stuff here
scripts = [
'scripts/myscript.sh'
]
)
</code></pre>
<p>Then type</p>
<pre><code>python setup.py install
</code></pre>
<p>Basically that's it. There's a chance that your script will land not exactly in <code>/usr/bin</code>, but in some other directory. If this is the case, type</p>
<pre><code>python setup.py install --help
</code></pre>
<p>and search for <code>--install-scripts</code> parameter and friends.</p>
| 30 | 2009-05-17T12:46:22Z | [
"python",
"install"
] |
wxPython: Path problems when exporting a bitmap | 874,625 | <p>I have a module which starts a wxPython app, which loads a <code>wx.Bitmap</code> from file for use as a toolbar button. It looks like this: <code>wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY)</code>. All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory, wxPython raises an exception. (The exception is something internal regarding the toolbar, which I think just means it's not loading the bitmap right.)</p>
<p>What should I do?</p>
| 2 | 2009-05-17T13:27:42Z | 874,644 | <p>"images\new.png" is a relative path, so when bitmap gets loaded it will depened what is the cur dir
so either you set cur dir</p>
<pre><code>os.chdir("location to images folder")
</code></pre>
<p>or
have a function which loads relative to your program e.g.</p>
<pre><code>def getProgramFolder():
moduleFile = __file__
moduleDir = os.path.split(os.path.abspath(moduleFile))[0]
programFolder = os.path.abspath(moduleDir)
return programFolder
bmpFilePath = os.path.join(getProgramFolder(), "images\\new.png")
</code></pre>
| 2 | 2009-05-17T13:45:10Z | [
"python",
"path",
"wxpython"
] |
wxPython: Path problems when exporting a bitmap | 874,625 | <p>I have a module which starts a wxPython app, which loads a <code>wx.Bitmap</code> from file for use as a toolbar button. It looks like this: <code>wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY)</code>. All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory, wxPython raises an exception. (The exception is something internal regarding the toolbar, which I think just means it's not loading the bitmap right.)</p>
<p>What should I do?</p>
| 2 | 2009-05-17T13:27:42Z | 874,665 | <p>The <a href="http://wiki.wxpython.org/Frequently%20Asked%20Questions#head-f3905e355271308d301310f0f8c1af64833ed912" rel="nofollow">wxPython FAQ</a> recommends using a tool called <code>img2py.py</code> to embed icon files into a Python module. This tool comes with the wxPython distribution.</p>
<p>Here is an <a href="http://wiki.wxpython.org/WorkingWithToolBars" rel="nofollow">example of embedding toolbar icons</a>.</p>
| 1 | 2009-05-17T14:00:26Z | [
"python",
"path",
"wxpython"
] |
Python IDLE subprocess error? | 874,757 | <blockquote>
<p>IDLE's subprocess didn't make
connection. Either IDLE can't start a
subprocess or personal firewall
software is blocking the connection.</p>
</blockquote>
<p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager & stop all Pythonw processes to get it to work again?</p>
<p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p>
<pre><code>f = open('money.txt')
currentmoney = float(f.readline())
print(currentmoney, end='')
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Sometimes it works, sometimes it doesn't!</p>
| 9 | 2009-05-17T14:42:48Z | 874,813 | <p>Can you be more specific by providing a short code sample?</p>
<p>IDLE has some threading issues. So the first thing to debug your problem would be to print some simple stuff in your subprocess. Thereby you will see whether it is a network or threading related issue.</p>
| 1 | 2009-05-17T15:19:09Z | [
"python",
"python-3.x",
"python-idle"
] |
Python IDLE subprocess error? | 874,757 | <blockquote>
<p>IDLE's subprocess didn't make
connection. Either IDLE can't start a
subprocess or personal firewall
software is blocking the connection.</p>
</blockquote>
<p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager & stop all Pythonw processes to get it to work again?</p>
<p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p>
<pre><code>f = open('money.txt')
currentmoney = float(f.readline())
print(currentmoney, end='')
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Sometimes it works, sometimes it doesn't!</p>
| 9 | 2009-05-17T14:42:48Z | 874,907 | <p>In Python 3.0.1, I have gotten that error after I Ctrl-C to interrupt a previous run of a program in Idle's Python Shell and then try to run a script.</p>
<p>Also in 3.0.1: Let's say you have two Idle windows open: a script open for editing in one, and Idle's Python Shell window. I have found that if you close the shell window and then immediately try to run the script, it will give that error when it tries to re-open the shell - but not if you wait a bit in between to let Idle do whatever connection clean up it needs to do.</p>
<p>Worse bugs I have found (again, in v3.0.1- not sure if this would happen in the 2.x versions):
I had a long script - getting up towards 9k lines - and once it got to a certain size, doing "save as" on it would crash Idle. I am not sure what the exact threshold was for size - but before that, I would also get some intermittent "save as" crashes that seemed to depend on what else I had going on - other Idle windows, how much output was in the shell window perhaps - stuff like that. It can crash and you will lose unsaved work.</p>
<p>Also - one thing I commonly do is have a scratch window open where I cut and paste bits of code in various stages of validity, write notes to myself, etc - so not a valid python script, but I sometimes save these so I can come back to them. I have one such file that will crash Idle every time I try to open it - and I lost unsaved work the first time. (FYI: Other editors including PythonWin 2.5.2 have no problem opening the file.)</p>
| 1 | 2009-05-17T16:17:45Z | [
"python",
"python-3.x",
"python-idle"
] |
Python IDLE subprocess error? | 874,757 | <blockquote>
<p>IDLE's subprocess didn't make
connection. Either IDLE can't start a
subprocess or personal firewall
software is blocking the connection.</p>
</blockquote>
<p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager & stop all Pythonw processes to get it to work again?</p>
<p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p>
<pre><code>f = open('money.txt')
currentmoney = float(f.readline())
print(currentmoney, end='')
howmuch = (float(input('How much did you put in or take out?:')))
now = currentmoney + howmuch
print(now)
f.close()
f = open('money.txt', 'w')
f.write(str(now))
f.close()
</code></pre>
<p>Sometimes it works, sometimes it doesn't!</p>
| 9 | 2009-05-17T14:42:48Z | 876,312 | <p>You can use <code>idle -n</code> to avoid such issues (albeit possibly getting some other limitations).</p>
| 3 | 2009-05-18T05:06:17Z | [
"python",
"python-3.x",
"python-idle"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.