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 |
|---|---|---|---|---|---|---|---|---|---|
Python - Nested List to Tab Delimited File? | 2,509,706 | <p>I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,</p>
<pre><code>nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
</code></pre>
<p>I wish to create a function in order to output this data construct into a tab delimited format, e.g.,</p>
<pre><code>x y z
a b c
</code></... | 5 | 2010-03-24T16:59:25Z | 2,509,886 | <p>In my view, it's a simple one-liner:</p>
<pre><code>print '\n'.join(['\t'.join(l) for l in nested_list])
</code></pre>
| 3 | 2010-03-24T17:19:49Z | [
"python",
"list",
"nested",
"tab-delimited"
] |
running python code in matlab? | 2,509,927 | <p>i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....</p>
| 3 | 2010-03-24T17:25:40Z | 2,509,968 | <p>You can use the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/system.html" rel="nofollow">system</a> command to execute the Python code externally. To link it in more "natively" I think you'll have to go through C. That is, embed your Python code in C code and then expose it with a DLL to Matlab... | 1 | 2010-03-24T17:31:37Z | [
"python",
"matlab"
] |
running python code in matlab? | 2,509,927 | <p>i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....</p>
| 3 | 2010-03-24T17:25:40Z | 2,509,973 | <p>There is a library called <a href="http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html" rel="nofollow">PyMat</a>. It allows to call python code from matlab.</p>
| -2 | 2010-03-24T17:31:58Z | [
"python",
"matlab"
] |
running python code in matlab? | 2,509,927 | <p>i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....</p>
| 3 | 2010-03-24T17:25:40Z | 2,511,441 | <p>The only thing I know of is pythoncall but it is a little out of date and I'm not sure it will work reliably with recent versions of matlab.</p>
<p><a href="http://www.elisanet.fi/ptvirtan/software/pythoncall/index.html" rel="nofollow">http://www.elisanet.fi/ptvirtan/software/pythoncall/index.html</a></p>
<p>Other... | 1 | 2010-03-24T21:10:47Z | [
"python",
"matlab"
] |
running python code in matlab? | 2,509,927 | <p>i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....</p>
| 3 | 2010-03-24T17:25:40Z | 2,511,689 | <p>You should probably avoid this. Use one or the other - preferably Python.
But if you have to use both, you could try this:</p>
<p><a href="http://github.com/kw/pymex" rel="nofollow">http://github.com/kw/pymex</a> (scroll down for the readme)</p>
<p>Disclaimer: I wrote this. It may be somewhat difficult to get it t... | 4 | 2010-03-24T21:54:30Z | [
"python",
"matlab"
] |
Can this be done with the ORM? - Django | 2,510,031 | <p>I have a few item listed in a database, ordered through <strong>Reddit's algorithm</strong>.</p>
<p>This is it:</p>
<pre><code>def reddit_ranking(post):
t = time.mktime(post.created_on.timetuple()) - 1134000000
x = post.score
if x>0: y=1
elif x==0: y=-0
else: y=-1
if x<0: z=1
el... | 1 | 2010-03-24T17:37:32Z | 2,510,221 | <p>It's not much work to do it manually:</p>
<pre><code>from django.db import connection
items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7))
cursor = connection.cursor()
cursor.executemany("UPDATE myapp_item SET reddit_rank = %s WHERE id = %s",
[(reddit_rank(item), item.pk... | 2 | 2010-03-24T18:00:23Z | [
"python",
"sql",
"django",
"orm",
"django-orm"
] |
More nest Python nested dictionaries | 2,510,126 | <p>After reading <a href="http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python">http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python</a> why is it wrong to do:</p>
<pre><code>c = collections.defaultdict(collection... | 3 | 2010-03-24T17:48:11Z | 2,510,138 | <p>The constructor of <code>defaultdict</code> expects a callable. <code>defaultdict(int)</code> is a default dictionary object, not a callable. Using a <code>lambda</code> it can work, however:</p>
<pre><code>c = collections.defaultdict(lambda: collections.defaultdict(int))
</code></pre>
<p>This works since what I p... | 14 | 2010-03-24T17:49:51Z | [
"python",
"collections",
"nested"
] |
More nest Python nested dictionaries | 2,510,126 | <p>After reading <a href="http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python">http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python</a> why is it wrong to do:</p>
<pre><code>c = collections.defaultdict(collection... | 3 | 2010-03-24T17:48:11Z | 2,510,245 | <p>Eli Bendersky provides a great direct answer for this question. It might also be better to restructure your data to</p>
<pre><code>>>> import collections
>>> c = collections.defaultdict(int)
>>> c[1, 2] = 'foo'
>>> c[5, 6] = 'bar'
>>> c
defaultdict(<type 'int'>, {(... | 5 | 2010-03-24T18:04:19Z | [
"python",
"collections",
"nested"
] |
Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog | 2,510,158 | <p>Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed login attempts - a sort of "blacklist".</p>
<p>So basically something like:</p>
<p>if "uniqueipaddress" and "a... | 0 | 2010-03-24T17:51:47Z | 2,510,205 | <p>For each line:</p>
<ul>
<li>read the IP and attempt status</li>
<li>keep a dictionary by IP of amount of failed attempts</li>
</ul>
<p>Then go over the dictionary:</p>
<ul>
<li>print to file all IPs with 5 or more attempts</li>
</ul>
<hr>
<p>Python hints:</p>
<ul>
<li>To read a file line by line: <code>for lin... | 1 | 2010-03-24T17:57:22Z | [
"python",
"ip-address",
"syslog",
"blacklist"
] |
Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog | 2,510,158 | <p>Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed login attempts - a sort of "blacklist".</p>
<p>So basically something like:</p>
<p>if "uniqueipaddress" and "a... | 0 | 2010-03-24T17:51:47Z | 2,511,206 | <p>The following code should do something similar to what you're looking for. It's not perfect, but it's a good jumping off point.</p>
<pre><code>ips = {}
for line in open('your_log.txt'):
parts = line.split(' ') #assuming this is a good place to split
if parts[1] == "AuthenticationFailure":
if parts[... | 0 | 2010-03-24T20:37:31Z | [
"python",
"ip-address",
"syslog",
"blacklist"
] |
maintaining a large list in python | 2,510,218 | <p>I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.</p>
<p>The list should implement all the python-list features, but ... | 3 | 2010-03-24T17:59:34Z | 2,511,026 | <p>I think the ZODB is the tool to use. It will store lots of arbitrary items, it handles memory issues.</p>
<p>Here is a working example, and in this case I included objects that reference each other as well as being stored in a BTree by number. </p>
<pre><code>import random
from collections import deque
import Z... | 0 | 2010-03-24T20:07:50Z | [
"python",
"database",
"zodb"
] |
maintaining a large list in python | 2,510,218 | <p>I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.</p>
<p>The list should implement all the python-list features, but ... | 3 | 2010-03-24T17:59:34Z | 2,511,693 | <p>How about using Tokyo Cabinet? Very fast and simple, like lists but built for what you want.
<a href="http://1978th.net/tokyocabinet/" rel="nofollow">http://1978th.net/tokyocabinet/</a></p>
| 0 | 2010-03-24T21:54:40Z | [
"python",
"database",
"zodb"
] |
maintaining a large list in python | 2,510,218 | <p>I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.</p>
<p>The list should implement all the python-list features, but ... | 3 | 2010-03-24T17:59:34Z | 2,527,637 | <p>Using zc.blist can bring good results after all, and setting the "cache_size" option when creating the DB controls the size of the data that will remain in the RAM. The size of used RAM can grow bigger if you don't do "transaction.commit" often enough. By defining a large cache_size and doing transaction.commit ofte... | 2 | 2010-03-27T00:21:36Z | [
"python",
"database",
"zodb"
] |
Keeping track of user habits and activities? - Django | 2,510,264 | <p>I was working on a project a few months ago, and had the need to implement an <strong>award system</strong>. Similar to S*<em>tackOverflow's badge system</em>*. <a href="http://stackoverflow.com/badges">Badges</a></p>
<p>I might have not implemented it in the best possible way, and I am curious what your say in it ... | 2 | 2010-03-24T18:07:03Z | 2,510,530 | <p>I don't think is as complicated as you think. I highly doubt that SO calculates badges with some kind of user activity log (although technically the entire database is a user activity log). When I look at the lists of badges, I don't see anything that can't be implemented by running a SQL select query.</p>
<p>Som... | 2 | 2010-03-24T18:48:27Z | [
"python",
"sql",
"django",
"logging",
"badge"
] |
Keeping track of user habits and activities? - Django | 2,510,264 | <p>I was working on a project a few months ago, and had the need to implement an <strong>award system</strong>. Similar to S*<em>tackOverflow's badge system</em>*. <a href="http://stackoverflow.com/badges">Badges</a></p>
<p>I might have not implemented it in the best possible way, and I am curious what your say in it ... | 2 | 2010-03-24T18:07:03Z | 2,516,818 | <p>In general badge/point systems can be based on two things.</p>
<ul>
<li><p>Activity log of interesting events, this is effectively the paper register receipt of what has happend such that you can re-compute from the ground up if it's ever needed. Can be as simple as (user_id, timestamp, event_id, event_detail)</p>... | 0 | 2010-03-25T15:24:42Z | [
"python",
"sql",
"django",
"logging",
"badge"
] |
How do I render text with pixel heights rather than points in pyglet? | 2,510,278 | <p>Pyglet only seems to use points. Is there a way to convert easily? Surely there must be a simple way because it's something obviously important, to be able to use pixels for text height.</p>
<pre><code>class Font():
def __init__(self,font,size):
self.size = size
self.font = font
def return_s... | 0 | 2010-03-24T18:08:39Z | 2,511,434 | <p>The number of pixels taken up by a certain point size will depend on your screens DPI.
For example, "14pt" is the distance covering 14 points, which at a default DPI of 96 is around 18 pixels.</p>
<p>This <a href="http://www.emdpi.com/fontsize.html" rel="nofollow">site</a> give a good explanation of converting poin... | 0 | 2010-03-24T21:09:45Z | [
"python",
"text",
"fonts",
"label",
"pyglet"
] |
What's the best django way to do a query that spans several tables? | 2,510,429 | <p>I have a reviews/ratings web application, a la Digg. My django app <code>content</code> has the following model:</p>
<pre><code>class Content(models.Model):
title = models.CharField(max_length=128)
url = models.URLField(max_length=2048)
description = models.TextField(blank=True)
class Recommendation(mo... | 2 | 2010-03-24T18:34:05Z | 2,510,599 | <p>I think that it's:</p>
<pre><code> Content.objects.filter(recommendation_set__user__publication_set__subscriber__pk=request.user.pk)/.distinct()/
</code></pre>
<p>or</p>
<pre><code> Recommendation.objects.filter(user__publication_set__subscriber__pk=request.user.pk)/.distinct()/
</code></pre>
<p>-- depending o... | 1 | 2010-03-24T18:57:54Z | [
"python",
"mysql",
"database",
"django"
] |
What's the best django way to do a query that spans several tables? | 2,510,429 | <p>I have a reviews/ratings web application, a la Digg. My django app <code>content</code> has the following model:</p>
<pre><code>class Content(models.Model):
title = models.CharField(max_length=128)
url = models.URLField(max_length=2048)
description = models.TextField(blank=True)
class Recommendation(mo... | 2 | 2010-03-24T18:34:05Z | 2,510,693 | <p>I would use:</p>
<pre><code>Recommendation.objects.filter(user__publication_set__subscriber=request.user).select_related()
</code></pre>
<p>That will get you all the Recommendation objects as you requested, and the select_related will load all the related User and Content objects into memory so that subsequent acc... | 10 | 2010-03-24T19:11:26Z | [
"python",
"mysql",
"database",
"django"
] |
Python: Count lines and differentiate between them | 2,510,651 | <p>I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. </p>
<p>An example output is this: </p>
<pre><code>13:48 An event happened.
... | 1 | 2010-03-24T19:05:53Z | 2,510,689 | <p>You could just use the time as a key for a dictionary and point it to a list of event messages. The length of that value would give you the number of events, while still letting you get at the specific events themselves:</p>
<pre><code>>>> from pprint import pprint
>>> from collections import defa... | 4 | 2010-03-24T19:10:58Z | [
"python",
"count"
] |
Python: Count lines and differentiate between them | 2,510,651 | <p>I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. </p>
<p>An example output is this: </p>
<pre><code>13:48 An event happened.
... | 1 | 2010-03-24T19:05:53Z | 2,511,106 | <p>If you don't need to know what happen but only how many times then:</p>
<pre><code>$ python3.1 -c'from collections import Counter
import fileinput
c = Counter(line.split(None, 1)[0] for line in fileinput.input() if line.strip())
print(c)' events.txt
</code></pre>
<p>Output:</p>
<pre><code>Counter({'13:49': 3, '1... | 1 | 2010-03-24T20:22:50Z | [
"python",
"count"
] |
Python: Count lines and differentiate between them | 2,510,651 | <p>I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. </p>
<p>An example output is this: </p>
<pre><code>13:48 An event happened.
... | 1 | 2010-03-24T19:05:53Z | 2,511,945 | <p>If you just want a count of how many events happen each minute then you don't really need python, you can do it from bash:</p>
<pre><code> cut -d ' ' -f1 filename | uniq -c
</code></pre>
<p>gives </p>
<pre><code> 2 13:48
3 13:49
</code></pre>
| 3 | 2010-03-24T22:36:28Z | [
"python",
"count"
] |
Python: Count lines and differentiate between them | 2,510,651 | <p>I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. </p>
<p>An example output is this: </p>
<pre><code>13:48 An event happened.
... | 1 | 2010-03-24T19:05:53Z | 2,513,370 | <p>You can also use a <code>groupby</code> function from an <code>itertools</code> module with time as a grouping key.</p>
<pre><code>>>> import itertools
>>> from operator import itemgetter
>>> lines = (line.strip().split(None, 1) for line in open('log.txt'))
>>> for key, group in ... | 1 | 2010-03-25T05:53:44Z | [
"python",
"count"
] |
Python: Count lines and differentiate between them | 2,510,651 | <p>I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. </p>
<p>An example output is this: </p>
<pre><code>13:48 An event happened.
... | 1 | 2010-03-24T19:05:53Z | 2,513,387 | <pre><code>awk '{_[$1]++}END{for(i in _) print i,_[i]}' filename
</code></pre>
| 0 | 2010-03-25T05:58:18Z | [
"python",
"count"
] |
Allowing threads from python after calling a blocking i/o code in a python extension generated using SWIG | 2,510,696 | <p>I have written a python extension wrapping an existing C++ library <a href="http://live555.com" rel="nofollow">live555</a> (wrapping RTSP client interface to be specific) in SWIG. The extension works when it is operated in a single thread, but as soon as I call the event loop function of the library, python interpre... | 1 | 2010-03-24T19:11:40Z | 2,512,155 | <p>SWIG gives you plenty of hooks to help make this happen. If a coarse solution is sufficient for your needs, one thing I've done in the past is put something like this in my .swig file:</p>
<pre><code>%exception {
Py_BEGIN_ALLOW_THREADS
$action
Py_END_ALLOW_THREADS
}
</code></pre>
<p>This (ab)uses the ... | 3 | 2010-03-24T23:22:06Z | [
"python",
"swig",
"rtsp-client"
] |
Short Python alphanumeric hash with minimal collisions | 2,510,716 | <p>I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). </p>
<p>What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision... | 13 | 2010-03-24T19:14:36Z | 2,510,733 | <p>Why don't you just truncate SHA1 or MD5? You'll have more collisions then if you didn't truncate, but it's still better than designing your own. Note that you can base64-encode the truncated hash, rather than using hexadecimal. E.g.</p>
<pre><code>import base64
import hashlib
hasher = hashlib.sha1("The quick bro... | 12 | 2010-03-24T19:16:22Z | [
"python",
"hash"
] |
Short Python alphanumeric hash with minimal collisions | 2,510,716 | <p>I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). </p>
<p>What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision... | 13 | 2010-03-24T19:14:36Z | 2,510,935 | <p>The smallest builtin hash I am aware of is md5</p>
<pre><code>>>> import hashlib
>>> hashlib.md5("hello worlds").digest().encode("base64")
'uWuHitcvVnCdu1Yo4c6hjQ==\n'
</code></pre>
<p>Low collision and short are somewhat mutually exclusive due to the <a href="http://en.wikipedia.org/wiki/Birthda... | 17 | 2010-03-24T19:51:52Z | [
"python",
"hash"
] |
Short Python alphanumeric hash with minimal collisions | 2,510,716 | <p>I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). </p>
<p>What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision... | 13 | 2010-03-24T19:14:36Z | 2,511,059 | <p>Below is a solution that uses alphanumeric characters plus a few punctuation characters. It returns very short strings (around 8 characters).</p>
<pre><code>import binascii, struct
def myhash(s):
return binascii.b2a_base64(struct.pack('i', hash(s)))
</code></pre>
| 2 | 2010-03-24T20:14:18Z | [
"python",
"hash"
] |
Short Python alphanumeric hash with minimal collisions | 2,510,716 | <p>I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). </p>
<p>What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision... | 13 | 2010-03-24T19:14:36Z | 3,682,446 | <p>You can use something like base 32 notation. It is more compact than decimal notation, case insensitive and collision-free. Just encode a plain old sequence number to generate a short hash-like code. </p>
<p>If the key is not for human consumption, you can use base 64 notation, which is case sensitive but a little ... | 0 | 2010-09-10T05:35:00Z | [
"python",
"hash"
] |
Short Python alphanumeric hash with minimal collisions | 2,510,716 | <p>I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). </p>
<p>What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision... | 13 | 2010-03-24T19:14:36Z | 31,479,994 | <p>Hashids is a library (with Python support) that creates hashes that you can encode/decode very easily.</p>
<p><a href="http://hashids.org/python/" rel="nofollow">http://hashids.org/python/</a></p>
| 0 | 2015-07-17T16:01:38Z | [
"python",
"hash"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,510,816 | <p>If you define an alphabet of characters, you can just convert to base 10, do an average, and convert back to base-N where N is the size of the alphabet.</p>
<pre><code>alphabet = 'abcdefghijklmnopqrstuvwxyz'
def enbase(x):
n = len(alphabet)
if x < n:
return alphabet[x]
return enbase(x/n) + a... | 6 | 2010-03-24T19:30:05Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,510,825 | <p>Based on your proposed usage, consistent hashing ( <a href="http://en.wikipedia.org/wiki/Consistent_hashing" rel="nofollow">http://en.wikipedia.org/wiki/Consistent_hashing</a> ) seems to make more sense.</p>
| 2 | 2010-03-24T19:31:34Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,510,928 | <p>It sounds like what you want, is to treat alphabetical characters as a base-26 value between 0 and 1. When you have strings of different length (an example in base 10), say 305 and 4202, your coming out with a midpoint of 3, since you're looking at the characters one at a time. Instead, treat them as a floating po... | 6 | 2010-03-24T19:49:49Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,510,989 | <pre><code>import math
def avg(str1,str2):
y = ''
s = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(str1)):
x = s.index(str2[i])+s.index(str1[i])
x = math.floor(x/2)
y += s[x]
return y
print(avg('z','a')) # m
print(avg('aa','az')) # am
print(avg('cat','dog')) # chm
</code></pr... | 0 | 2010-03-24T20:00:26Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,510,990 | <p>If you mean the alphabetically, simply use FogleBird's algorithm but reverse the parameters and the result!</p>
<pre><code>>>> print average('cat'[::-1], 'doggie'[::-1])[::-1]
cumdec
</code></pre>
<p>or rewriting average like so</p>
<pre><code>>>> def average(a, b):
... a = debase(a[::-1])
.... | 6 | 2010-03-24T20:00:46Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,511,153 | <p>This version thinks 'abc' is a fraction like 0.abc. In this approach space is zero and a valid input/output.</p>
<pre><code>MAX_ITER = 10
letters = " abcdefghijklmnopqrstuvwxyz"
def to_double(name):
d = 0
for i, ch in enumerate(name):
idx = letters.index(ch)
d += idx * len(letters) ** (-i - ... | 0 | 2010-03-24T20:28:50Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,512,556 | <p>I haven't programmed in python in a while and this seemed interesting enough to try.
Bear with my recursive programming. Too many functional languages look like python.</p>
<pre><code>def stravg_half(a, ln):
# If you have a problem it will probably be in here.
# The floor of the character's value is 0, b... | 0 | 2010-03-25T01:15:31Z | [
"python",
"algorithm"
] |
Average of two strings in alphabetical/lexicographical order | 2,510,755 | <p>Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.</p>
<p>You could extend it to strings with more than one cha... | 8 | 2010-03-24T19:19:43Z | 2,544,310 | <p>Thanks for everyone who answered, but I ended up writing my own solution because the others weren't exactly what I needed. I am trying to average app engine key names, and after studying them a bit more I discovered they actually allow any 7-bit ASCII characters in the names. Additionally I couldn't really rely on t... | 1 | 2010-03-30T10:07:14Z | [
"python",
"algorithm"
] |
python, accessing a psycopg2 form a def? | 2,510,756 | <p>i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python</p>
<p>i have tried this:</p>
<pre><code>def get_dblink( dbstring):
"""
Return a database cnx.
"""
global psycopg2
try
cnx = psycopg2.connect( dbstring)
except Exception, e:
print "Unab... | 2 | 2010-03-24T19:19:45Z | 2,510,821 | <p>You just need to <code>import psycopg2</code> in your first snippet.</p>
<p>If you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use <code>globals</code> for this is bad practice.</p>
<p><strong>So</strong>: at the top of ever... | 4 | 2010-03-24T19:30:41Z | [
"python",
"psycopg2"
] |
Persistent Hashing of Strings in Python | 2,511,058 | <p>How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example <code>hash('my string')</code> wouldn't work because a different value is returned for each Python session and platform.</p>
| 19 | 2010-03-24T20:14:16Z | 2,511,075 | <p>Use a hash algorithm such as MD5 or SHA1, then convert the <code>hexdigest</code> via <code>int()</code>:</p>
<pre><code>>>> import hashlib
>>> int(hashlib.md5('Hello, world!').hexdigest(), 16)
144653930895353261282233826065192032313L
</code></pre>
| 26 | 2010-03-24T20:17:29Z | [
"python"
] |
Persistent Hashing of Strings in Python | 2,511,058 | <p>How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example <code>hash('my string')</code> wouldn't work because a different value is returned for each Python session and platform.</p>
| 19 | 2010-03-24T20:14:16Z | 2,511,190 | <p>First off, you probably don't <em>really</em> want the integers to be actually unique. If you do then your numbers might be unlimited in size. If that really is what you want then you could use a bignum library and interpret the bits of the string as the representation of a (potentially very large) integer. If your ... | 2 | 2010-03-24T20:34:42Z | [
"python"
] |
Persistent Hashing of Strings in Python | 2,511,058 | <p>How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example <code>hash('my string')</code> wouldn't work because a different value is returned for each Python session and platform.</p>
| 19 | 2010-03-24T20:14:16Z | 2,511,232 | <p>If a hash function really won't work for you, you can turn the string into a number. </p>
<pre><code>my_string = 'my string'
def string_to_int(s):
ord3 = lambda x : '%.3d' % ord(x)
return int(''.join(map(ord3, s)))
In[10]: string_to_int(my_string)
Out[11]: 109121032115116114105110103L
</code></pre>
<p>Thi... | 8 | 2010-03-24T20:41:51Z | [
"python"
] |
Persistent Hashing of Strings in Python | 2,511,058 | <p>How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example <code>hash('my string')</code> wouldn't work because a different value is returned for each Python session and platform.</p>
| 19 | 2010-03-24T20:14:16Z | 13,023,766 | <p>Here are my python27 implementation for algorithms listed here: <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow">http://www.cse.yorku.ca/~oz/hash.html</a>.
No idea if they are efficient or not.</p>
<pre><code>from ctypes import c_ulong
def ulong(i): return c_ulong(i).value # numpy would be better if... | 3 | 2012-10-23T04:52:22Z | [
"python"
] |
Persistent Hashing of Strings in Python | 2,511,058 | <p>How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example <code>hash('my string')</code> wouldn't work because a different value is returned for each Python session and platform.</p>
| 19 | 2010-03-24T20:14:16Z | 14,471,247 | <p>Here's another option, quite crude (probably has many collisions) and not very legible.</p>
<p>It worked for the purpose of generating an int (and later on, a random color) for different strings:</p>
<pre><code>aString = "don't panic"
reduce( lambda x,y:x+y, map( lambda x:ord(x[0])*x[1],zip( aString, range( 1, len... | 0 | 2013-01-23T01:55:23Z | [
"python"
] |
XML file as model for django project | 2,511,091 | <p>I have a XML file that is managed by other programs, I am writing a web service such that users are able to query this file. In essence i am using a xml based database instead of using sql as the model database in Django.</p>
<p>how do i do this? all the tutorials that i find use a sql database in the backend. is t... | 2 | 2010-03-24T20:19:57Z | 2,511,105 | <p>Use <a href="http://www.w3.org/TR/xpath20/" rel="nofollow">XPath</a> with <a href="http://codespeak.net/lxml/xpathxslt.html#xpath" rel="nofollow"><code>lxml</code></a> to find specific nodes within the document.</p>
| 0 | 2010-03-24T20:22:49Z | [
"python",
"django",
"django-models"
] |
XML file as model for django project | 2,511,091 | <p>I have a XML file that is managed by other programs, I am writing a web service such that users are able to query this file. In essence i am using a xml based database instead of using sql as the model database in Django.</p>
<p>how do i do this? all the tutorials that i find use a sql database in the backend. is t... | 2 | 2010-03-24T20:19:57Z | 5,518,951 | <p>There's a package to do just this available <a href="http://djangorestmodel.sourceforge.net/" rel="nofollow">here</a>. I haven't tried it, but looking through the source, it seems to be doing pretty much what you're asking.</p>
| 1 | 2011-04-01T21:15:38Z | [
"python",
"django",
"django-models"
] |
AES encryption with PyCrypto and decryption with mcrypt | 2,511,126 | <p>For some sensitive data I decided to store it AES-encrypted on disc. I've implemented the encryption using <a href="http://www.pycrypto.org/" rel="nofollow">PyCrypto</a>.</p>
<p>Furthermore, the data is important, and the stored encrypted data will be my only copy of it (backups aside), so I looked for some means o... | 2 | 2010-03-24T20:25:04Z | 2,512,083 | <p>Why is it important to be able to recover without PyCrypto?</p>
<p>But if that is the case, you should probably use something else. You didn't indicate how big the thing is that you want to save. But you might use PGP or OpenSSL or some other widely available encryption system. </p>
| 0 | 2010-03-24T23:05:03Z | [
"python",
"encryption",
"aes",
"mcrypt",
"pycrypto"
] |
AES encryption with PyCrypto and decryption with mcrypt | 2,511,126 | <p>For some sensitive data I decided to store it AES-encrypted on disc. I've implemented the encryption using <a href="http://www.pycrypto.org/" rel="nofollow">PyCrypto</a>.</p>
<p>Furthermore, the data is important, and the stored encrypted data will be my only copy of it (backups aside), so I looked for some means o... | 2 | 2010-03-24T20:25:04Z | 8,445,784 | <p>I think the problem may lay in the fact that you don't supply an IV for CBC mode and without an IV maybe mCrypt and PyCrypto handle it differently by using different default IVs. I have seen some implementations (phpseclib for instance) use and IV of 16 null bytes by default. mcrypt might not do this.</p>
| 1 | 2011-12-09T12:55:12Z | [
"python",
"encryption",
"aes",
"mcrypt",
"pycrypto"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 2,511,238 | <p>You can use this:</p>
<pre><code>>>> import random
>>> ''.join(random.choice('0123456789ABCDEF') for i in range(16))
'E2C6B2E19E4A7777'
</code></pre>
<p>There is no guarantee that the keys generated will be unique so you should be ready to retry with a new key in the case the original insert fail... | 31 | 2010-03-24T20:42:58Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 2,511,244 | <p>Have a look at the <a href="http://docs.python.org/library/uuid.html" rel="nofollow">uuid module</a> (Python 2.5+).</p>
<p>A quick example:</p>
<pre><code>>>> import uuid
>>> uid = uuid.uuid4()
>>> uid.hex
'df008b2e24f947b1b873c94d8a3f2201'
</code></pre>
<p>Note that the OP asked for a ... | 18 | 2010-03-24T20:43:17Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 2,511,387 | <p>This value is incremented by 1 on each call (it wraps around). Deciding where the best place to store the value will depend on how you are using it. You may find <a href="http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx" rel="nofollow">this</a> explanation of interest, as it discusses not only how... | 2 | 2010-03-24T21:02:45Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 3,817,309 | <p>For random numbers a good source is <code>os.urandom</code>:</p>
<pre><code> >> import os
>> import hashlib
>> random_data = os.urandom(128)
>> hashlib.md5(random_data).hexdigest()[:16]
</code></pre>
| 4 | 2010-09-28T21:53:42Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 23,268,106 | <h1>Simply use python builtin uuid:</h1>
<p>If UUIDs are okay for your purposes use the built in <a href="http://docs.python.org/2/library/uuid.html" rel="nofollow">uuid</a> package.</p>
<h2>One Line Solution:</h2>
<pre><code>>>> import uuid
>>> str(uuid.uuid4().get_hex().upper()[0:16])
'40003A9B8C... | 0 | 2014-04-24T11:51:20Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 28,947,019 | <pre><code>>>> import random
>>> ''.join(random.sample(map(chr, range(48, 57) + range(65, 90) + range(97, 122)), 16))
'CDh0geq3NpKtcXfP'
</code></pre>
| 2 | 2015-03-09T16:27:18Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 30,779,367 | <p>As none of the answers provide you with a random string consisting of characters 0-9, a-z, A-Z: Here is a working solution which will give you approx. 4.5231285e+74 keys:</p>
<pre><code>import random, string
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16... | 12 | 2015-06-11T11:21:17Z | [
"python",
"hash",
"random"
] |
Efficiently generate a 16-character, alphanumeric string | 2,511,222 | <p>I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.</p>
<p>Would something like this work?</p>
<pre><code>def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
return alnum_hash[:16]
</co... | 19 | 2010-03-24T20:40:16Z | 38,906,979 | <pre><code>import uuid
print str(uuid.uuid1()).replace('-','')
</code></pre>
| 0 | 2016-08-11T22:19:27Z | [
"python",
"hash",
"random"
] |
Is there a way to change lookandfeel for wx Python? | 2,511,228 | <p>i was curious if there is some sort of way to change the look and feel of wxpython to something that is more standardized. I am writing a small application for windows and mac os x. And i noticed that Mac formats the layout and look of my application pretty terribly. I looked around online and could not find anythin... | 0 | 2010-03-24T20:40:56Z | 2,511,520 | <p>From <a href="http://old.nabble.com/wxPython-Themes-Colors-td20337650.html" rel="nofollow">http://old.nabble.com/wxPython-Themes-Colors-td20337650.html</a>:</p>
<blockquote>
<p>Not really. The default colors are always the platform and/or theme
defaults, but some things can be changed by setting the colors of ... | 2 | 2010-03-24T21:24:28Z | [
"python",
"wxpython",
"wx"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 2,511,319 | <p>The asterisk performs <code>apply</code> (as it's known in Lisp and Scheme). Basically, it takes your list, and calls the function with that list's contents as arguments.</p>
| 14 | 2010-03-24T20:54:08Z | [
"python",
"zip"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 2,511,332 | <p>The asterisk in Python is documented in the Python tutorial, under <a href="http://docs.python.org/tutorial/controlflow.html#tut-unpacking-arguments">Unpacking Argument Lists</a>.</p>
| 31 | 2010-03-24T20:55:32Z | [
"python",
"zip"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 2,511,400 | <p>It's also useful for multiple args:</p>
<pre><code>def foo(*args):
print args
foo(1, 2, 3) # (1, 2, 3)
# also legal
t = (1, 2, 3)
foo(*t) # (1, 2, 3)
</code></pre>
<p>And, you can use double asterisk for keyword arguments and dictionaries:</p>
<pre><code>def foo(**kwargs):
print kwargs
foo(a=1, b=2) # {'a... | 7 | 2010-03-24T21:04:43Z | [
"python",
"zip"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 16,246,006 | <p>It doesn't always work:</p>
<pre><code>>>> x = []
>>> y = []
>>> zipped = zip(x, y)
>>> unzipped_x, unzipped_y = zip(*zipped)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
</code></pre>
<p>Oops!... | 4 | 2013-04-26T22:13:54Z | [
"python",
"zip"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 23,608,246 | <p>Addendum to @bcherry's answer:</p>
<pre><code>>>> def f(a2,a1):
... print a2, a1
...
>>> d = {'a1': 111, 'a2': 222}
>>> f(**d)
222 111
</code></pre>
<p>So it works not just with keyword arguments (in <a href="http://stackoverflow.com/questions/1419046/python-normal-arguments-vs-keyword... | 0 | 2014-05-12T11:48:49Z | [
"python",
"zip"
] |
Why does x,y = zip(*zip(a,b)) work in Python? | 2,511,300 | <p>OK I love Python's <code>zip()</code> function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of <code>zip()</code>, think "I used to know how to do that", then google python unzip, then remember that one uses this magical <code>*</code> to unzip a zipped list of tuples. Like thi... | 59 | 2010-03-24T20:51:31Z | 28,710,417 | <p>I'm extremely new to Python so this just recently tripped me up, but it had to do more with how the example was presented and what was emphasized.</p>
<p>What gave me problems with understanding the zip example was the asymmetry in the handling of the zip call return value(s). That is, when zip is called the first ... | 0 | 2015-02-25T03:07:52Z | [
"python",
"zip"
] |
Calling private parent class method from parent class (django) | 2,511,321 | <p>I want to call a redefined private method from an abstract parent class. I am using django if that matters.</p>
<pre><code>class Parent(models.Model):
def method1(self):
#do somthing
self.__method2()
def method2(self):
pass # I also tried calling up a prent method with super
cla... | 0 | 2010-03-24T20:54:22Z | 2,511,345 | <p>Initial double underscores prevent polymorphism since both the method definition <em>and</em> the method call get mangled, to two different names. Replace with a single underscore to fix this.</p>
<p>Also, double underscores are <em>not</em> used for "private" attributes, and you should discard whatever reference t... | 2 | 2010-03-24T20:57:04Z | [
"python",
"django",
"inheritance",
"abstract-class"
] |
Clear all class variables between instances | 2,511,556 | <p>This is probably a stupid question, but what's the best way to clear class variables between instances? </p>
<p>I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? </p>
<p>Or am I doing something totally wrong that requires a different approach? Thanks for ... | 3 | 2010-03-24T21:30:07Z | 2,511,576 | <p>Can you just pass the parameters into the constructor like this?</p>
<pre><code>class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
def commit(self):
pass
jason = User('jason', 'jason@email.com')
jack = User('jack', 'jack@yahoo.com')
</code></pre... | 2 | 2010-03-24T21:33:34Z | [
"python",
"oop",
"class",
"pylons"
] |
Clear all class variables between instances | 2,511,556 | <p>This is probably a stupid question, but what's the best way to clear class variables between instances? </p>
<p>I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? </p>
<p>Or am I doing something totally wrong that requires a different approach? Thanks for ... | 3 | 2010-03-24T21:30:07Z | 2,511,577 | <p>Binding an attribute on an instance creates instance attributes, not class attributes. Perhaps you are seeing another problem that is not shown in the code above.</p>
| 0 | 2010-03-24T21:33:39Z | [
"python",
"oop",
"class",
"pylons"
] |
Clear all class variables between instances | 2,511,556 | <p>This is probably a stupid question, but what's the best way to clear class variables between instances? </p>
<p>I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? </p>
<p>Or am I doing something totally wrong that requires a different approach? Thanks for ... | 3 | 2010-03-24T21:30:07Z | 2,511,579 | <p>This code does not change the <code>name</code> or <code>email</code> attributes of any of the instances of <code>User</code> except for <code>u</code>. </p>
| 0 | 2010-03-24T21:34:09Z | [
"python",
"oop",
"class",
"pylons"
] |
Clear all class variables between instances | 2,511,556 | <p>This is probably a stupid question, but what's the best way to clear class variables between instances? </p>
<p>I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? </p>
<p>Or am I doing something totally wrong that requires a different approach? Thanks for ... | 3 | 2010-03-24T21:30:07Z | 2,511,585 | <p>If you want to reset the values each time you construct a new object then you should be using instance variables, not class variables.</p>
<p>If you use class variables and try to create more than one user object at the same time then one will overwrite the other's changes.</p>
| 2 | 2010-03-24T21:34:49Z | [
"python",
"oop",
"class",
"pylons"
] |
Python: Number of rows affected by cursor.execute("SELECT ...) | 2,511,679 | <p>How can I access the number of rows affected by:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
</code></pre>
| 26 | 2010-03-24T21:52:54Z | 2,511,718 | <p>From <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a>, which is usually implemented by Python database APIs:</p>
<blockquote>
<p>Cursor Objects should respond to the following methods and attributes:</p>
<p>[...]</p>
<p>.rowcount<br>
This read-only attribute specifies the num... | 70 | 2010-03-24T21:59:35Z | [
"python",
"sql",
"rows",
"database"
] |
Python: Number of rows affected by cursor.execute("SELECT ...) | 2,511,679 | <p>How can I access the number of rows affected by:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
</code></pre>
| 26 | 2010-03-24T21:52:54Z | 2,512,521 | <p>Try using <code>fetchone</code>:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()
</code></pre>
<p><code>result</code> will hold a tuple with one element, the value of <code>COUNT(*)</code>.
So to find the number o... | 34 | 2010-03-25T01:07:06Z | [
"python",
"sql",
"rows",
"database"
] |
Python: Number of rows affected by cursor.execute("SELECT ...) | 2,511,679 | <p>How can I access the number of rows affected by:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
</code></pre>
| 26 | 2010-03-24T21:52:54Z | 2,834,349 | <p>The number of rows effected is returned from execute:</p>
<pre><code>rows_affected=cursor.execute("SELECT ... ")
</code></pre>
<p>of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:</p>
<pre><code>cu... | 25 | 2010-05-14T13:08:27Z | [
"python",
"sql",
"rows",
"database"
] |
Python: Number of rows affected by cursor.execute("SELECT ...) | 2,511,679 | <p>How can I access the number of rows affected by:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
</code></pre>
| 26 | 2010-03-24T21:52:54Z | 19,854,354 | <p>In my opinion, the simplest way to get the amount of selected rows is the following:</p>
<p>The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)<... | 7 | 2013-11-08T08:14:09Z | [
"python",
"sql",
"rows",
"database"
] |
Python: Number of rows affected by cursor.execute("SELECT ...) | 2,511,679 | <p>How can I access the number of rows affected by:</p>
<pre><code>cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
</code></pre>
| 26 | 2010-03-24T21:52:54Z | 25,589,624 | <p>for mysql simplest way is this </p>
<pre><code>mycur.execute("SELECT COUNT(*) FROM osreport")
print(mycur.fetchall())
</code></pre>
| 1 | 2014-08-31T06:51:21Z | [
"python",
"sql",
"rows",
"database"
] |
Is there a recommended command for "hg bisect --command"? | 2,511,704 | <p>I have an emergent bug that I've got to track down tomorrow. I know a previous hg revision which was good so I'm thinking about using hg bisect.</p>
<p>However, I'm on Windows and don't want to get into DOS scripting.</p>
<p>Ideally, I'd be able to write a Python unit test and have hg bisect use that. This is my f... | 8 | 2010-03-24T21:56:12Z | 2,512,068 | <p>I think you can remove your <code>main()</code> function and use the following block to run the tests:</p>
<pre><code>if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The call to <code>unittest.main()</code> will run the tests it finds in this file and exit with an appropriate status code depending o... | 4 | 2010-03-24T23:03:05Z | [
"python",
"mercurial"
] |
Is there a recommended command for "hg bisect --command"? | 2,511,704 | <p>I have an emergent bug that I've got to track down tomorrow. I know a previous hg revision which was good so I'm thinking about using hg bisect.</p>
<p>However, I'm on Windows and don't want to get into DOS scripting.</p>
<p>Ideally, I'd be able to write a Python unit test and have hg bisect use that. This is my f... | 8 | 2010-03-24T21:56:12Z | 2,513,749 | <p>Thanks to all, especially to Will McCutchen.
The solution that worked best is below.</p>
<p>bisector.py</p>
<pre><code>#!/usr/bin/env python
import unittest
class TestCase(unittest.TestCase):
def test(self):
# Raise an assertion error to mark the revision as bad
pass
if '__main__' == __nam... | 10 | 2010-03-25T07:37:08Z | [
"python",
"mercurial"
] |
Is there a recommended command for "hg bisect --command"? | 2,511,704 | <p>I have an emergent bug that I've got to track down tomorrow. I know a previous hg revision which was good so I'm thinking about using hg bisect.</p>
<p>However, I'm on Windows and don't want to get into DOS scripting.</p>
<p>Ideally, I'd be able to write a Python unit test and have hg bisect use that. This is my f... | 8 | 2010-03-24T21:56:12Z | 2,990,430 | <p>In case you have some unix tools at your disposal, note that 'grep' sets its exit status in a useful way. So if your unit test prints "PASS" when it passes, you can do:</p>
<pre><code>hg bisect -c './unittest | grep PASS'
</code></pre>
<p>and that'll work pretty darn well.</p>
| 1 | 2010-06-07T14:38:23Z | [
"python",
"mercurial"
] |
Unknown syntax error | 2,511,722 | <p>Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead.</p>
<p>Please help :)</p>
<pre><code>def dealcards():
for i in range(len(cards)):
cards[i] = ''
for j in range(8):
cards[i] = ... | 0 | 2010-03-24T21:59:59Z | 2,511,734 | <p>Missing a close:</p>
<pre><code>cards[i] = cards[i].append(random.randint(0,9))
</code></pre>
| 1 | 2010-03-24T22:01:34Z | [
"python"
] |
Unknown syntax error | 2,511,722 | <p>Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead.</p>
<p>Please help :)</p>
<pre><code>def dealcards():
for i in range(len(cards)):
cards[i] = ''
for j in range(8):
cards[i] = ... | 0 | 2010-03-24T21:59:59Z | 2,511,739 | <pre><code>cards[i] = cards[i].append(random.randint(0,9)
^
</code></pre>
<p>Missing closing parenthesis. And the return statement on the next line is incorrectly indented.</p>
| 5 | 2010-03-24T22:01:58Z | [
"python"
] |
Unknown syntax error | 2,511,722 | <p>Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead.</p>
<p>Please help :)</p>
<pre><code>def dealcards():
for i in range(len(cards)):
cards[i] = ''
for j in range(8):
cards[i] = ... | 0 | 2010-03-24T21:59:59Z | 2,512,172 | <ul>
<li>Your <code>SyntaxError</code> is due to an unclosed paren after <code>cards[i] = cards[i].append(random.randint(0,9)</code></li>
<li>When you clear that up, you'll find you will get an <code>AttributeError</code> when you call this function. You set <code>cards[i]</code> to be a <code>str</code> object then tr... | 0 | 2010-03-24T23:24:15Z | [
"python"
] |
Bundle module with app on Google App Engine | 2,511,883 | <p>This may be a basic question but how can I include a module with my app. </p>
<p>I'm very new to python and what I want to do is to include this module <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">simplejson</a> with my app, but after downloading it I have no idea what to do next :( </p>
<p>Thi... | 0 | 2010-03-24T22:26:07Z | 2,511,947 | <p>Put the directory (or a link) into your deployment directory and <code>appcfg.py update</code> will send it along to the server. This is documented in the <a href="http://code.google.com/appengine/docs/python/runtime.html#Pure_Python" rel="nofollow">Python Runtime Environment</a> page.</p>
| 1 | 2010-03-24T22:36:48Z | [
"python",
"google-app-engine"
] |
Bundle module with app on Google App Engine | 2,511,883 | <p>This may be a basic question but how can I include a module with my app. </p>
<p>I'm very new to python and what I want to do is to include this module <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">simplejson</a> with my app, but after downloading it I have no idea what to do next :( </p>
<p>Thi... | 0 | 2010-03-24T22:26:07Z | 2,512,035 | <p>Put the <code>simplejson</code> directory (that is inside the <code>simplejson-2.1.0</code>) in your app.</p>
<p>Or, you could just use the <code>simplejson</code> lib that's bundled with the Django lib that's bundled with App Engine by doing the following import wherever you need it:</p>
<pre><code>from django.ut... | 3 | 2010-03-24T22:56:33Z | [
"python",
"google-app-engine"
] |
Numpy Matrix keeps giving me an Error, | 2,512,033 | <p>Okay this is werid, i keep getting the error, randomly.</p>
<pre><code>ValueError: matrix must be 2-dimensional
</code></pre>
<p>So i tracked it down, and cornered it to basically something like this:</p>
<pre><code>a_list = [[(1,100) for _ in range(32)] for _ in range(32)]
numpy.matrix(a_list)
</code></pre>
<p>... | 1 | 2010-03-24T22:56:26Z | 2,512,057 | <p>tuples have more than one value, so they are considered a dimension. So you're creating a 3d matrix.</p>
| 1 | 2010-03-24T23:00:39Z | [
"python",
"numpy"
] |
Numpy Matrix keeps giving me an Error, | 2,512,033 | <p>Okay this is werid, i keep getting the error, randomly.</p>
<pre><code>ValueError: matrix must be 2-dimensional
</code></pre>
<p>So i tracked it down, and cornered it to basically something like this:</p>
<pre><code>a_list = [[(1,100) for _ in range(32)] for _ in range(32)]
numpy.matrix(a_list)
</code></pre>
<p>... | 1 | 2010-03-24T22:56:26Z | 2,512,065 | <p>What are you trying to do? In numpy, a matrix is a 2-d array of <em>numbers</em>.</p>
<p>You can make a 32x32x2 "matrix" with <code>numpy.array(a_list)</code>.
You could also make a 32x32 array of tuples using numpy object arrays, but there is little that would be better for than the 32x32x2 case (since you can thi... | 0 | 2010-03-24T23:02:42Z | [
"python",
"numpy"
] |
Numpy Matrix keeps giving me an Error, | 2,512,033 | <p>Okay this is werid, i keep getting the error, randomly.</p>
<pre><code>ValueError: matrix must be 2-dimensional
</code></pre>
<p>So i tracked it down, and cornered it to basically something like this:</p>
<pre><code>a_list = [[(1,100) for _ in range(32)] for _ in range(32)]
numpy.matrix(a_list)
</code></pre>
<p>... | 1 | 2010-03-24T22:56:26Z | 2,512,120 | <p>The easiest way around this is to just use a <a href="http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93" rel="nofollow">numpy array</a>, instead of a <a href="http://www.scipy.org/Tentative_NumPy_Tutorial#head-926a6c9b68b752eed8a330636c41829e6358b1d3" rel="nofollow">numpy ma... | 2 | 2010-03-24T23:11:21Z | [
"python",
"numpy"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 2,512,309 | <p>When you try </p>
<pre><code>plt.savefig('myfilename.png')
</code></pre>
<p>instead of </p>
<pre><code>plt.show()
</code></pre>
<p>does that save the correct image named <code>myfilename.png</code> in the current path?</p>
| 5 | 2010-03-24T23:54:51Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 2,512,358 | <p>I can verify this on my end as well. To fix, here's what I did</p>
<pre><code>sudo port install py25-matplotlib +cairo+gtk2
sudo port install py26-matplotlib +cairo+gtk2
</code></pre>
<p>Also, we need to change the default backend to a GUI based one.</p>
<p>Edit the file <code>~/.matplotlib/matplotlibrc</code>, a... | 30 | 2010-03-25T00:12:07Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 4,877,902 | <p>just to add a note, </p>
<p>The matplotlibrc file was not present on my system and I had to to download a copy from the matplotlib website. Future users may have to do the same.</p>
| 3 | 2011-02-02T17:47:12Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 8,007,903 | <p>I only had python 2.5 and I did not want to install python 2.6 on my mac. So I used different procedure mentioned in the following link to solve this problem:</p>
<p><a href="http://www.gtkforums.com/viewtopic.php?f=3&t=54928" rel="nofollow">http://www.gtkforums.com/viewtopic.php?f=3&t=54928</a></p>
<p><st... | 1 | 2011-11-04T10:29:56Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 17,369,923 | <p>This is what worked for me:</p>
<pre><code>brew install pkg-config
brew link pkg-config
brew install pygtk
brew install freetype
brew install libpng
sudo ln -s /usr/local/Cellar/freetype/*/lib/pkgconfig/freetype2.pc /usr/local/lib/pkgconfig/freetype2.pc
git clone git@github.com:matplotlib/matplotlib.git
cd matplo... | 2 | 2013-06-28T16:57:13Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 32,082,076 | <p>This is what worked for me. I just changed the import of Matplotlib</p>
<pre><code>import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
</code></pre>
| 3 | 2015-08-18T20:30:57Z | [
"python",
"osx",
"matplotlib"
] |
Matplotlib not showing up in Mac OSX | 2,512,225 | <p>I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/unicode_minus.html">http://matplotlib.sourceforge.net/examples/api/unicode_minus.html</a></p>
<p>I ... | 34 | 2010-03-24T23:36:24Z | 35,383,308 | <p>I had the same problem, even I could see how a new application window was created and immediately disappeared. </p>
<p>Simple solution - just check if you have </p>
<pre><code>plt.show()
</code></pre>
<p>after the plot</p>
| 4 | 2016-02-13T17:56:04Z | [
"python",
"osx",
"matplotlib"
] |
Pylons/Routes Did url_for() change within templates? | 2,512,264 | <p>I'm getting an error:</p>
<pre><code>GenerationException: url_for could not generate URL. Called with args: () {}
</code></pre>
<p>from this line of a mako template:</p>
<pre><code><p>Your url is ${h.url_for()}</p>
</code></pre>
<p>Over in my helpers.py, I do have:</p>
<pre><code>from routes import ... | 2 | 2010-03-24T23:46:26Z | 2,512,346 | <p>I didn't know <code>url_for()</code> (no arguments) was ever legal, but if it was and this is what you're referring to as "url_current", I believe the <a href="http://wiki.pylonshq.com/pages/viewpage.action?pageId=11174779#What%27snewinPylons0.9.7%3F-%7B%7Burl%7D%7Dobject">new approach</a> is to use the <code>url</c... | 5 | 2010-03-25T00:08:07Z | [
"python",
"routes",
"pylons",
"mako"
] |
Distance by sea calculator, intermediate coordinates? | 2,512,322 | <p>How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.</p>
<p>Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coor... | 3 | 2010-03-24T23:59:27Z | 2,512,912 | <p>Pretty much you'll need to split the sea into pixels and do something like A*. You could optimize it a bit by coalescing contiguous pixels into larger areas, but if you keep everything squares it'll probably make the search easier. The search would no longer be Manhattan-style, but if you had large enough squares,... | 1 | 2010-03-25T03:31:25Z | [
"python",
"maps",
"distance",
"geo"
] |
Distance by sea calculator, intermediate coordinates? | 2,512,322 | <p>How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.</p>
<p>Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coor... | 3 | 2010-03-24T23:59:27Z | 2,534,944 | <p>Beware of the fact that maps can distort distances. For example, in a Mercator projections segments far away from the equator represent less actual distance than segments near the equator of equal length. If you just assign uniform cost to your pixels/squares/etc, you will end up with non-optimal routing and erroneo... | 2 | 2010-03-28T23:05:38Z | [
"python",
"maps",
"distance",
"geo"
] |
Distance by sea calculator, intermediate coordinates? | 2,512,322 | <p>How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.</p>
<p>Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coor... | 3 | 2010-03-24T23:59:27Z | 2,556,845 | <p>I reached a satisfactory solution. It is along the lines of what you suggested and what I had in mind initially but it took me a while to figure out the software and GIS concepts, I am a GIS newbie. If someone bumps into something similar again here's my setup: <a href="http://postgis.refractions.net/" rel="nofollow... | 1 | 2010-03-31T22:13:13Z | [
"python",
"maps",
"distance",
"geo"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 2,512,416 | <p>If the merged CSV is going to be used in Python then just use <a href="http://docs.python.org/library/glob.html" rel="nofollow"><code>glob</code></a> to get a list of the files to pass to <a href="http://docs.python.org/library/fileinput.html#fileinput.input" rel="nofollow"><code>fileinput.input()</code></a> via the... | 3 | 2010-03-25T00:35:19Z | [
"python",
"csv",
"merge"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 2,512,418 | <pre><code>fout=open("out.csv","a")
for num in range(1,201):
for line in open("sh"+str(num)+".csv"):
fout.write(line)
fout.close()
</code></pre>
| 9 | 2010-03-25T00:35:48Z | [
"python",
"csv",
"merge"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 2,512,425 | <p>It depends what you mean by "merging" -- do they have the same columns? Do they have headers? For example, if they all have the same columns, and no headers, simple concatenation is sufficient (open the destination file for writing, loop over the sources opening each for reading, use <a href="http://docs.python.or... | 9 | 2010-03-25T00:41:28Z | [
"python",
"csv",
"merge"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 2,512,437 | <p>You could import csv then loop through all the CSV files reading them into a list. Then write the list back out to disk.</p>
<pre><code>import csv
rows = []
for f in (file1, file2, ...):
reader = csv.reader(open("f", "rb"))
for row in reader:
rows.append(row)
writer = csv.writer(open("some.csv",... | 1 | 2010-03-25T00:44:58Z | [
"python",
"csv",
"merge"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 2,512,572 | <p>As ghostdog74 said, but this time with headers:</p>
<pre><code>fout=open("out.csv","a")
# first file:
for line in open("sh1.csv"):
fout.write(line)
# now the rest:
for num in range(2,201):
f = open("sh"+str(num)+".csv")
f.next() # skip the header
for line in f:
fout.write(line)
f.cl... | 34 | 2010-03-25T01:20:10Z | [
"python",
"csv",
"merge"
] |
how to merge 200 csv files in Python | 2,512,386 | <p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
| 22 | 2010-03-25T00:24:29Z | 5,876,058 | <p>Why can't you just <code>sed 1d sh*.csv > merged.csv</code>?</p>
<p>Sometimes you don't even have to use python!</p>
| 17 | 2011-05-03T21:41:01Z | [
"python",
"csv",
"merge"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.