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
Parse xml file while a tag is missing
1,991,840
<p>I try to parse an xml file. The text which is in tags is parsed successfully (or it seems so) but I want to output as the text which is not contained in some tags and the following program just ignores it.</p> <pre><code>from xml.etree.ElementTree import XMLTreeBuilder class HtmlLatex: # The ta...
0
2010-01-02T15:05:19Z
1,991,910
<p>Here's a pyparsing version - I hope the comments are sufficiently explanatory.</p> <pre><code>src = """&lt;p&gt;&lt;i&gt;p&lt;/i&gt;&lt;sub&gt;0&lt;/sub&gt; = (&lt;i&gt;m&lt;/i&gt;&lt;sup&gt;3&lt;/sup&gt;+(2&lt;i&gt;l&lt;/i&gt;&lt;sub&gt;2&lt;/sub&gt;+&lt;i&gt;l&lt;/i&gt;&lt;sub&gt;1&lt;/sub&gt;) """ \ """&lt...
2
2010-01-02T15:32:02Z
[ "python", "html", "xml", "parsing" ]
Recompile Vim for pythoncomplete#Complete on modules *other* than standard library?
1,991,865
<p>I like using <code>pythoncomplete#Complete</code> for <a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="nofollow">Vim</a> <code>omnicompletion</code>, but it doesn't work for Python modules other than the standard library. </p> <p>Is there a way to re-compile Vim so that this will work on non-standa...
3
2010-01-02T15:15:28Z
1,992,773
<p>Have you tried setting PYTHONPATH prior to starting Vim?</p> <p>You can also modify the path from inside Vim, by doing:</p> <pre><code>:python import sys :python print sys.path :python sys.path.append(...) ... etc </code></pre>
1
2010-01-02T20:41:34Z
[ "python", "vim" ]
Optimize .png images with PIL
1,991,929
<p>All I need is to create a .png image with transparent background, draw some text in black on it and save it using <code>img.save('target.png', option='optimize')</code></p> <p>It looks like PIL saves .png images in 32-bit mode automatically. Can I reduce the color depth while not making the output images look much ...
5
2010-01-02T15:44:01Z
1,991,949
<p>Hey jack, check <a href="http://stackoverflow.com/questions/1521058/is-it-possible-to-reduce-an-images-depth-using-pil">this</a> answered question about PIL color depth. :)</p>
2
2010-01-02T15:51:59Z
[ "python", "image", "optimization", "png", "python-imaging-library" ]
SQL to calculate the Tanimoto Coefficient of several vectors
1,992,158
<p>I think it's easier to explain my problem with an example.</p> <p>I have one table with ingredients for recipes and I have implemented a function to calculate the <a href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29" rel="nofollow">Tanimoto coefficient</a> betw...
4
2010-01-02T17:15:14Z
1,992,263
<p>Why aren't you simply fetching all recipes into memory and then computing Tanimoto coefficients in memory? </p> <p>It's simpler and it's much, much faster.</p>
3
2010-01-02T18:00:57Z
[ "python", "sql", "collaborative-filtering" ]
SQL to calculate the Tanimoto Coefficient of several vectors
1,992,158
<p>I think it's easier to explain my problem with an example.</p> <p>I have one table with ingredients for recipes and I have implemented a function to calculate the <a href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29" rel="nofollow">Tanimoto coefficient</a> betw...
4
2010-01-02T17:15:14Z
1,992,305
<p>I think this will cut you down to 2 selects per pair for the intersection, and 4 queries per pair total. You can't get away from O(N^2) since you are trying all pairs -- N*(N-1)/2 is simply how many pairs there are.</p> <pre><code>def n_recipes_intersection(self, ingredient_a, ingredient_b): cursor = self._cur ...
0
2010-01-02T18:15:37Z
[ "python", "sql", "collaborative-filtering" ]
SQL to calculate the Tanimoto Coefficient of several vectors
1,992,158
<p>I think it's easier to explain my problem with an example.</p> <p>I have one table with ingredients for recipes and I have implemented a function to calculate the <a href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29" rel="nofollow">Tanimoto coefficient</a> betw...
4
2010-01-02T17:15:14Z
1,992,341
<p>If you have 1000 ingredients, 1000 queries will suffice to map each ingredient to a set of recipes in memory. If (say) an ingredient is typically part of about 100 recipes, each set will take a few KB, so the whole dictionary will take just a few MB -- absolutely no problem to hold the whole thing in memory (and st...
1
2010-01-02T18:26:16Z
[ "python", "sql", "collaborative-filtering" ]
SQL to calculate the Tanimoto Coefficient of several vectors
1,992,158
<p>I think it's easier to explain my problem with an example.</p> <p>I have one table with ingredients for recipes and I have implemented a function to calculate the <a href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29" rel="nofollow">Tanimoto coefficient</a> betw...
4
2010-01-02T17:15:14Z
1,992,578
<p>If anybody is interested, this is the code that I came up with after Alex's and S.Lotts's suggestions. Thank you guys.</p> <pre><code>def __init__(self): self._connection=sqlite.connect('database.db') self._counts = None self._intersections = {} def inc_intersections(self, ingredients): ingredients...
1
2010-01-02T19:37:09Z
[ "python", "sql", "collaborative-filtering" ]
Python soap using soaplib (server) and suds (client)
1,992,239
<p>This question is related to: <a href="http://stackoverflow.com/questions/1751027/python-soap-server-client">http://stackoverflow.com/questions/1751027/python-soap-server-client</a></p> <p>In the case of soap with python, there are recommendation to use soaplib (http://wiki.github.com/jkp/soaplib) as soap server and...
11
2010-01-02T17:51:55Z
1,993,600
<p>try to import primitives into your class:</p> <pre><code>class HelloWorldService(SimpleWSGISoapApp): from soaplib.serializers.primitive import String, Integer, Arraycode @soapmethod(String,Integer,_returns=Array(String)) </code></pre>
0
2010-01-03T01:32:03Z
[ "python", "soap", "suds" ]
Python soap using soaplib (server) and suds (client)
1,992,239
<p>This question is related to: <a href="http://stackoverflow.com/questions/1751027/python-soap-server-client">http://stackoverflow.com/questions/1751027/python-soap-server-client</a></p> <p>In the case of soap with python, there are recommendation to use soaplib (http://wiki.github.com/jkp/soaplib) as soap server and...
11
2010-01-02T17:51:55Z
2,625,359
<p>this bug is fixed if you get the latest sources from the trunk, see <a href="https://github.com/soaplib/soaplib/pull/12" rel="nofollow">https://github.com/soaplib/soaplib/pull/12</a> for details</p>
1
2010-04-12T20:52:54Z
[ "python", "soap", "suds" ]
How do I open all files of a certain type in Python and process them?
1,992,657
<p>I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.</p> <p>In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and...
4
2010-01-02T20:03:26Z
1,992,680
<p>And I've answered my own question again... I imported the os and glob modules to nab a path. </p>
0
2010-01-02T20:11:18Z
[ "python" ]
How do I open all files of a certain type in Python and process them?
1,992,657
<p>I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.</p> <p>In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and...
4
2010-01-02T20:03:26Z
1,992,684
<p>The best way is probably to use the shell's globbing ability, or alternatively the glob module of Python.</p> <h2>Shell (Linux, Unix)</h2> <p>Shell:</p> <pre> python myapp.py folder/*.csv </pre> <p>myapp.py:</p> <pre><code>import sys for filename in sys.argv[1:]: with open(filename) as f: # do some...
7
2010-01-02T20:12:56Z
[ "python" ]
How do I open all files of a certain type in Python and process them?
1,992,657
<p>I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.</p> <p>In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and...
4
2010-01-02T20:03:26Z
1,992,712
<p>A few suggestions:</p> <ul> <li><p>You could keep the header indices for Keyword, First Name, and Last Name in a map instead of using separate variables. This would make it easier to modify the script later on.</p></li> <li><p>You could use the list index() function instead of looping over the headers, e.g.:<pre> i...
1
2010-01-02T20:24:01Z
[ "python" ]
How do I open all files of a certain type in Python and process them?
1,992,657
<p>I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.</p> <p>In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and...
4
2010-01-02T20:03:26Z
1,992,853
<p>The "get all the CSV files" part of the question has been answered several times (including by the OP), but the "get the right <em>named</em> columns" hasn't yet: <a href="http://docs.python.org/library/csv.html?highlight=dictreader#csv.DictReader" rel="nofollow">csv.DictReader</a> makes it trivial -- the "process o...
4
2010-01-02T21:09:31Z
[ "python" ]
How do I open all files of a certain type in Python and process them?
1,992,657
<p>I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.</p> <p>In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and...
4
2010-01-02T20:03:26Z
1,993,233
<p>I think the best way to process a bunch of files in a directory is with os.walk (documented in the Python os module docs <a href="http://docs.python.org/library/os.html#file-descriptor-operations" rel="nofollow">here</a>.</p> <p>Here is an answer I wrote to another Python question, which includes working tested Pyt...
1
2010-01-02T23:19:25Z
[ "python" ]
Python Working with lists based on indexes
1,992,659
<p>I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE column, N in that column indicates that in that r...
0
2010-01-02T20:03:33Z
1,992,787
<p>I would split this into two tasks.</p> <p>First, divide <code>thedata</code> into groups of <code>LTYPE=N</code> rows and the <code>LTYPE=A</code> rows that follow it.</p> <pre><code>def group_name_and_attributes(thedata): group = [] for row in thedata: if row['LTYPE'] == 'N': if group:...
1
2010-01-02T20:46:56Z
[ "python", "list", "variable-assignment" ]
Python Working with lists based on indexes
1,992,659
<p>I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE column, N in that column indicates that in that r...
0
2010-01-02T20:03:33Z
1,992,807
<p>I suggest a different, index-free approach based on <a href="http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p> <pre><code>import itertools, operator data = [ {'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'}, {'LTYPE': 'A', 'RI...
2
2010-01-02T20:53:47Z
[ "python", "list", "variable-assignment" ]
python qt raise syntax error
1,992,739
<p>I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings.</p> <pre><code>#!/usr/bin/python # simple.py import sys ...
2
2010-01-02T20:32:27Z
1,992,783
<p>"raise" is a keyword (reserved word) in Python. So, you can't use it. And PyQt4 certainly doesn't use it as you think, because, well, it's a keyword, so no extension can. It's like you can't use "from" for a variable name (pet peeve: Python doesn't have variables, but I digress...)</p> <p>As a hint, it's also h...
8
2010-01-02T20:44:38Z
[ "python", "qt", "qt4", "pyqt4" ]
Use raw SQL to create tables in SQLAlchemy, after which use ORM
1,992,815
<p>Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used to create tables (I've spent too long mired in SAS and SQL to lear...
4
2010-01-02T20:56:01Z
1,992,825
<p>Yes.</p> <pre><code>connection.execute(""" CREATE TABLE ... """) </code></pre> <p>You can then reflect all tables: <code>MetaData(dsn, reflect=True)</code> or <code>metadata_instance.reflect()</code>.</p>
3
2010-01-02T20:59:09Z
[ "python", "database-design", "sqlalchemy" ]
Use raw SQL to create tables in SQLAlchemy, after which use ORM
1,992,815
<p>Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used to create tables (I've spent too long mired in SAS and SQL to lear...
4
2010-01-02T20:56:01Z
1,994,300
<p>You can use the <code>autoload</code> paramater to the <code>Table</code> constructor to have it automatically load up the table definitions. There are some examples <a href="http://www.sqlalchemy.org/docs/05/metadata.html" rel="nofollow">here</a>.</p>
1
2010-01-03T08:15:20Z
[ "python", "database-design", "sqlalchemy" ]
upload file via python script
1,993,060
<p>I want to upload a file from my computer to a filehoster like hotfile.com via a python script. Because Hotfile is only offering a webbased-upload service (no ftp) I need python first to login with my username and password and after that to upload the file. When the Filetransfer is over, I need the Download and Delet...
1
2010-01-02T22:14:33Z
1,993,075
<p>For a similar task, I've previously used <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>, with some quite success.<br> Note: although I was not uploading files, its documentation <a href="http://wwwsearch.sourceforge.net/ClientForm/" rel="nofollow">says</a> that it is capable to ha...
1
2010-01-02T22:18:22Z
[ "python", "automation", "login", "file-upload" ]
upload file via python script
1,993,060
<p>I want to upload a file from my computer to a filehoster like hotfile.com via a python script. Because Hotfile is only offering a webbased-upload service (no ftp) I need python first to login with my username and password and after that to upload the file. When the Filetransfer is over, I need the Download and Delet...
1
2010-01-02T22:14:33Z
1,993,139
<p>You mention they do not offer FTP, but I went to their site and found the following:</p> <blockquote> <p>How to upload with FTP? ftp.hotfile.com user: your hotfile username pass: your hotfile password You can upload and make folders, but cant rename,move files</p> </blockquote> <p>Try it. If it works, us...
0
2010-01-02T22:43:49Z
[ "python", "automation", "login", "file-upload" ]
upload file via python script
1,993,060
<p>I want to upload a file from my computer to a filehoster like hotfile.com via a python script. Because Hotfile is only offering a webbased-upload service (no ftp) I need python first to login with my username and password and after that to upload the file. When the Filetransfer is over, I need the Download and Delet...
1
2010-01-02T22:14:33Z
1,993,214
<p>Okay, you want to use Python to upload a file using HTTP "put". You will need to use a Python library that lets you do HTML stuff; a good choice might be <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a> which is included with Python.</p> <p>A Google search for "Python HTTP put" foun...
1
2010-01-02T23:12:51Z
[ "python", "automation", "login", "file-upload" ]
Compare attributes of a Django Queryset in a template using the `in` Operator
1,993,064
<p>I'm trying to use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#in-operator" rel="nofollow"><code>in</code> operator</a> to determine if a template variable on the current page is also a foreign key in another model.</p> <p>The model is like so:</p> <pre><code>class WishlistItem(models....
1
2010-01-02T22:16:17Z
1,993,111
<p>I think what you are refering to should go into the view, more than the template.<br> Of course, you could create some templatetag, however Django's approach to templates is to maintain them as dumb as possible, and move all logic to the view. </p> <p>On the other hand, moving the logic in the view, and then passi...
0
2010-01-02T22:31:26Z
[ "python", "django" ]
Compare attributes of a Django Queryset in a template using the `in` Operator
1,993,064
<p>I'm trying to use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#in-operator" rel="nofollow"><code>in</code> operator</a> to determine if a template variable on the current page is also a foreign key in another model.</p> <p>The model is like so:</p> <pre><code>class WishlistItem(models....
1
2010-01-02T22:16:17Z
1,993,119
<p><code>wishlist_items</code> is not a queryset - it's a manager. <code>wishlist_items.all</code> IS a queryset, but obviously it is a queryset of <code>WishlistItem</code> objects, not <code>Issue</code> objects. What I would do is handle this logic in the view... something like:</p> <pre><code>user_has_issue = issu...
0
2010-01-02T22:35:49Z
[ "python", "django" ]
Compare attributes of a Django Queryset in a template using the `in` Operator
1,993,064
<p>I'm trying to use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#in-operator" rel="nofollow"><code>in</code> operator</a> to determine if a template variable on the current page is also a foreign key in another model.</p> <p>The model is like so:</p> <pre><code>class WishlistItem(models....
1
2010-01-02T22:16:17Z
1,993,122
<p>It seems that there's a relationship between <code>User</code> and wishlist issues that you ought to express as a <code>ManyToManyField</code> on the <code>User</code>. If there is extra metadata about the relationship that you need to record in a <code>WishlistItem</code>, then use <code>through=WishlistItem</code>...
1
2010-01-02T22:36:11Z
[ "python", "django" ]
Compare attributes of a Django Queryset in a template using the `in` Operator
1,993,064
<p>I'm trying to use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#in-operator" rel="nofollow"><code>in</code> operator</a> to determine if a template variable on the current page is also a foreign key in another model.</p> <p>The model is like so:</p> <pre><code>class WishlistItem(models....
1
2010-01-02T22:16:17Z
1,993,130
<p>If I understood correctly, instead of writing a templatetag for it you can pass that as a parameter of the view.</p> <pre><code>def myView(request): return render_to_response('template.html', {'query': queryToCheckIfIssueInWishList}, RequestContext(request)) </code></pre>
0
2010-01-02T22:38:21Z
[ "python", "django" ]
Compare attributes of a Django Queryset in a template using the `in` Operator
1,993,064
<p>I'm trying to use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#in-operator" rel="nofollow"><code>in</code> operator</a> to determine if a template variable on the current page is also a foreign key in another model.</p> <p>The model is like so:</p> <pre><code>class WishlistItem(models....
1
2010-01-02T22:16:17Z
2,046,477
<p>I ended up solving this by writing a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters" rel="nofollow">template filter</a>:</p> <pre><code>@register.filter def in_list(obj, arg): "Is the issue in the list?" return obj in (item.issue for item in arg) </...
2
2010-01-12T03:15:06Z
[ "python", "django" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,093
<p>Does Python have any sort of asynchronous IO functionality? That would be the preferred answer IMO - spawning an extra thread for each outbound connection isn't as neat as having a single thread which is effectively event-driven.</p>
3
2010-01-02T22:23:24Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,094
<p>Make sure your threads get destroyed properly after they've been used or use a threadpool, although per what I see they're not that effective in Python</p> <p>see here:</p> <p><a href="http://code.activestate.com/recipes/203871/" rel="nofollow">http://code.activestate.com/recipes/203871/</a></p>
1
2010-01-02T22:24:57Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,095
<p>Using the <a href="http://docs.python.org/library/select.html" rel="nofollow"><code>select</code></a> module or a similar library would most probably be a more efficient solution, but that would require bigger architectural changes.</p> <p>If you just want to limit the number of threads, a global counter should be ...
1
2010-01-02T22:25:31Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,097
<p>You want to do non-blocking I/O with the <a href="http://docs.python.org/library/select.html" rel="nofollow">select module</a>.</p> <p>There are a couple of different specific techniques. select.select should work for every major platform. There are other variations that are more efficient (and could matter if yo...
5
2010-01-02T22:25:53Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,101
<p>Using different processes, and pipes to transfer data. Using threads in python is pretty lame. From what I heard, they don't actually run in parallel, even if you have a multi-core processor... But maybe it was fixed in python3.</p>
2
2010-01-02T22:27:46Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,105
<p>I've run into this situation before. Just make a pool of Tasks, and spawn a fixed number of threads that run an endless loop which grabs a Task from the pool, run it, and repeat. Essentially you're implementing your own thread abstraction and using the OS threads to implement it.</p> <p>This does have drawbacks, ...
4
2010-01-02T22:28:55Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,107
<p>Be careful to minimize the default thread stack size. At least on Linux, the default limit puts severe restrictions on the number of created threads. Linux allocates a chunk of the process virtual address space to the stack (usually 10MB). 300 threads x 10MB stack allocation = 3GB of virtual address space dedicated ...
1
2010-01-02T22:29:09Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,114
<blockquote> <p>My solution is: A global variable that gets incremented when a thread spawns and decrements when a thread finishes. The function which spawns the threads monitors the variable so that the limit is not reached. </p> </blockquote> <p>The standard way is to have each thread get next tasks in a loop inst...
2
2010-01-02T22:33:04Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,189
<p>A counting semaphore should do the trick.</p> <pre><code>from socket import * from threading import * maxthreads = 1000 threads_sem = Semaphore(maxthreads) class MyThread(Thread): def __init__(self, conn, addr): Thread.__init__(self) self.conn = conn self.addr = addr def run(self):...
2
2010-01-02T23:01:42Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,299
<p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> is a perfect fit for this problem. See <a href="http://twistedmatrix.com/documents/current/core/howto/clients.html" rel="nofollow">http://twistedmatrix.com/documents/current/core/howto/clients.html</a> for a tutorial on writing a client.</p> <p>If ...
1
2010-01-02T23:37:57Z
[ "python", "multithreading" ]
A programming strategy to bypass the os thread limit?
1,993,079
<p>The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. <br>My solution is: A global variable that gets incremented when a thread spawns and decr...
3
2010-01-02T22:19:10Z
1,993,311
<p>As mentioned in another thread, why do you spawn off a new thread for each single operation? This is a classical producer - consumer problem, isn't it? Depending a bit on how you look at it, the proxy checkers might be comsumers or producers.</p> <p>Anyway, the solution is to make a "queue" of "tasks" to process, a...
1
2010-01-02T23:42:29Z
[ "python", "multithreading" ]
How to reset Python interpreter to a 'safe' state?
1,993,238
<p>I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything except I have a bunch of PyObject * references that ...
1
2010-01-02T23:21:42Z
1,996,024
<p>Er, trying to "recover" from a segfault or access violation is quite dangerous. There is a reason you get these in the first place, and it's that your program has tried to do something which it shouldn't have tried to do; therefore it has hit a bug or an unforeseen condition.</p> <p>There is no provision in the Pyt...
2
2010-01-03T19:35:54Z
[ "python", "function", "recover" ]
SocketServer client side socket error during third send() on winXP
1,993,243
<p>I'm struggling with following error:</p> <blockquote> <p>"socket.error: [10053] 'Software caused connection abort'"</p> <p>Traceback (most recent call last): ... self.send(json.dumps([0x02, subItems])+"\n") ... sent = self.handler.send(data) socket.error: [Errno 10053]</p> </blockquote> <p>I ...
0
2010-01-02T23:22:21Z
1,993,319
<p>If this, as you report, is really how your main server code ends...:</p> <pre><code>server_thread.setDaemon(True) server_thread.start() </code></pre> <p>then your code is saying: let <code>server_thread</code> just die when the main thread dies, let <code>server_thread</code> start, and now let the main thread die...
0
2010-01-02T23:44:38Z
[ "python", "sockets" ]
python hebrew input\filesytem format
1,993,402
<pre><code>import os import pprint import subprocess def Convert (dir): curDir = dir pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives problemFiles = [] #A list of files that failed conversion # for item in os.listdir(curDir): if item.upper().endswith('.M4...
3
2010-01-03T00:09:24Z
2,001,855
<p>Just use <code>os.listdir(unicode(str))</code> instead of <code>os.listdir(str)</code> in order to be sure that str is Unicode, otherwise it will just fail.</p> <p>Same problem can be found on <a href="http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames">this question</a></p>
0
2010-01-04T20:05:28Z
[ "python", "unicode", "hebrew" ]
Possible to send variables to the index page in CherryPy?
1,993,565
<p>For instance I want to visit <a href="http://localhost:8080/?var=val" rel="nofollow">http://localhost:8080/?var=val</a> or similar with POST, but I get a 500 server error:</p> <blockquote> <p>500 Internal Server Error</p> <p>The server encountered an unexpected condition which prevented it from fulfilling th...
1
2010-01-03T01:11:14Z
1,993,588
<p>It is definitely possible.</p> <p>Here is an example (adapted from <a href="http://www.cherrypy.org/wiki/CherryPyTutorial" rel="nofollow">the CherryPy tutorial</a>):</p> <pre><code>&lt;form action="indexPostHandler" method="post"&gt; &lt;p&gt;Enter a value:&lt;/p&gt; &lt;input type="text" name="val" value=...
1
2010-01-03T01:25:21Z
[ "python", "cherrypy" ]
translate this block of C physics code to python
1,993,580
<p>I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!</p> <pre><code>for(i=0; i&lt;n; i++) { /* Forea...
-2
2010-01-03T01:22:02Z
1,993,590
<p>Treat this as an ideal opportunity to learn some C, the syntax is not <em>so</em> unlike Python.</p> <p>It will serve you well</p>
7
2010-01-03T01:25:55Z
[ "python", "c" ]
translate this block of C physics code to python
1,993,580
<p>I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!</p> <pre><code>for(i=0; i&lt;n; i++) { /* Forea...
-2
2010-01-03T01:22:02Z
1,993,595
<p>Honestly, except for the loops this <em>is</em> already very close to python .. <pre> for(j=0; j &lt; n; ++j) </pre> simply maintains the loop counter j, which is incremented after each loop iteration. The loop runs for all <pre>0 &lt;= j &lt; n</pre>. Good luck.</p>
1
2010-01-03T01:28:36Z
[ "python", "c" ]
translate this block of C physics code to python
1,993,580
<p>I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!</p> <pre><code>for(i=0; i&lt;n; i++) { /* Forea...
-2
2010-01-03T01:22:02Z
1,993,596
<p>Here's a literal translation</p> <p>(<strong>Edit</strong>: <em>was</em> a literal translation but there are some anomalies in the original C code which @hughdbrown pointed out in comments -- looks like you're trying to study this subject from code so utterly broken it wouldn't even compile, which seems very unwise...
2
2010-01-03T01:29:02Z
[ "python", "c" ]
translate this block of C physics code to python
1,993,580
<p>I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!</p> <pre><code>for(i=0; i&lt;n; i++) { /* Forea...
-2
2010-01-03T01:22:02Z
1,993,698
<p>Incidentally this code is <strong><em>extremely</em></strong> buggy, assuming the intent is to numerically integrate the n-body problem.</p> <ul> <li><p>The loop to calculate the force doesn't correctly handle the case i == j, resulting in a very large (depending on the size of eps) spurious error being added to ea...
1
2010-01-03T02:09:42Z
[ "python", "c" ]
How can I force cherrypy to accept a variable number of GET parameters?
1,993,604
<p>for instance, say I have my cherrypy index module set up like this</p> <pre><code>&gt;&gt;&gt; import cherrypy &gt;&gt;&gt; class test: def index(self, var = None): if var: print var else: print "nothing" index.exposed = True &gt;&gt;&gt; cher...
12
2010-01-03T01:33:47Z
1,993,610
<p>For complete generality, change</p> <pre><code> def index(self, var = None): </code></pre> <p>to</p> <pre><code> def index(self, *vars): </code></pre> <p><code>vars</code> will be bound to a tuple, which is empty if no arguments were passed, has one item if one argument was passed, two if two, and so forth...
1
2010-01-03T01:38:15Z
[ "python", "cherrypy" ]
How can I force cherrypy to accept a variable number of GET parameters?
1,993,604
<p>for instance, say I have my cherrypy index module set up like this</p> <pre><code>&gt;&gt;&gt; import cherrypy &gt;&gt;&gt; class test: def index(self, var = None): if var: print var else: print "nothing" index.exposed = True &gt;&gt;&gt; cher...
12
2010-01-03T01:33:47Z
1,993,801
<pre><code>def index(self, var=None, **params): </code></pre> <p>or</p> <pre><code>def index(self, **params): </code></pre> <p>'var2' will be a key in the params dict. In the second example, so will 'var'.</p> <p>Note the other answers which reference the *args syntax won't work in this case, because CherryPy pass...
28
2010-01-03T03:00:23Z
[ "python", "cherrypy" ]
if my condition false how to do a statement one time only in python
1,993,637
<p>is there any way to make this logic:</p> <p>I need to make a statement one time only if the condition is false as below:</p> <pre><code>while 1: statement1 statement2 if condition: --condition is true here statement3 else --condition is false here ...
0
2010-01-03T01:49:44Z
1,993,644
<p>Couldn't you just put a <code>break</code> statement after <code>statement3</code>? That would mean that it would run once and then the <code>while</code> loop would exit.</p>
0
2010-01-03T01:54:04Z
[ "python" ]
if my condition false how to do a statement one time only in python
1,993,637
<p>is there any way to make this logic:</p> <p>I need to make a statement one time only if the condition is false as below:</p> <pre><code>while 1: statement1 statement2 if condition: --condition is true here statement3 else --condition is false here ...
0
2010-01-03T01:49:44Z
1,993,645
<p>add a boolean variable:</p> <pre><code>neverdone = True while 1: statement1 statement2 if condition: statement3 elif neverdone: neverdone = False statement3 if anothercondition: break </code></pre>
3
2010-01-03T01:54:17Z
[ "python" ]
if my condition false how to do a statement one time only in python
1,993,637
<p>is there any way to make this logic:</p> <p>I need to make a statement one time only if the condition is false as below:</p> <pre><code>while 1: statement1 statement2 if condition: --condition is true here statement3 else --condition is false here ...
0
2010-01-03T01:49:44Z
1,993,659
<p>you can use a flag, or write something like:</p> <pre><code>while 1: state1() state2() state3() if not condition: state3 = lambda : None if another_condition: break </code></pre> <p>Thise will destroy the state3 when the condition is false.</p>
0
2010-01-03T01:58:10Z
[ "python" ]
if my condition false how to do a statement one time only in python
1,993,637
<p>is there any way to make this logic:</p> <p>I need to make a statement one time only if the condition is false as below:</p> <pre><code>while 1: statement1 statement2 if condition: --condition is true here statement3 else --condition is false here ...
0
2010-01-03T01:49:44Z
1,993,669
<p>If you want to do something once don't put it in a infinite loop (duh)</p> <pre><code>def dostuff(): statement1 statement2 if condition: statement3 dostuff() if not contition: statement3 while True: dostuff() if another condition: break </code></pre>
0
2010-01-03T02:00:19Z
[ "python" ]
Where is os.environ initialized?
1,993,643
<p>Using this code, many keys are output, but I expected no output:</p> <pre><code>import os for i in os.environ: print i </code></pre> <p>This is the code from os.py:</p> <pre><code>try: environ except NameError: environ = {} </code></pre> <p><strong>Where does os.environ get its values from?</strong...
0
2010-01-03T01:53:59Z
1,993,664
<p>The <code>os</code> module starts by importing all names from a platform-specific submodule (such as <code>_nt</code> or <code>_posix</code>) then does a little normalization. Clearly the <code>environ</code> name (standing for the system environment) <strong>was</strong> defined by the platform-specific submodule ...
7
2010-01-03T01:59:26Z
[ "python", "initialization", "std" ]
Where is os.environ initialized?
1,993,643
<p>Using this code, many keys are output, but I expected no output:</p> <pre><code>import os for i in os.environ: print i </code></pre> <p>This is the code from os.py:</p> <pre><code>try: environ except NameError: environ = {} </code></pre> <p><strong>Where does os.environ get its values from?</strong...
0
2010-01-03T01:53:59Z
1,993,847
<p>The quoted code from <code>os.py</code> is a backstop. It's saying, if no-one has yet defined an <code>environ</code> variable, create one, with an empty dictionary as a value.</p> <p>But <code>environ</code> does exist, because it has been imported by this further up on line 58:</p> <pre><code>from nt import * </...
3
2010-01-03T03:23:21Z
[ "python", "initialization", "std" ]
PNG optimisation tools
1,993,678
<p>A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...</p> <p>I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre...
10
2010-01-03T02:03:28Z
1,993,706
<p>As long as your PHP is compiled with GD2 support (quite common nowadays):</p> <pre><code>&lt;?php $image = imagecreatefromstring(file_get_contents('/path/to/image.original.png')); imagepng($image, '/path/to/image.smushed.png', 9); </code></pre> <p>This will read in any image format GD2 understands (not just PNG) a...
3
2010-01-03T02:12:08Z
[ "php", "python", "optimization", "png" ]
PNG optimisation tools
1,993,678
<p>A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...</p> <p>I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre...
10
2010-01-03T02:03:28Z
1,993,712
<p>Have you heard of PNGCrush? You could check out the source, part of <a href="http://sourceforge.net/projects/pmt/" rel="nofollow">PNG and MNG Tools at SourceForge</a>, and transcribe or wrap it in Python.</p>
2
2010-01-03T02:12:54Z
[ "php", "python", "optimization", "png" ]
PNG optimisation tools
1,993,678
<p>A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...</p> <p>I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre...
10
2010-01-03T02:03:28Z
2,000,540
<p>I would question the wisdom of throwing away other chunks (like gAMA and iCCP), but if that's what you want to do it's fairly easy to use <a href="http://pypng.googlecode.com/" rel="nofollow">PyPNG</a> to remove chunks:</p> <pre><code>#!/usr/bin/env python import png import sys input=sys.stdin out=sys.stdout def ...
2
2010-01-04T16:23:47Z
[ "php", "python", "optimization", "png" ]
PNG optimisation tools
1,993,678
<p>A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...</p> <p>I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre...
10
2010-01-03T02:03:28Z
2,014,051
<p>Execute with PHP this command line tools</p> <pre><code> pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -l 9 -max -reduce -m 0 -q IMAGE optipng -o7 -q pngout.png pngout pngout.png -q -y -k0 -s0 advpng -z -4 pngout.png &gt; /dev/null </code></pre> <ul> <li><a href="http://pmt.sourceforge.net/pngcrus...
13
2010-01-06T15:37:40Z
[ "php", "python", "optimization", "png" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,993,703
<p><a href="http://docs.python.org/library/collections.html#defaultdict-examples" rel="nofollow">defaultdict</a> makes this easy:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2] &gt;&gt;&gt; seqDic = defaultdict(int) &gt;&gt;&gt; for v in seq: ... ...
2
2010-01-03T02:11:33Z
[ "python" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,993,710
<p>I'm not really sure what you try to do .. count how often each number appears?</p> <pre><code>#arbitrary sequence of numbers seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2] #dictionary counting number of occurances seqDic = {} ### what you want to do, spelled out for number in seq: if number in seqDic: # we had the numb...
2
2010-01-03T02:12:18Z
[ "python" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,993,713
<p>How about this:</p> <pre><code>#arbitrary sequence of numbers seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2] #dictionary counting number of occurances seqDic = { } for v in seq: if v in seqDic: seqDic[v] += 1 else: seqDic[v] = 1 dv = seqDic.keys() print "orig:", seq print "new: ", dv print seqDic ...
1
2010-01-03T02:13:23Z
[ "python" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,993,716
<p>Or, if you use Python3, you can use <code>collections.Counter</code>, which is essentially a <code>dict</code>, albeit subclassed.</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2] &gt;&gt;&gt; Counter(seq) Counter({2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1...
0
2010-01-03T02:14:26Z
[ "python" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,993,718
<p><code>defaultdict</code> is not <code>dict</code> (it's a subclass, and may do too much of the work for you to help you learn via this exercise), so here's a simple way to do it with plain <code>dict</code>:</p> <pre><code>dv = list() # arbitrary sequence of numbers seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2] # dictionar...
2
2010-01-03T02:17:46Z
[ "python" ]
Learning Python and using dictionaries
1,993,689
<p>I'm working through exercises in <a href="http://homepage.mac.com/s_lott/books/python/html/p02/p02c05_maps.html" rel="nofollow">Building Skills in Python</a>, which to my knowledge don't have any published solutions.</p> <p>In any case, I'm attempting to have a dictionary count the number of occurrences of a certai...
3
2010-01-03T02:07:04Z
1,994,180
<pre><code>for v in seq: try: seqDic[v] += 1 except KeyError: seqDic[v] = 1 </code></pre> <p>That's the way I've always done the inner loop of things like this.</p> <p>Apart from anything else, it's significantly faster than testing membership before working on the element, so if you have a fe...
0
2010-01-03T06:31:55Z
[ "python" ]
Expanding tuples into arguments
1,993,727
<p>Is there a way to expand a Python tuple into a function - as actual parameters?</p> <p>For example, here <code>expand()</code> does the magic:</p> <pre><code>tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") <...
163
2010-01-03T02:22:49Z
1,993,732
<p><code>myfun(*tuple)</code> does <strong>exactly</strong> what you request.</p> <p>Side issue: <strong>don't</strong> use as your identifiers builtin type names such as <code>tuple</code>, <code>list</code>, <code>file</code>, <code>set</code>, and so forth -- it's horrible practice and it <em>will</em> come back an...
302
2010-01-03T02:24:05Z
[ "python", "tuples", "argument-passing" ]
Expanding tuples into arguments
1,993,727
<p>Is there a way to expand a Python tuple into a function - as actual parameters?</p> <p>For example, here <code>expand()</code> does the magic:</p> <pre><code>tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") <...
163
2010-01-03T02:22:49Z
1,993,740
<p>Take a look at <a href="http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions">the Python tutorial</a> section 4.7.3 and 4.7.4. It talks about passing tuples os arguments.</p> <p>I would also consider using named parameters (and passing a dictionary) over a tuple and passing a sequence. I find...
10
2010-01-03T02:28:28Z
[ "python", "tuples", "argument-passing" ]
Expanding tuples into arguments
1,993,727
<p>Is there a way to expand a Python tuple into a function - as actual parameters?</p> <p>For example, here <code>expand()</code> does the magic:</p> <pre><code>tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") <...
163
2010-01-03T02:22:49Z
29,138,472
<p>Note that you can also expand part of argument list:</p> <pre><code>myfun(1, *("foo", "bar")) </code></pre>
11
2015-03-19T06:31:30Z
[ "python", "tuples", "argument-passing" ]
How do I trust the order of a Python dictionary?
1,993,747
<p>I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this?</p>
1
2010-01-03T02:33:32Z
1,993,750
<p>A standard Dictionary does not impose an ordering, it's simply a lookup.</p> <p>You want an <a href="http://www.voidspace.org.uk/python/odict.html" rel="nofollow">Ordered Dictionary</a> or <a href="http://www.python.org/dev/peps/pep-0372/" rel="nofollow">Ordered Dictionary</a>.</p>
9
2010-01-03T02:35:07Z
[ "python", "dictionary" ]
How do I trust the order of a Python dictionary?
1,993,747
<p>I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this?</p>
1
2010-01-03T02:33:32Z
1,993,765
<p>Python <code>dict</code>s are built as hash tables -- great performance, but ordering is essentially arbitrary and unpredictable. If your need for predictably-ordered walks are occasional, and based on keys or values, the <code>sorted</code> built-in is very handy:</p> <pre><code># print all entries in sorted key ...
5
2010-01-03T02:42:04Z
[ "python", "dictionary" ]
Drag and drop ordering of formset with extra entries
1,993,826
<p>I have been looking for a way to allow the user to easily change the order of entries in a formset. I found <a href="http://stackoverflow.com/questions/110774/re-ordering-entries-in-a-model-using-drag-and-drop">a StackOverflow question</a> that addresses this subject, with the accepted answer referencing a <a href=...
2
2010-01-03T03:09:58Z
1,998,067
<p>I do sortable formsets in one of my apps. I use this jQuery drag and drop plugin:</p> <p><a href="http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/" rel="nofollow">http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/</a></p> <p>I bind the plugin's onDrop event to a function that resets t...
1
2010-01-04T07:47:17Z
[ "javascript", "jquery", "python", "django" ]
Drag and drop ordering of formset with extra entries
1,993,826
<p>I have been looking for a way to allow the user to easily change the order of entries in a formset. I found <a href="http://stackoverflow.com/questions/110774/re-ordering-entries-in-a-model-using-drag-and-drop">a StackOverflow question</a> that addresses this subject, with the accepted answer referencing a <a href=...
2
2010-01-03T03:09:58Z
2,029,529
<p>I found my own solution. The snippet was setting the order for every row that had a non-empty primary key value. But the extra rows have an empty primary key, and I believe they have to stay empty for Django to know that they are to be inserted instead of updated. I modified the function to check for the other fi...
2
2010-01-08T17:50:54Z
[ "javascript", "jquery", "python", "django" ]
how change int to binary. on python 2.5
1,993,834
<pre><code>print 077777#how can i get binary </code></pre> <p>i use python2.5</p>
1
2010-01-03T03:16:17Z
1,993,861
<p>Here are some recipes from ActiveState Code you might find helpful: <a href="http://code.activestate.com/recipes/219300/" rel="nofollow">Format integer as binary string</a></p> <hr> <p>My initial answer only works in Python 2.6 and up as Alex correctly pointed out.</p> <blockquote> <p>Like this:</p> <p><co...
1
2010-01-03T03:30:25Z
[ "python" ]
how change int to binary. on python 2.5
1,993,834
<pre><code>print 077777#how can i get binary </code></pre> <p>i use python2.5</p>
1
2010-01-03T03:16:17Z
1,993,863
<p>Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers):</p> <pre><code>def bin(value): binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'} return ''.join(binmap[x] for x in ('%x' % (value,))).lstrip('0') or '0' </code></pre>
6
2010-01-03T03:31:07Z
[ "python" ]
how change int to binary. on python 2.5
1,993,834
<pre><code>print 077777#how can i get binary </code></pre> <p>i use python2.5</p>
1
2010-01-03T03:16:17Z
1,993,894
<p>Simplest (not fastest!) way to get a binary string for an int in Python 2.5:</p> <pre><code>def dobin(n): digs = [] s = '' if n&lt;0: s = '-' n = -n while True: digs.append(str(n % 2)) n /= 2 if not n: break if s: digs.append(s) digs.reverse() return ''.join(digs) </code></pre> <p...
1
2010-01-03T03:42:28Z
[ "python" ]
how change int to binary. on python 2.5
1,993,834
<pre><code>print 077777#how can i get binary </code></pre> <p>i use python2.5</p>
1
2010-01-03T03:16:17Z
1,993,904
<pre><code>n = 1234 "".join([["0", "1"][(n &gt;&gt; i) &amp; 1] for i in reversed(range(n.__sizeof__()))]) </code></pre> <p>although not sure if sizeof its correct.you could also calculate the highest bit set and only print those.</p> <pre><code>"".join([["0", "1"][(n&gt;&gt;i)&amp;1] for i in range(log(n,2)+1)]) </...
1
2010-01-03T03:45:10Z
[ "python" ]
Map list onto dictionary
1,993,840
<p>Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;</p> <pre><code>somefunction(lambda a: a[0], ["hello", "world"]) =&gt; {"h":"hello", "w":"world"} </code></pre> <p>(This isn't a specific...
9
2010-01-03T03:18:13Z
1,993,848
<p>I don't think a standard function exists that does exactly that, but it's very easy to construct one using the dict builtin and a comprehension:</p> <pre><code>def somefunction(keyFunction, values): return dict((keyFunction(v), v) for v in values) print somefunction(lambda a: a[0], ["hello", "world"]) </code><...
13
2010-01-03T03:23:45Z
[ "python", "list", "functional-programming", "hashtable" ]
Map list onto dictionary
1,993,840
<p>Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;</p> <pre><code>somefunction(lambda a: a[0], ["hello", "world"]) =&gt; {"h":"hello", "w":"world"} </code></pre> <p>(This isn't a specific...
9
2010-01-03T03:18:13Z
1,993,853
<p>If I understand your question correctly, I believe you can accomplish this with a combination of <code>map</code>, <code>zip</code>, and the <code>dict</code> constructor:</p> <pre><code>def dictMap(f, xs) : return dict(zip(map(f, xs), xs) </code></pre> <p>And a saner implementation :</p> <pre><code>def dictM...
5
2010-01-03T03:25:44Z
[ "python", "list", "functional-programming", "hashtable" ]
Map list onto dictionary
1,993,840
<p>Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;</p> <pre><code>somefunction(lambda a: a[0], ["hello", "world"]) =&gt; {"h":"hello", "w":"world"} </code></pre> <p>(This isn't a specific...
9
2010-01-03T03:18:13Z
1,994,012
<p>In Python 3 you can use this dictionary comprehension syntax:</p> <pre><code>def foo(somelist): return {x[0]:x for x in somelist} </code></pre>
15
2010-01-03T04:45:12Z
[ "python", "list", "functional-programming", "hashtable" ]
Map list onto dictionary
1,993,840
<p>Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;</p> <pre><code>somefunction(lambda a: a[0], ["hello", "world"]) =&gt; {"h":"hello", "w":"world"} </code></pre> <p>(This isn't a specific...
9
2010-01-03T03:18:13Z
2,004,101
<p>If you want a general function to do this, then you're asking almost the right question. Your example doesn't specify what happens when the key function produces duplicates, though. Do you keep the last one? The first one? Do you actually want to make a list of all the words that start with the same letter? These qu...
1
2010-01-05T04:02:14Z
[ "python", "list", "functional-programming", "hashtable" ]
Map list onto dictionary
1,993,840
<p>Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;</p> <pre><code>somefunction(lambda a: a[0], ["hello", "world"]) =&gt; {"h":"hello", "w":"world"} </code></pre> <p>(This isn't a specific...
9
2010-01-03T03:18:13Z
2,004,437
<pre><code>&gt;&gt;&gt; dict((a[0], a) for a in "hello world".split()) {'h': 'hello', 'w': 'world'} </code></pre> <p>If you want to use a function instead of subscripting, use operator.itemgetter:</p> <pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; first = itemgetter(0) &gt;&gt;&gt; dict((first(x...
1
2010-01-05T05:58:41Z
[ "python", "list", "functional-programming", "hashtable" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
1,993,918
<p>The end-of-file condition holds as soon as the <code>for</code> statement terminates -- that seems the simplest way to minorly fix this code (you can extract <code>text_block.getvalue()</code> at the end if you want to check it's not empty before appending it).</p>
1
2010-01-03T03:49:34Z
[ "python", "eof" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
1,993,928
<p>Why do you need StringIO here?</p> <pre><code>def get_text_blocks(filename): text_blocks = [""] with open(filename, 'r') as f: for line in f: if line.startswith('-- -'): text_blocks.append(line) else: text_blocks[-1] += line return text_blocks </...
0
2010-01-03T03:55:35Z
[ "python", "eof" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
1,993,930
<p>You might find it easier to solve this using <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby</a>.</p> <pre><code>def get_text_blocks(filename): import itertools with open(filename,'r') as f: groups = itertools.groupby(f, lambda line:line.sta...
3
2010-01-03T03:56:23Z
[ "python", "eof" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
1,994,855
<p>This is the standard problem with emitting buffers.</p> <p>You don't detect EOF -- that's needless. You write the last buffer.</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO.StringIO() with open(filename, 'r') as f: for line in f: text_block.wr...
0
2010-01-03T12:44:08Z
[ "python", "eof" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
4,835,532
<pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO.StringIO() with open(filename, 'r') as f: for line in f: text_block.write(line) print line if line.startswith('-- -'): text_blocks.append(text_block.getvalue()) ...
1
2011-01-29T06:33:04Z
[ "python", "eof" ]
How to check for EOF in Python?
1,993,896
<p>How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn't added to the return list. Or maybe there's a better way of expressing this function?</p> <p>Here's my code:</p> <pre><code>def get_text_blocks(filename): text_blocks = [] text_block = StringIO....
8
2010-01-03T03:43:13Z
10,093,521
<p>This is a fast way to see if you have an empty file:</p> <pre><code>if f.read(1) == '': print "EOF" f.close() </code></pre>
-2
2012-04-10T17:28:34Z
[ "python", "eof" ]
How safe is expression evaluation using eval?
1,994,071
<p>I am building a website where I have a need that user should be able to evaluate some expression based from the value in DB tables, instead of using tools like pyparsing etc, I am thinking of using python itself, and have come up with a solution which is sufficient for my purpose. I am basically using eval to evalua...
3
2010-01-03T05:23:19Z
1,994,102
<p>Certainly it's possible to consume all available memory or create an infinite loop even without the builtins. There are many ways to do it such as 'a'*999999*999999 or to make an infinite loop:</p> <pre><code>&gt;&gt;&gt; print eval('[[x.append(a) for a in x] for x in [[0]]]', ... {'__builtins__':{}}, {...
4
2010-01-03T05:45:56Z
[ "python", "security", "eval" ]
How safe is expression evaluation using eval?
1,994,071
<p>I am building a website where I have a need that user should be able to evaluate some expression based from the value in DB tables, instead of using tools like pyparsing etc, I am thinking of using python itself, and have come up with a solution which is sufficient for my purpose. I am basically using eval to evalua...
3
2010-01-03T05:23:19Z
1,994,145
<p>It's completely unsafe to use <code>eval</code>, even with built-ins emptied and blocked -- the attacker can start with a literal, get its <code>__class__</code>, etc, etc, up to <code>object</code>, its <code>__subclasses__</code>, and so forth... basically, Python introspection is just too strong to stand up to a ...
7
2010-01-03T06:14:40Z
[ "python", "security", "eval" ]
How safe is expression evaluation using eval?
1,994,071
<p>I am building a website where I have a need that user should be able to evaluate some expression based from the value in DB tables, instead of using tools like pyparsing etc, I am thinking of using python itself, and have come up with a solution which is sufficient for my purpose. I am basically using eval to evalua...
3
2010-01-03T05:23:19Z
10,964,412
<p>It is possible to get create and invoke any class defined in the program, which includes ones that can exit the Python interpreter. In addition, you can create and execute arbitrary strings of bytecode, which can segfault the interpreter. See <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.h...
2
2012-06-09T20:35:06Z
[ "python", "security", "eval" ]
assistance troubleshooting a python/cherrypy error
1,994,107
<pre><code>import cherrypy import os PORT = 8080 class intelServ: def index(self, botkey = None, userkey = None, network = None, user = None, channel = None, msg = None, step = None, **args): # If any necessary parameters are missing, the bot should fail silently. #if not botkey or not userkey or...
0
2010-01-03T05:48:20Z
1,994,385
<p>It looks like the parameter botkey as supplied to intelServ.index() is None (hence the 'NoneType'). You should uncomment your input validation code.</p>
1
2010-01-03T09:04:40Z
[ "python", "cherrypy" ]
i *must* store third party credentials in my database. best way?
1,994,112
<p>My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plain...
7
2010-01-03T05:52:44Z
1,994,158
<p>It's a difficult task, and no approach will save you the trouble to make sure that there is no weak link. For starters, I wouldn't know if hosting on Google is the best way to go, because you will be forfeiting control (I really don't know if App Engine is designed with the required level of security in mind, you sh...
2
2010-01-03T06:21:39Z
[ "python", "security", "google-app-engine", "authentication", "passwords" ]
i *must* store third party credentials in my database. best way?
1,994,112
<p>My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plain...
7
2010-01-03T05:52:44Z
1,994,236
<p>If you need to reversably store credentials there simply is no solution. Use AES and keep the secret key under well paid armed guard.</p> <p>If your using windows I would check out the Cred* Win32 API (advapi32.dll) it would at least allow you to punt key management to windows syskey where TPM and or bootup passph...
2
2010-01-03T07:31:31Z
[ "python", "security", "google-app-engine", "authentication", "passwords" ]
i *must* store third party credentials in my database. best way?
1,994,112
<p>My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plain...
7
2010-01-03T05:52:44Z
1,995,060
<p>How are the credentials being used? If their use is only triggered by the original owner (eg. you're storing a bank card number and they're making their 2nd purchase) then they can provide a password at that point which is used as your encryption key. You would then never need to store that key locally and the datab...
3
2010-01-03T14:05:32Z
[ "python", "security", "google-app-engine", "authentication", "passwords" ]
i *must* store third party credentials in my database. best way?
1,994,112
<p>My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plain...
7
2010-01-03T05:52:44Z
1,995,178
<p>A decent book that covers this sort of situation is <a href="http://rads.stackoverflow.com/amzn/click/0321320735" rel="nofollow" title="Cryptography In The Database">Cryptography In The Database</a>.</p>
2
2010-01-03T14:49:49Z
[ "python", "security", "google-app-engine", "authentication", "passwords" ]
What is python's 'restricted execution mode'?
1,994,117
<p>When <code>__builtins__</code> is set and I try to access function globals, I get this error</p> <pre><code>&gt;&gt;&gt; def f(): pass ... &gt;&gt;&gt; f.func_globals {'f': &lt;function f at 0x00B83270&gt;, '__builtins__': &lt;module '__builtin__' (built-in)&gt;} &gt;&gt;&gt; __builtins__ = {} &gt;&gt;&gt; f.func_...
0
2010-01-03T05:57:27Z
1,994,130
<p>Alas, a long-obsolete concept, see <a href="http://docs.python.org/library/restricted.html?highlight=restricted" rel="nofollow">the docs</a> -- the original idea was to provide a safe / sandboxed mode, but it just didn't pan out and was abandoned and deprecated since 2.3.</p>
3
2010-01-03T06:03:57Z
[ "python", "security" ]
python, and unicode stderr
1,994,157
<p>I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?</p> <p><strong>UPDATE 2010-01-03:</strong></p> <p>Thank you for the reply, but it seems the <co...
2
2010-01-03T06:21:21Z
1,994,176
<p>You can work with Unicode in python either by marking strings as Unicode (ie: <code>u'Hello World'</code>) or by using the encode() method that all strings have.</p> <p><strong>Eg.</strong> assuming you have a Unicode string, aStringVariable:</p> <pre><code>aStringVariable.encode('utf-8') </code></pre> <p>will co...
0
2010-01-03T06:29:32Z
[ "python", "unicode", "stderr" ]
python, and unicode stderr
1,994,157
<p>I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?</p> <p><strong>UPDATE 2010-01-03:</strong></p> <p>Thank you for the reply, but it seems the <co...
2
2010-01-03T06:21:21Z
1,996,049
<p><code>wsprintf</code>?</p> <p>This seems to be a "C/C++" question rather than a Python question.</p> <p>The Python interpreter always writes bytestrings to stdout/stderr, rather than unicode (or "wide") strings. It means Python first encodes all unicode data using the current encoding (likely <code>sys.getdefaulte...
-1
2010-01-03T19:41:50Z
[ "python", "unicode", "stderr" ]
python, and unicode stderr
1,994,157
<p>I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?</p> <p><strong>UPDATE 2010-01-03:</strong></p> <p>Thank you for the reply, but it seems the <co...
2
2010-01-03T06:21:21Z
2,001,767
<p>First, please remember that on Windows console may not fully support Unicode.</p> <p>The example below does make python output to <code>stderr</code> and <code>stdout</code> using <strong>UTF-8</strong>. If you want you could change it to other encodings.</p> <pre><code>#!/usr/bin/python # -*- coding: UTF-8 -*- i...
8
2010-01-04T19:54:37Z
[ "python", "unicode", "stderr" ]
Why am I getting an error using 'set' in Python?
1,994,163
<pre><code>s = set('ABC') s.add('z') s.update('BCD') s.remove('DEF') # error here s -= set('DEFG') </code></pre>
1
2010-01-03T06:23:23Z
1,994,172
<p>The argument to <a href="http://docs.python.org/library/stdtypes.html#set.remove" rel="nofollow"><code>set.remove()</code></a> must be a set member.</p> <p><code>'DEF'</code> is not a member of your set. <code>'D'</code> is.</p>
2
2010-01-03T06:27:04Z
[ "python", "set" ]
Why am I getting an error using 'set' in Python?
1,994,163
<pre><code>s = set('ABC') s.add('z') s.update('BCD') s.remove('DEF') # error here s -= set('DEFG') </code></pre>
1
2010-01-03T06:23:23Z
1,994,175
<p>From <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">http://docs.python.org/library/stdtypes.html</a> :</p> <blockquote> <p>remove(elem)</p> <p>Remove element elem from the set. Raises KeyError if elem is not contained in the set.</p> </blockquote> <p>'DEF' is not in the set</p>
0
2010-01-03T06:28:55Z
[ "python", "set" ]