content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Class attribute for two instances of the same class There is this code: class Sample: variable = 2 object1 = Sample() object2 = Sample() print object1.variable # 2 print object2.variable # 2 object1.variable = 1 print object1.variable # 1 print object2.variable # 2 <- why not 1 too? Why object2.variable i...
Class attribute for two instances of the same class
There is this code: class Sample: variable = 2 object1 = Sample() object2 = Sample() print object1.variable # 2 print object2.variable # 2 object1.variable = 1 print object1.variable # 1 print object2.variable # 2 <- why not 1 too? Why object2.variable is not also 1 after assignment to class variable?
[ "Don't confuse this with a static variable. In your case, both objects have a name variable point to a 2 object after instantiation. Now if you change the variable to 1 in one object, all you do is bind the name to a different object, i.e. the 1 object. The name in object2 still refers to a 2 object. The original c...
[ 5, 4, 2, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008688026_python.txt
Q: random sample in python I wanna speed this up: import random ndim = 50000 for i in xrange(ndim): random.sample([j for j in xrange(ndim) if j != i], 30000) I'm thinking about using NumPy but don't know how. A: From NumPy Docs - numpy.random.sample(size=None) Return random floats in the half-open interval [0....
random sample in python
I wanna speed this up: import random ndim = 50000 for i in xrange(ndim): random.sample([j for j in xrange(ndim) if j != i], 30000) I'm thinking about using NumPy but don't know how.
[ "From NumPy Docs -\n\nnumpy.random.sample(size=None)\nReturn random floats in the half-open interval [0.0, 1.0).\n\n>>> np.random.random_sample()\n0.47108547995356098\n>>> np.random.random_sample((5,))\narray([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])\n\nso if your ndim = 50000, then you cou...
[ 1, 1, 1 ]
[]
[]
[ "performance", "python", "random", "sample", "xrange" ]
stackoverflow_0008687959_performance_python_random_sample_xrange.txt
Q: How to get entity by child id while child is already deleted? I have this entity: class Room(db.Model): name = db.StringProperty() fb_user = db.ReferenceProperty(FbUser) I have fb_user_id = 131 but I have deleted that fb_user already. How to get room of that fb_user by that fb_user_id? A: This is soluti...
How to get entity by child id while child is already deleted?
I have this entity: class Room(db.Model): name = db.StringProperty() fb_user = db.ReferenceProperty(FbUser) I have fb_user_id = 131 but I have deleted that fb_user already. How to get room of that fb_user by that fb_user_id?
[ "This is solution for my own question:\nk = db.Key.from_path(FbUser.kind(), 131) \nroom = Room.all().filter('fb_user =', k).get()\ndb.delete(room)\n\n" ]
[ 1 ]
[]
[]
[ "google_cloud_datastore", "python" ]
stackoverflow_0008638285_google_cloud_datastore_python.txt
Q: Django can't have quoted characters in urls? I'm following this thread and adopt the code by peppergrower. But when I add the encrypted and quoted characters to the url and try access this url, Django failed with the following errors: Traceback (most recent call last): File "C:\Python27\lib\site-packages\django...
Django can't have quoted characters in urls?
I'm following this thread and adopt the code by peppergrower. But when I add the encrypted and quoted characters to the url and try access this url, Django failed with the following errors: Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 283, in run ...
[ "There are a few Django tickets relevant to this issue https://code.djangoproject.com/ticket/16541 and https://code.djangoproject.com/ticket/5738. In particular Malcolm's comment on #5738 given in part below:\n\nThe problem is that although UTF-8 is strongly recommended as the\n encoding for non-ASCII data, it's n...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008685139_django_python.txt
Q: Is there such a thing as startup file in PyDev under Eclipse? I have created a new project in Eclipse, PyDev. If I were in VS2010, I would mark a project as startup project, and whenever I click F5, it runs. I want to mark one .py file to be my so called Main, and that each time I click run (F11), it will be t...
Is there such a thing as startup file in PyDev under Eclipse?
I have created a new project in Eclipse, PyDev. If I were in VS2010, I would mark a project as startup project, and whenever I click F5, it runs. I want to mark one .py file to be my so called Main, and that each time I click run (F11), it will be the one to run, and not the current that is being edited. Is it poss...
[ "Go to run -> run configurations \nIn the menu on the right you should have Python Run option. Create new run configuration by double clicking.\nOn the right you can select the project you want to run and it's main module. The other tabs can be used to configure arguments, python interpreter used to run the project...
[ 2, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0008688050_eclipse_pydev_python.txt
Q: Good Python 2 audio module What is a good module for playing wav files for Python 2 that would also be supported by py2app? (no pygame) I just need it to be able to play a simple wav file. Thanks in advance :) A: Check PyAudio. I found some examples like this where it has been used with py2app
Good Python 2 audio module
What is a good module for playing wav files for Python 2 that would also be supported by py2app? (no pygame) I just need it to be able to play a simple wav file. Thanks in advance :)
[ "Check PyAudio. I found some examples like this where it has been used with py2app \n" ]
[ 1 ]
[]
[]
[ "audio", "module", "py2app", "python", "wav" ]
stackoverflow_0008688451_audio_module_py2app_python_wav.txt
Q: Locking a row with SQLite (read lock ?) I have developed a basic proxy tester in Python. Proxy IPs and ports, as well as their date_of_last_test (e.g. 31/12/2011 10:10:10) and result_of_last_test (OK or KO) are stored in a single SQLite table. (I realize I could store a lot more details on the tests results and ke...
Locking a row with SQLite (read lock ?)
I have developed a basic proxy tester in Python. Proxy IPs and ports, as well as their date_of_last_test (e.g. 31/12/2011 10:10:10) and result_of_last_test (OK or KO) are stored in a single SQLite table. (I realize I could store a lot more details on the tests results and keep an history / stats, but this simple model ...
[ "SQlite only allows one process to update anything in the database at a time, From the FAQ\n\nMultiple processes can have the same database open at the same time. Multiple processes can be doing a SELECT at the same time. But only one process can be making changes to the database at any moment in time,\n\nand\n\nWh...
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0008688476_python_sqlite.txt
Q: Downloading data from the datastore I wanted to download the data on my online app's datastore, I followed the guide on code.google, I added this to my app.yaml file builtins: - remote_api: on But when I updated using appcfg.py update src and called this: appcfg.py download_data --application=myapp --url=http://m...
Downloading data from the datastore
I wanted to download the data on my online app's datastore, I followed the guide on code.google, I added this to my app.yaml file builtins: - remote_api: on But when I updated using appcfg.py update src and called this: appcfg.py download_data --application=myapp --url=http://myapp.appspot.com/remote_api_path --filena...
[ "Try this:\nbuiltins:\n- remote_api: on\n\nAnd for url\nappcfg.py download_data --application=~myapp --url=http://myapp.appspot.com/_ah/remote_api --filename=first-test-backup\n\nAtttention _ah in url: http://myapp.appspot.com/_ah/remote_api\n" ]
[ 4 ]
[]
[]
[ "database_backups", "google_app_engine", "google_cloud_datastore", "python", "python_2.7" ]
stackoverflow_0008688594_database_backups_google_app_engine_google_cloud_datastore_python_python_2.7.txt
Q: Python server script and C program communication Error The objective of my application is to control some LEDs on my embedded target from the ethernet link. My embedded board supports lighttpd web server. From this web server, I can run python scripts that read to devices on my board no problem. The problem comes ...
Python server script and C program communication Error
The objective of my application is to control some LEDs on my embedded target from the ethernet link. My embedded board supports lighttpd web server. From this web server, I can run python scripts that read to devices on my board no problem. The problem comes when I am trying to write to those devices. The lighttpd ser...
[ "Ricardo Cárdenes's suggestion to change the ownership or permissions of the device is a good one, but if you can't do that, just make the Python script that lighttpd calls be a \"setuid\" script, meaning that lighttpd will invoke it as www but it will run as root.\nI normally would not suggest making a script setu...
[ 1 ]
[]
[]
[ "c++", "ipc", "python", "web" ]
stackoverflow_0008688509_c++_ipc_python_web.txt
Q: Why does Django make Python look ugly? I took up the Python programming language because of its design philosophies, its great community and most importantly for me its beautiful syntax. However, recently I've been a left a little disheartend. In my attempts to customise Django I've come across code that I think s...
Why does Django make Python look ugly?
I took up the Python programming language because of its design philosophies, its great community and most importantly for me its beautiful syntax. However, recently I've been a left a little disheartend. In my attempts to customise Django I've come across code that I think syntactically could be cleaner. I'm by no mea...
[ "\nI appreciate that maybe it's my lack of experience with Python itself or that bits of code that make the syntax look unclean are in-fact core features of the Python programming language.\n\nThat's just it. As you continue to code you'll realize that what you were experiencing was a result of everything being new...
[ 3, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008688410_django_python.txt
Q: how to decompile user password in django I have a SECRET_KEY, how do i decompile a user password using python? I assume that the encryption method is sha1. thanks. A: You are asking the impossible. The passwords are salted and hashed. The way they're validated is by performing the same process on the re-suppli...
how to decompile user password in django
I have a SECRET_KEY, how do i decompile a user password using python? I assume that the encryption method is sha1. thanks.
[ "You are asking the impossible. The passwords are salted and hashed. The way they're validated is by performing the same process on the re-supplied password. There's no way to 'decrypt' it.\n" ]
[ 5 ]
[]
[]
[ "django", "python", "sha1" ]
stackoverflow_0008688762_django_python_sha1.txt
Q: Make simple edits on Word document programmatically I want to make some simple edits on a Word document, eg replace all TEXT with text. I have tried python-docx, but it doesn't let me save only my changes. Instead it makes a new document with default style and saves it with my content. Is there a good library(Pyt...
Make simple edits on Word document programmatically
I want to make some simple edits on a Word document, eg replace all TEXT with text. I have tried python-docx, but it doesn't let me save only my changes. Instead it makes a new document with default style and saves it with my content. Is there a good library(Python or other languages) that supports quick edits on docx...
[ "Little bit of why you are not able to do simple string replace in docx - a .docx document is a Zip archive in OpenXML format: you have first to uncompress it. Earlier I used to use zip to unzip the docx & then search for the text, like so -\n>>> import zipfile\n>>> z = zipfile.ZipFile(\"yourDocInDocx.docx\")\n>>> ...
[ 3 ]
[]
[]
[ "ms_word", "python" ]
stackoverflow_0008688176_ms_word_python.txt
Q: Python - Dijkstra's algorithm on a large scale I have a large network, about 400 nodes, and what I'm trying to do is calculate every possible route you can make on the network. That means, the nodes traversed and the total weighting of the route from Node 1 to Node 2, Node 1 to Node 3 up to Node 1 to Node 400. Th...
Python - Dijkstra's algorithm on a large scale
I have a large network, about 400 nodes, and what I'm trying to do is calculate every possible route you can make on the network. That means, the nodes traversed and the total weighting of the route from Node 1 to Node 2, Node 1 to Node 3 up to Node 1 to Node 400. Then, from Node 2 to Node 3, Node 2 to Node 4 up to No...
[ "You can use the Python graph module NetworkX which has methods for all pairs shortest paths (weighted and unweighted). And they are optimized in the sense that they use the best known algorithms for such tasks.\n", "The tweak which you are suggesting will simply change its method of sorting the possible route an...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008688884_python.txt
Q: XPath: select tag with empty value How I can find in XPath 1.0 all rows with empty col name="POW"? <row> <col name="WOJ">02</col> <col name="POW"/> <col name="GMI"/> <col name="RODZ"/> <col name="NAZWA">DOLNOŚLĄSKIE</col> <col name="NAZDOD">województwo</col> <col name="STAN_NA">2011-01-01</col> </row> I tried man...
XPath: select tag with empty value
How I can find in XPath 1.0 all rows with empty col name="POW"? <row> <col name="WOJ">02</col> <col name="POW"/> <col name="GMI"/> <col name="RODZ"/> <col name="NAZWA">DOLNOŚLĄSKIE</col> <col name="NAZDOD">województwo</col> <col name="STAN_NA">2011-01-01</col> </row> I tried many solutions. Few times in Firefox extens...
[ "\nHow I can find in XPath 1.0 all rows with empty col name=\"POW\"?\n\nThere are many possible definitions of \"empty\" and for each one of them there is a different XPath expression selecting \"empty\" elements.\nA reasonable definition for an empty element is: an element that has no children elements and no text...
[ 12, 4, 1 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0008688185_lxml_python_xml_xpath.txt
Q: excluding element from numpy array I want to get the c array as result, but I don't know how: import numpy as np a = xrange(10) b = np.array([3,2,1,9]) c is made of elements of a that are not in b: c = np.array([0,4,5,6,7,8]) A: Perhaps a more straightforward solution is the following: import numpy as np a = xr...
excluding element from numpy array
I want to get the c array as result, but I don't know how: import numpy as np a = xrange(10) b = np.array([3,2,1,9]) c is made of elements of a that are not in b: c = np.array([0,4,5,6,7,8])
[ "Perhaps a more straightforward solution is the following:\nimport numpy as np\na = xrange(10)\nb = np.array([3,2,1,9])\n\nc = np.setdiff1d(a,b)\n\nWhich results in:\nIn [7]: c\nOut[7]: array([0, 4, 5, 6, 7, 8])\n\nYou can find all of the set-like operations for numpy arrays in the documentation:\nhttp://docs.scipy...
[ 9, 2 ]
[]
[]
[ "arrays", "elements", "numpy", "python" ]
stackoverflow_0008688203_arrays_elements_numpy_python.txt
Q: Find most similar shapes in Python I am working on a virtual keyboard, similar to Swype (but for a platform it doesn't support). Basically, what it does (for those not familiar) is you move your finger over the keys without lifting it off for each word. So what I need to do is compare the shape drawn to the shape ...
Find most similar shapes in Python
I am working on a virtual keyboard, similar to Swype (but for a platform it doesn't support). Basically, what it does (for those not familiar) is you move your finger over the keys without lifting it off for each word. So what I need to do is compare the shape drawn to the shape of each word in the wordlist, and use th...
[ "Had written this sometime back. A slightly different approach, It is pretty fast. hope it helps.. \nhttp://krishnabharadwaj.info/how-swype-works/\n", "Check out the $1 Unistroke Recognizer in JavaScript. It is badass.\n" ]
[ 2, 1 ]
[]
[]
[ "comparison", "n900", "python", "vector", "virtual_keyboard" ]
stackoverflow_0006932408_comparison_n900_python_vector_virtual_keyboard.txt
Q: Publicly accessible functions from python module I am writing a sizable side project in python and I have got a module which implements all database access with only functions declared within the module.I was wondering if there is anyway to declare functions in the module as public so that python knows that these ...
Publicly accessible functions from python module
I am writing a sizable side project in python and I have got a module which implements all database access with only functions declared within the module.I was wondering if there is anyway to declare functions in the module as public so that python knows that these are the only functions that should be used from outsid...
[ "Don't preface them with _ (underscore). \nAccording to PEP 8 -- Style Guide for Python Code:\n\npublic attributes should have no leading underscores\n\n", "No. The convention is to prefix private names with a single underscore, e.g. _foo.\n", "Declare a module-level variable named __all__. This is a tuple of s...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008689258_python.txt
Q: tkSnack not working properly I'm using Python 2.7 and I'm trying to use tkSnack but I don't really get it. I installed it but when I do initializeSnack(), it gives me: /Library/Tcl/snack2.2/libsnack.dylib: mach-o, but wrong architecture I tried searching it for a long time but none of them gave me a clear answer ...
tkSnack not working properly
I'm using Python 2.7 and I'm trying to use tkSnack but I don't really get it. I installed it but when I do initializeSnack(), it gives me: /Library/Tcl/snack2.2/libsnack.dylib: mach-o, but wrong architecture I tried searching it for a long time but none of them gave me a clear answer what I should do. Does anyone kno...
[ "Maybe this and the following reply also fits your case.\nThe problem seems to be related with an out-of-date version of Tcl/Tk.\n" ]
[ 0 ]
[]
[]
[ "architecture", "macos", "module", "python", "python_2.7" ]
stackoverflow_0008689274_architecture_macos_module_python_python_2.7.txt
Q: Python create list from specific indexes in a list of lists I have a list of lists and I want to create multiple smaller lists from specific indexes in this list. If I have this big "matrix" can I create a small list made up of integers collected from this matrix? Code: matrix = [ [0, 0, 0, 5, 0, 0, 0, 0, 6], ...
Python create list from specific indexes in a list of lists
I have a list of lists and I want to create multiple smaller lists from specific indexes in this list. If I have this big "matrix" can I create a small list made up of integers collected from this matrix? Code: matrix = [ [0, 0, 0, 5, 0, 0, 0, 0, 6], [8, 0, 0, 0, 4, 7, 5, 0, 3], [0, 5, 0, 0, 0, 3, 0, 0, 0],...
[ "if index1 means FIRST index, row1 means FIRST row,\nthen matrix[0][0] = 0 in this case.\n matrix[1][0] = 8\n matrix[1][5] = 7\nIn all, you can do matrix[row_index][col_index]\nSo\nlist1 = [ matrix[0,0], matrix[2][2] ]\n\nHope this helps.\n", "list1 = [matrix[1][1], matrix[2][2]]\nlist2 = [matrix[6][3], m...
[ 4, 4, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008689613_list_python.txt
Q: Python; comma at the end of old formatter argument list Just a quick question: What does a comma in the following statement does: print "Average = %s" % (avg,) It seems I just can't find the relevant documentation. A: It makes the argument list into a tuple. Without the trailing comma a single value in pare...
Python; comma at the end of old formatter argument list
Just a quick question: What does a comma in the following statement does: print "Average = %s" % (avg,) It seems I just can't find the relevant documentation.
[ "It makes the argument list into a tuple. Without the trailing comma a single value in parentheses is just that value in parentheses.\n", "It creates a one item tuple:\n>>> x = ('hello')\n>>> type(x)\n<type 'str'>\n>>> x = ('hello',)\n>>> type(x)\n<type 'tuple'>\n\n", "The comma makes it into a tuple.\nYou coul...
[ 5, 2, 2 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0008689763_formatting_python.txt
Q: Assign lat/long to zip codes I have a dataframe latitude and longitude points in R. Using the R data science toolkit, I can assign these points to Country/State/County/City/Constituency/Neighborhood, which is useful. I'd like to assign these points to 5 digit zip-codes (or even 9 digit zip codes!) in R or python....
Assign lat/long to zip codes
I have a dataframe latitude and longitude points in R. Using the R data science toolkit, I can assign these points to Country/State/County/City/Constituency/Neighborhood, which is useful. I'd like to assign these points to 5 digit zip-codes (or even 9 digit zip codes!) in R or python. Is there an easy way to do this?...
[ "\nFind a zip code shapefile somewhere (.shp format, sometimes called\nArcGIS Shapefiles).\nLoad it into R using the maptools package's readShapePoly\ncommand.\nCreate a SpatialPointsDataFrame to hold the points.\nMake sure your projections are correct.\nUse the sp package's overlay command to overlay the points in...
[ 5, 3 ]
[]
[]
[ "python", "r", "reverse_geocoding", "zipcode" ]
stackoverflow_0006913316_python_r_reverse_geocoding_zipcode.txt
Q: Crawler for Twitter social graph via python I am sorry for asking but I am new in writing crawler. I would like to crawl Twitter space for Twitter users and follow relationship among them using python. Any recommendation for starting points such as tutorials? Thank you very much in advance. A: I'm a big fan of T...
Crawler for Twitter social graph via python
I am sorry for asking but I am new in writing crawler. I would like to crawl Twitter space for Twitter users and follow relationship among them using python. Any recommendation for starting points such as tutorials? Thank you very much in advance.
[ "I'm a big fan of Tweepy myself - https://github.com/tweepy/tweepy\nYou'll have to refer to the Twitter docs for the API methods that you're going to need. As far as I know, Tweepy wraps all of them, but I recommend looking at Twitter's own docs to find out which ones you need.\nTo construct a following/follower gr...
[ 2, 1 ]
[]
[]
[ "python", "twitter", "web_crawler" ]
stackoverflow_0008689825_python_twitter_web_crawler.txt
Q: Status of the "marker" keyword in Jinja I was looking though the templating documentation for Jinja and noticed that the example does not use the marker keyword in the base template, nor is it used later on in the documentation. However if you look here, marker is used in the example with block. Why is that? Is ma...
Status of the "marker" keyword in Jinja
I was looking though the templating documentation for Jinja and noticed that the example does not use the marker keyword in the base template, nor is it used later on in the documentation. However if you look here, marker is used in the example with block. Why is that? Is marker deprecated? Is one doc more up to date t...
[ "Those are documentation for two very different versions of Jinja. http://jinja.pocoo.org/docs/ documents the current version, Jinja2, while http://wsgiarea.pocoo.org/jinja/ documents an old jinja \"pre 1.0\" version, for historical purposes presumably. marker was probably removed in Jinja2 because it is equivale...
[ 1 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0008685616_jinja2_python.txt
Q: Python insert variable in loop into SQLite database using SQLAlchemy I am using SQLAlchemy with declarative base and Python 2.6.7 to insert data in a loop into an SQLite database. As brief background, I have implemented a dictionary approach to creating a set of variables in a loop. What I am trying to do is scra...
Python insert variable in loop into SQLite database using SQLAlchemy
I am using SQLAlchemy with declarative base and Python 2.6.7 to insert data in a loop into an SQLite database. As brief background, I have implemented a dictionary approach to creating a set of variables in a loop. What I am trying to do is scrape some data from a website, and have between 1 and 12 pieces of data in t...
[ "Python attribute access doesn't work like that. row.key looks up the attribute with the literal name \"key\", not the value that's in the variable key.\nYou probably need to use setattr:\nsetattr(row, key, value)\n\n" ]
[ 3 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0008689958_python_sqlalchemy_sqlite.txt
Q: Add a column to an existing table using GQL? I have a table having some entries. I want to add a column to that table with some default value.In mysql we it as In mysql: `ALTER TABLE Example ADD status VARCHAR(60) default 1` How can I achieve same in GQL (google query language)? A: As google datastore is objec...
Add a column to an existing table using GQL?
I have a table having some entries. I want to add a column to that table with some default value.In mysql we it as In mysql: `ALTER TABLE Example ADD status VARCHAR(60) default 1` How can I achieve same in GQL (google query language)?
[ "As google datastore is object oriented, it is different from MySql.\nOnce you update your existing model by adding new field to your model class:\nclass Example(db.Model): \n #other fields\n status = db.StringProperty()\n\nand \nexample = Example()\nexample.status = \"Happy new year\"\nexample.put()\n\nyo...
[ 3 ]
[]
[]
[ "google_app_engine", "mysql", "python" ]
stackoverflow_0008690060_google_app_engine_mysql_python.txt
Q: pycurl: how to reset a cookie session I'm using the following piece of code to get the content of a webpage from python script: #!/usr/bin/env python import pycurl import StringIO c = pycurl.Curl() c.setopt(pycurl.URL, "http://google.com") b = StringIO.StringIO() c.setopt( c.WRITEFUNCTION, b.write) #c.setopt(pycu...
pycurl: how to reset a cookie session
I'm using the following piece of code to get the content of a webpage from python script: #!/usr/bin/env python import pycurl import StringIO c = pycurl.Curl() c.setopt(pycurl.URL, "http://google.com") b = StringIO.StringIO() c.setopt( c.WRITEFUNCTION, b.write) #c.setopt(pycurl.COOKIESESSION, True); c.setopt(pycurl.CO...
[ "I'm sorry but this option is not supported in pycurl, but as I can see in the source code, it should be a fairly easy fix.\nYou should ask for it on the curl and python mailing list.\n", "This fixes the Problem:\nimport pycurl\npycurl.COOKIESESSION = 96\n\n", "I guess removing the cookiefile will have the same...
[ 2, 2, 0 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0002906292_pycurl_python.txt
Q: Python MDP Policy I'm trying to implement a 4 dimensional race-car problem using a famous MDP library for python. We have a race-car in a 2 dimensional track. When I say 4 dimensional problem, I mean that each STATE is (x,y,vx,vy), meaning: position (x,y) and SPEED (vx,vy). SPEED is either 0 or 1 (for each axis), ...
Python MDP Policy
I'm trying to implement a 4 dimensional race-car problem using a famous MDP library for python. We have a race-car in a 2 dimensional track. When I say 4 dimensional problem, I mean that each STATE is (x,y,vx,vy), meaning: position (x,y) and SPEED (vx,vy). SPEED is either 0 or 1 (for each axis), so the number of states...
[ "I think I solved it.\nNotice that all states that include negative speeds are not present at the STATES set, and also not preset at the REWARD dictionary.\nThis was due to a faulty initialization process.\n" ]
[ 0 ]
[]
[]
[ "artificial_intelligence", "python" ]
stackoverflow_0008687879_artificial_intelligence_python.txt
Q: Pygame MemoryError HI i wrote a simple block collecting program that was working just fine and dandy until i added sound. Then all the sudden i get a MemoryError which is something ive never seen before. my code is attached along with the sound(wav) file that seem to be the problem. Any help would be great, and ye...
Pygame MemoryError
HI i wrote a simple block collecting program that was working just fine and dandy until i added sound. Then all the sudden i get a MemoryError which is something ive never seen before. my code is attached along with the sound(wav) file that seem to be the problem. Any help would be great, and yes the code and the sound...
[ "I think you have to initialize the mixer first, before using sounds.\npygame.mixer.init(44100, -16, 2, 2048)\n# Read the docs to know what these numbers are\n\n" ]
[ 12 ]
[]
[]
[ "audio", "memory", "pygame", "python" ]
stackoverflow_0008690301_audio_memory_pygame_python.txt
Q: Node.toprettyxml() adds newlines to DOCTYPE in Python When using prettify my DOCTYPE is broken into three lines. How can I keep it on one line? The "broken" output: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE smil PUBLIC '-//W3C//DTD SMIL 2.0//EN' 'http://www.w3.org/2001/SMIL20/SMIL20.dtd'> <smil xmlns="h...
Node.toprettyxml() adds newlines to DOCTYPE in Python
When using prettify my DOCTYPE is broken into three lines. How can I keep it on one line? The "broken" output: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE smil PUBLIC '-//W3C//DTD SMIL 2.0//EN' 'http://www.w3.org/2001/SMIL20/SMIL20.dtd'> <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> <head> <meta ...
[ "I think you have at least three options:\n\nJust accept the newlines. They may be undesired and ugly but they are perfectly legal.\nAdd a kludge that replaces the bad DOCTYPE with a nicer one. Perhaps something like this:\nimport re\n\npretty_xml = prettify(doctype, elem)\nm = re.search(\"(<!.*dtd'>)\", pretty_xml...
[ 2, 2, 0 ]
[]
[]
[ "elementtree", "minidom", "pretty_print", "python", "xml" ]
stackoverflow_0008685032_elementtree_minidom_pretty_print_python_xml.txt
Q: How to send login request in python? i am trying this python script: import httplib import urllib conn = httplib.HTTPConnection("moodle.tau.ac.il") conn.request("POST" , "/hu11/?lang=en_utf8&username=bugs&password=bunny" ) response = conn.getresponse() print response.status, response.reason print response.read() ...
How to send login request in python?
i am trying this python script: import httplib import urllib conn = httplib.HTTPConnection("moodle.tau.ac.il") conn.request("POST" , "/hu11/?lang=en_utf8&username=bugs&password=bunny" ) response = conn.getresponse() print response.status, response.reason print response.read() conn.close() but it doesn't log in the si...
[ "Try BeautifulSoup or Mechanize.\n" ]
[ 1 ]
[]
[]
[ "html", "http_request", "python" ]
stackoverflow_0008690314_html_http_request_python.txt
Q: How to compare variables and find difference in python I have two variables readARP and readFPING which will have a series of IP's listed in them and I want to compare one to the other. After comparing them I would like to print out the difference if there is any. readARP = scanProcess.read() readFPING = fpingscan...
How to compare variables and find difference in python
I have two variables readARP and readFPING which will have a series of IP's listed in them and I want to compare one to the other. After comparing them I would like to print out the difference if there is any. readARP = scanProcess.read() readFPING = fpingscanPocess.read() >>> print readARP 192.168.1.1 192.168.1.100 1...
[ "As simple as it can get. You can use the set symmetric_difference to find the unique elements in both the input source.\nreadARP=scanProcess.read()\nreadFPING = fpingscanPocess.read()\nprint readARP\n192.168.1.1\n192.168.1.100\n192.168.1.1\n\nprint readFPING\n192.168.1.1\n192.168.2.1\n192.168.1.12\n\nprint '\\n'.j...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008690424_python.txt
Q: Is there a way to include contents of a file in Python as code (compile-time)? I am using a 3rd party application's Python integration where Python code is stored internally in binary files. So I want to separate the code from it. I could create a module but the code I need to include doesn't function on its own, ...
Is there a way to include contents of a file in Python as code (compile-time)?
I am using a 3rd party application's Python integration where Python code is stored internally in binary files. So I want to separate the code from it. I could create a module but the code I need to include doesn't function on its own, as it includes locals only valid in that context, etc. I am basically looking for a ...
[ "Yes, it's called exec.\nYour code would look like this: exec your_code_str. The code is then executed in the current scope.\nYou could also specify a different scope: exec your_code_str in globals(), locals() (those values are the default, so only specify them if they differ)\nNote that you can also pass a file ob...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0008690500_python.txt
Q: How can I switch the positions of each element in a list with Python? Using Python, what's the most efficient way to switch the positions of every other element in a list? For example, I'm trying to get a sequential list of the alphabet with each letter after A switched, like so: import string alphabet = string.as...
How can I switch the positions of each element in a list with Python?
Using Python, what's the most efficient way to switch the positions of every other element in a list? For example, I'm trying to get a sequential list of the alphabet with each letter after A switched, like so: import string alphabet = string.ascii_uppercase # ABCDEFGHIJKLMNOPQRSTUVWXYZ switched_alphabet = do_somethin...
[ ">>> import string\n>>> alphabet = list(string.ascii_uppercase)\n>>> for i in range(2, len(alphabet), 2):\n... alphabet[i], alphabet[i-1] = alphabet[i-1], alphabet[i]\n... \n>>> alphabet\n['A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X'...
[ 6, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008690448_python.txt
Q: Django, class-views: How can I save session data with a form's object? I'm trying to store the username from the current request's session into a db object. How can I do this from within a class-based view? Is there a "clean" way to do this? What should I override/subclass? I have a model that looks like this: fro...
Django, class-views: How can I save session data with a form's object?
I'm trying to store the username from the current request's session into a db object. How can I do this from within a class-based view? Is there a "clean" way to do this? What should I override/subclass? I have a model that looks like this: from django.contrib.auth.models import User class Entry(django.db.models.Model)...
[ "The \"correct\" way to do this is to write your own view for object creation if the generic view doesn't suffice. Creation views are relatively short and there are numerous examples of how to save foreign keys.\n", "Incidentally, Django's 1.3 docs say somewhere in there that modifications to the authentication m...
[ 1, 0 ]
[]
[]
[ "django", "django_class_based_views", "python" ]
stackoverflow_0008688367_django_django_class_based_views_python.txt
Q: Issues with Python hashlib.sha256 (2.4.3) So I have some code: signature = hmac.new( key=AWS_SECRET_ACCESS_KEY, msg=string_to_sign, digestmod=hashlib.sha256).digest() That runs perfectly on my own computer (has python 2.6.1). However, when I run this code on my server (Python 2.4.3) I get the followin...
Issues with Python hashlib.sha256 (2.4.3)
So I have some code: signature = hmac.new( key=AWS_SECRET_ACCESS_KEY, msg=string_to_sign, digestmod=hashlib.sha256).digest() That runs perfectly on my own computer (has python 2.6.1). However, when I run this code on my server (Python 2.4.3) I get the following: /home/MYUSERNAME/public_html/Foo.com/cgi-bi...
[ "hashlib is new in 2.5. You'll need the backport for older versions of Python.\n", "This is a hack to make hashlib backport work with hmac on python 2.4:\nclass mysha256:\n digest_size = 32\n def new(self, inp=''):\n return hashlib.sha256(inp)\n\nand use hmac like this:\nsignature = hmac.new(\n ke...
[ 0, 0 ]
[]
[]
[ "hashlib", "python", "sha256" ]
stackoverflow_0003172536_hashlib_python_sha256.txt
Q: Is there a text editor that will automatically determine whether to indent with spaces or tabs? It's very easy to set a text editor to use spaces or tab characters with each press of the tab key. However, I'm working with a grip of Python code maintained by a large team of developers in my company, and some use sp...
Is there a text editor that will automatically determine whether to indent with spaces or tabs?
It's very easy to set a text editor to use spaces or tab characters with each press of the tab key. However, I'm working with a grip of Python code maintained by a large team of developers in my company, and some use spaces and some use tabs. I cannot simply make them all conform with each other, because 1) it would br...
[ "Sublime Text does this.\n", "I think geany ( http://www.geany.org/ ) has that option in the preferences, if you use linux.\n", "For Emacs, there is guess-style.\n", "TextMate for the Mac does this.\nI'm sure there are scripts for both vim and emacs.\n", "You can do this in vim. This function from codeblog...
[ 6, 1, 1, 0, 0, 0 ]
[]
[]
[ "editor", "indentation", "python", "spaces", "tabs" ]
stackoverflow_0001704028_editor_indentation_python_spaces_tabs.txt
Q: Unescaping filenames generated by ls -R I have a text file containing the output of a recursive directory listing that generally looks like this: ./subfolder/something with spaces: something\ with\ spaces.txt* something\ with\ spaces.dat* ./subfolder/yet another thing: yet\ another\ thing.txt* yet\ another\ thing...
Unescaping filenames generated by ls -R
I have a text file containing the output of a recursive directory listing that generally looks like this: ./subfolder/something with spaces: something\ with\ spaces.txt* something\ with\ spaces.dat* ./subfolder/yet another thing: yet\ another\ thing.txt* yet\ another\ thing.dat* I need to get a list of the full paths...
[ "I'm not sure if there's built-in for this, but a simple regex could be used.\nre.sub(r'(?<!\\\\)\\\\', '', filename)\n\nThis would remove all backslashes (except for those following another backslash). This seems to be the behavior when you try and echo these values on the terminal (I've only tested this in bash)....
[ 1 ]
[]
[]
[ "escaping", "ls", "python", "shell" ]
stackoverflow_0008690640_escaping_ls_python_shell.txt
Q: How to make a variable name without creating an array in Python? I'm asking a question similar to this, but with python 2.7 instead. I know that I'm the same asker of the question, but the answer should be different. Here's the link. How to make a variable name without creating an array in C++? I looked up Data St...
How to make a variable name without creating an array in Python?
I'm asking a question similar to this, but with python 2.7 instead. I know that I'm the same asker of the question, but the answer should be different. Here's the link. How to make a variable name without creating an array in C++? I looked up Data Structures on the python website, but I have no idea what they're talkin...
[ "If you are looking for a structure that is similar to std::map in C++, you should use dict. It is a dictionary, that can have any hashable object as key (a string, a tuple, an integer). For example:\nx = dict()\nx['a'] = 5\nx[6] = MyObject()\n\nAs you can see this is more powerful than std::map, because keys might...
[ 3, 1 ]
[ "You could do something like the following:\nglobals()['foo'] = 10\n\nor\nlocals()['foo'] = 10\n\nAnd then you can access foo by its name after that. From your other question, it seems like your asking how do you make an array (in Python, it's usually a list) without using square brackets.\nUnlike C/C++, you do not...
[ -6 ]
[ "data_structures", "python" ]
stackoverflow_0008691333_data_structures_python.txt
Q: Python referring to an item in a list from another list I have a list of variables (listA) from from another list (listB). The problem I am having is that the items from listB are being passed by value to listA rather than by reference. Is there anyway I can access the the object in listB after having put its valu...
Python referring to an item in a list from another list
I have a list of variables (listA) from from another list (listB). The problem I am having is that the items from listB are being passed by value to listA rather than by reference. Is there anyway I can access the the object in listB after having put its value in listA? For example: listB = [1,2,3,4,5] listA = [listB[0...
[ "Everything in python is a reference. After all those statements are executed, listB[1] and listA[1] are literally the same object. (you can check, by calling id(listB[1]) and id(listA[1]).\nThe reason listA[0] and listB[0] are different is merely because you put a different reference into that spot.\nJudging from ...
[ 1, 1 ]
[]
[]
[ "list", "pass_by_reference", "python" ]
stackoverflow_0008691326_list_pass_by_reference_python.txt
Q: How to set up settings.py on Google app engine I changed from GAE/Py2.5 to 2.7 and from Django0.9 to Django1.2. I am useing relative paths extends tag to Template Engine When caused TemplateDoesNotExist error and disable. It's use Template “google.appengine.ext.webapp.template”. I think , how do I set up your own ...
How to set up settings.py on Google app engine
I changed from GAE/Py2.5 to 2.7 and from Django0.9 to Django1.2. I am useing relative paths extends tag to Template Engine When caused TemplateDoesNotExist error and disable. It's use Template “google.appengine.ext.webapp.template”. I think , how do I set up your own loader to TEMPLATE_LOADERS or setting the template p...
[ "Can you use just a regular requesthandler? What happens if you test:\nclass Home(RequestHandler):\n def get(self):\n data = {}\n path = os.path.join(os.path.dirname(__file__), 'templates/main.html')\n self.response.out.write(template.render(path, data))\n\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python", "settings", "webapp2" ]
stackoverflow_0008676040_google_app_engine_python_settings_webapp2.txt
Q: Calculating with a SVG elipitical arc? I'm working on a custom pyQt SVG renderer and need help. This is purely mathematical so you won't need an API. To calculate a SVG elliptical arc you need two radii rx and ry; the rotation of the ellipse in degrees x-axis-rotation; the large-arc-sweep-flag (1 or 0) that deter...
Calculating with a SVG elipitical arc?
I'm working on a custom pyQt SVG renderer and need help. This is purely mathematical so you won't need an API. To calculate a SVG elliptical arc you need two radii rx and ry; the rotation of the ellipse in degrees x-axis-rotation; the large-arc-sweep-flag (1 or 0) that determines if an arc is drawn through greater tha...
[ "SVG elliptical arcs use \"endpoint parametrization\".\nQPainterPath.arcTo arcs use \"center parametrization\".\nThe SVG link you kindly provided has a link near the end of the section entitled \n\"Elliptical arc implementation notes\" which gives formulas for the conversion between endpoint and center parametrizat...
[ 1 ]
[]
[]
[ "pyqt4", "python", "python_3.x" ]
stackoverflow_0008691419_pyqt4_python_python_3.x.txt
Q: Percentile rank calculation I'm attempting to calculate the percentile rank of a score using the python statlib module. The percentileofscore function is supposed to return a value between 0 and 100, however it regularly produces numbers outside this range. An example: >> a = [0,1,2,3,4,5] >> percentileofscore(a...
Percentile rank calculation
I'm attempting to calculate the percentile rank of a score using the python statlib module. The percentileofscore function is supposed to return a value between 0 and 100, however it regularly produces numbers outside this range. An example: >> a = [0,1,2,3,4,5] >> percentileofscore(a, 0) 108.33333333333333 I've tr...
[ "scipy.stats.percentileofscore seems to work as expected:\nIn [2]: import scipy.stats as stats\n\nIn [3]: stats.percentileofscore([0,1,2,3,4,5], 0)\nOut[3]: 16.666666666666664\n\n" ]
[ 8 ]
[]
[]
[ "percentile", "python", "scipy", "statistics" ]
stackoverflow_0008691573_percentile_python_scipy_statistics.txt
Q: Unusual Math with incorrect results? My python interpreter is acting funky when I use the math.cos() and math.sin() function. For example, if I do this on my calculator: cos(35)*15+9 = 21.28728066 sin(35)*15+9 = 17.60364655 But when I do this on python (both 3.2 and 2.7) >>> import math >>> math.cos(35)*15+9 -4.5...
Unusual Math with incorrect results?
My python interpreter is acting funky when I use the math.cos() and math.sin() function. For example, if I do this on my calculator: cos(35)*15+9 = 21.28728066 sin(35)*15+9 = 17.60364655 But when I do this on python (both 3.2 and 2.7) >>> import math >>> math.cos(35)*15+9 -4.5553830763726015 >>> import math >>> math....
[ "This is being caused by the fact that you are using degrees\nand the trigonometric functions expect radians as input:\nsin(radians)\nThe description for sin is:\nsin(x)\n Return the sine of x (measured in radians).\n\nIn Python, you can convert degrees to radians with the math.radians function.\n\nSo if you do ...
[ 9, 1, 0 ]
[]
[]
[ "math", "python", "trigonometry" ]
stackoverflow_0008691800_math_python_trigonometry.txt
Q: Foreign key in tastypie So, I started using the TastyPie plugin for Django to make a REST api for my project. I was following the getting started guide with my project, but when I got in this point, when I was supposed to put a Foreign Key, it started giving me some errors. The maior one is this when I do a simpl...
Foreign key in tastypie
So, I started using the TastyPie plugin for Django to make a REST api for my project. I was following the getting started guide with my project, but when I got in this point, when I was supposed to put a Foreign Key, it started giving me some errors. The maior one is this when I do a simple get: "Reverse for 'api_disp...
[ "The final answer for my problem is the answer from @manji and @dlrust combined:\n\"change urlpatterns value to urlpatterns = patterns('', (r'^api/', include(api.urls)),)\"\nand, after that, \"define an authorization in your Meta for the resource\".\nHope it's useful for somebody else as it was for me :)\n", "It ...
[ 3, 1 ]
[]
[]
[ "django", "python", "rest", "tastypie" ]
stackoverflow_0005756205_django_python_rest_tastypie.txt
Q: method of class receiving unknown arguments I have a class that I defined, the class currently takes 2 arguments, self and savepath. A method of this class takes 2 arguments, self. Within that method, I call a function which again takes 2 arguments, local_hash and filename, however, upon calling this the method, I...
method of class receiving unknown arguments
I have a class that I defined, the class currently takes 2 arguments, self and savepath. A method of this class takes 2 arguments, self. Within that method, I call a function which again takes 2 arguments, local_hash and filename, however, upon calling this the method, I get the error described below. I assume it has s...
[ "You are probably missing 'self' in the argument list of the 'put_nowait' method. Something like this I believie:\nclass md5_queue:\n def put_nowait(filename, local_hash):\n .\n .\n .\n\nChanging it to the following should fix your problem:\nclass md5_queue:\n def put_nowait(self, filename, local_...
[ 0, 0 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0008690669_class_methods_python.txt
Q: Memcacheing WHERE IN query myModel.gql("WHERE prop IN :1", myList) After running this query, how can I memcache entities that match each prop separately? For example, if myList is: ['prop1', 'prop2', 'prop3'] How do I make 3 separate memcache entries, one for each item in the list? A: query = MyModel.gql(<your G...
Memcacheing WHERE IN query
myModel.gql("WHERE prop IN :1", myList) After running this query, how can I memcache entities that match each prop separately? For example, if myList is: ['prop1', 'prop2', 'prop3'] How do I make 3 separate memcache entries, one for each item in the list?
[ "query = MyModel.gql(<your GQL query WHERE statement>)\n\nfor mymodel in query:\n memcache.add(somekey, mymodel.somedata, 60)\n\nWhere 60 is the expiration time in seconds, which can be any expiration that is appropriate for your app. Also, please note the difference between \"add()\" and \"set()\" functions - a...
[ 1 ]
[]
[]
[ "google_app_engine", "memcached", "python" ]
stackoverflow_0008692042_google_app_engine_memcached_python.txt
Q: Subprocess.communicate prints newline to standard output I have a script that calls ffprobe, parses its output and outputs it to the console. Here's a stripped-down version of it without the parsing code and command-line options: """Invoke ffprobe to query a video file and parse the output""" def ffprobe(fname): ...
Subprocess.communicate prints newline to standard output
I have a script that calls ffprobe, parses its output and outputs it to the console. Here's a stripped-down version of it without the parsing code and command-line options: """Invoke ffprobe to query a video file and parse the output""" def ffprobe(fname): import subprocess as sub import re p = sub.Popen([...
[ "I cannot reproduce the problem, so maybe it depends on the file you're passing to ffprobe.\nAnyway, from what I see, stdout isn't being captured, so maybe the problem is just that ffprobe is printing a new line character to stdout.\nTo confirm this, please replace:\np = sub.Popen(['ffprobe', fname], stderr=sub.PIP...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0008692496_python.txt
Q: looking for a Python based web-app to serve files I am looking for a Python-based alternatives for AutoIndex PHP Script. Preferably it runs under WSGI. The features of AutoIndex are listed here and there is also a live demo. Note: + I'm not looking for a web server. My shared web hosting doesn't allow me to run my...
looking for a Python based web-app to serve files
I am looking for a Python-based alternatives for AutoIndex PHP Script. Preferably it runs under WSGI. The features of AutoIndex are listed here and there is also a live demo. Note: + I'm not looking for a web server. My shared web hosting doesn't allow me to run my own background process. + Neither am I looking for web...
[ "Look at this question:\nWhat is the best way to serve static web pages from within a Django application?\nUse Django with the flatpages app. I cannot be sure, since your comments and your question disagree, but I think this is what you're looking for.\n", "Flask-Autoindex is what you're looking for... \n\nFlask...
[ 2, 2, 0 ]
[]
[]
[ "passenger", "python", "web", "web_applications", "wsgi" ]
stackoverflow_0002304668_passenger_python_web_web_applications_wsgi.txt
Q: Python re "bogus escape error" I've been messing around with the python re modules .search method. cur is the input from a Tkinter entry widget. Whenever I enter a "\" into the entry widget, it throws this error. I'm not all to sure what the error is or how to deal with it. Any insight would be much appreciated. ...
Python re "bogus escape error"
I've been messing around with the python re modules .search method. cur is the input from a Tkinter entry widget. Whenever I enter a "\" into the entry widget, it throws this error. I'm not all to sure what the error is or how to deal with it. Any insight would be much appreciated. cur is a string tup[0] is also a st...
[ "\"bogus escape (end of line)\" means that your pattern ends with a backslash. This has nothing to do with Tkinter. You can duplicate the error pretty easily in an interactive shell:\n>>> import re\n>>> pattern=\"foobar\\\\\"\n>>> re.search(pattern, \"foobar\")\nTraceback (most recent call last):\n File \"<stdin>\...
[ 18, 12, 3, 3 ]
[]
[]
[ "python", "regex", "tkinter" ]
stackoverflow_0004427174_python_regex_tkinter.txt
Q: Python: NameError - what should I do with this? I am working on a large-scale software system that is written in Python right now. The thing is, I am not sure how to make sure if each individual .py file in the system is correct. The only way for me to run the software is to run the main.py file, which uses all th...
Python: NameError - what should I do with this?
I am working on a large-scale software system that is written in Python right now. The thing is, I am not sure how to make sure if each individual .py file in the system is correct. The only way for me to run the software is to run the main.py file, which uses all the other .py files. So either everything works, or one...
[ "This is a straight-forward error message which indicates that the execution flow has not yet encountered class/module/variable RGBox prior to it being called.\nRGBox is either being called out of sequence or has been mispelt.\nPerform a commandline search through the app files for the name 'RGBox' or its regex equ...
[ 1 ]
[]
[]
[ "class", "module", "python" ]
stackoverflow_0008679317_class_module_python.txt
Q: Roundrobin over changing set I'd like to implement a simple round robin over a Python list or set that may be changed at runtime. The Problem is that I have a set of tasks that are to be executed in a round robin fashion, which should be simple enough to implement with a list and a modular increment of the index, ...
Roundrobin over changing set
I'd like to implement a simple round robin over a Python list or set that may be changed at runtime. The Problem is that I have a set of tasks that are to be executed in a round robin fashion, which should be simple enough to implement with a list and a modular increment of the index, but since I will modify the list i...
[ "I once used for testing purposes a \"round-robin\" test-object generator. I don't know if this will help you, but i included a simple example script to demsonstrate how it operates.\nfrom itertools import cycle\n\nn = 1\nlst = [n]\nfor i in cycle(lst):\n print i\n n += 1\n if n < 100:\n lst.append(n)\n\n...
[ 1 ]
[]
[]
[ "list", "python", "round_robin", "scheduling", "set" ]
stackoverflow_0008693420_list_python_round_robin_scheduling_set.txt
Q: Python 2.7 Tkinter and ftplib I have quick question, and it may sound dumb. But for the love of me I can't find a solution online or by myself! I am trying to make a FTP client using python for my self, and I am trying to make a listbox in Tkinter display all the filenames on the FTP server. But I can't get the te...
Python 2.7 Tkinter and ftplib
I have quick question, and it may sound dumb. But for the love of me I can't find a solution online or by myself! I am trying to make a FTP client using python for my self, and I am trying to make a listbox in Tkinter display all the filenames on the FTP server. But I can't get the text to display! Here is the code I h...
[ "You get \"Transfer Complete\" because retrlines returns the response code, not the listing. If you check the documentation, you'll see that apart from the command, there's a second argument, a callback, that will be called for each line returned. By default it just prints the line to the standard output.\nlines = ...
[ 2 ]
[]
[]
[ "ftplib", "python", "python_2.7", "tkinter" ]
stackoverflow_0008693595_ftplib_python_python_2.7_tkinter.txt
Q: Python and Line Breaks With Python I know that the "\n" breaks to the next line in a string, but what I am trying to do is replace every "," in a string with a '\n'. Is that possible? I am kind of new to Python. A: Try this: text = 'a, b, c' text = text.replace(',', '\n') print text For lists: text = ['a', 'b',...
Python and Line Breaks
With Python I know that the "\n" breaks to the next line in a string, but what I am trying to do is replace every "," in a string with a '\n'. Is that possible? I am kind of new to Python.
[ "Try this:\ntext = 'a, b, c'\ntext = text.replace(',', '\\n')\nprint text\n\nFor lists:\ntext = ['a', 'b', 'c']\ntext = '\\n'.join(text)\nprint text\n\n", ">>> str = 'Hello, world' \n>>> str = str.replace(',','\\n') \n>>> print str \nHello \n world\n\n>>> str_list=str.split('\\n')\n>>> print str_list\n['Hello...
[ 3, 2, 0 ]
[]
[]
[ "python", "python_2.7", "string" ]
stackoverflow_0008693732_python_python_2.7_string.txt
Q: Python arguments, for in items I'd like to pass a list of integers as an argument to a python script. Example code: items = sys.argv[1] for item in items: print item My command would be: python myscript.py 101,102,103 The problem is that 'for in' is giving me each digit rather than each item as delimited by ...
Python arguments, for in items
I'd like to pass a list of integers as an argument to a python script. Example code: items = sys.argv[1] for item in items: print item My command would be: python myscript.py 101,102,103 The problem is that 'for in' is giving me each digit rather than each item as delimited by the commas. I'm sure there's an easy...
[ "Normally the command line arguments are separated by spaces. The comma separated numbers are coming in as a single string, and the for is splitting the string into characters. You need to split it by commas: items.split(','). Once you do that you'll find that you still have strings, so you need to convert each str...
[ 6, 3, 2, 2 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0008693715_for_loop_loops_python.txt
Q: subprocess.Popen: Different buffering for stdin, stdout, stderr? I'm in need of setting the stderr stream in a Popen call to line-buffered. I discovered the bufsize argument, but it applies to all of the stdin, stdout, and stderr files. How do I adjust the buffering to be different for each file? A: I assume you...
subprocess.Popen: Different buffering for stdin, stdout, stderr?
I'm in need of setting the stderr stream in a Popen call to line-buffered. I discovered the bufsize argument, but it applies to all of the stdin, stdout, and stderr files. How do I adjust the buffering to be different for each file?
[ "I assume you use PIPE for stderr? In that case, I think you can do something like this:\np = subprocess.Popen(..., stderr=subprocess.PIPE)\nfd = p.stderr.fileno()\nmy_stderr = os.fdopen(os.dup(fd), 'rU', new_bufsize)\nos.close(fd)\n# use my_stderr from here on\n\n", "If you intend to write stdout/stderr to a fil...
[ 3, 1 ]
[]
[]
[ "buffering", "popen", "python", "python_3.x" ]
stackoverflow_0005604441_buffering_popen_python_python_3.x.txt
Q: Instantiate MySQL DB class I would like to write a class that would contain all my MySQL operations. Right now, I cant even get the class instantiated. Traceback (most recent call last): File "./compare.py", line 71, in <module> main() File "./compare.py", line 67, in main db = Table.mysqlconnect() Typ...
Instantiate MySQL DB class
I would like to write a class that would contain all my MySQL operations. Right now, I cant even get the class instantiated. Traceback (most recent call last): File "./compare.py", line 71, in <module> main() File "./compare.py", line 67, in main db = Table.mysqlconnect() TypeError: unbound method mysqlconn...
[ "The error is exactly right:\nTypeError: unbound method mysqlconnect() must be called with Table instance as first argument (got nothing instead)\nIn other words, you are using a class name (Table) and not an instance of the class Table.\nRead these examples, they do exactly what you want. If you want to read up on...
[ 3, 3, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0008693845_mysql_python.txt
Q: Performance for finding the maximum value in a dictionary versus numpy array I have a large (in thousands) collection of word : value (float) pairs. I need to find the best of the value and extract the corresponding associated word. For example, I have (a,2.4),(b,5.2),(c,1.2),(d,9.2),(e,6.3),(f,0.4). I would like ...
Performance for finding the maximum value in a dictionary versus numpy array
I have a large (in thousands) collection of word : value (float) pairs. I need to find the best of the value and extract the corresponding associated word. For example, I have (a,2.4),(b,5.2),(c,1.2),(d,9.2),(e,6.3),(f,0.4). I would like (d,9.2) as the output. Currently, I am using a dictionary to store these tuples an...
[ "I don't see how a numpy array would help you in this case.\nIn particular, any conversion of a data structure into another (in your case a list of tuples in a numpy array or a heapq) will be much slower than finding the maximum value iterating over each tuple). This is because converting the data structure will al...
[ 5, 3 ]
[]
[]
[ "dictionary", "max", "numpy", "performance", "python" ]
stackoverflow_0008693116_dictionary_max_numpy_performance_python.txt
Q: Python List Replace Possible Duplicate: Python and Line Breaks In Python I know that when your handling strings you can use "replace" to replace a certain character in a string. For example: h = "2,3,45,6" h = h.replace(',','\n') print h Returns: 2 3 45 6 Is there anyway to do this with a list? For example rep...
Python List Replace
Possible Duplicate: Python and Line Breaks In Python I know that when your handling strings you can use "replace" to replace a certain character in a string. For example: h = "2,3,45,6" h = h.replace(',','\n') print h Returns: 2 3 45 6 Is there anyway to do this with a list? For example replace all the "," in a li...
[ "Looking at your example and desire, you can use the str.join and this is probably what you want\n>>> h\n['2', '3', '45', '6']\n>>> print '\\n'.join(str(i) for i in h)\n2\n3\n45\n6\n\nsimilarly for your second example\n>>> h = [\"hello\",\"goodbye\",\"how are you\"]\n>>> print '\\n'.join(str(i) for i in h)\nhello\n...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "list", "python", "python_2.7" ]
stackoverflow_0008693867_list_python_python_2.7.txt
Q: python code explanation I have been studying this code to generate random text: from collections import defaultdict, Counter from itertools import ifilter from random import choice, randrange def pairwise(iterable): it = iter(iterable) last = next(it) for curr in it: yield last, curr l...
python code explanation
I have been studying this code to generate random text: from collections import defaultdict, Counter from itertools import ifilter from random import choice, randrange def pairwise(iterable): it = iter(iterable) last = next(it) for curr in it: yield last, curr last = curr valid = set('abcd...
[ "target = randrange(sum(d.values()))\nd.values() Since model is a dictionary mapping letters to counter object, and a counter object is a dictionary, d.values() is a list of all the counts for each key in the dictionary (but doesn't return the keys). This means sum(d.values()) will return the total of all the count...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008694724_python.txt
Q: Need an example of a POP3 Server or IMAP Server written in Python Experimenting with Application Messaging over email for Applications. I have already created my SMTP Server but now missing a centralised delivery mechanism. I can create a propriety delivery mechanism very easily but I am trying to use protocol sta...
Need an example of a POP3 Server or IMAP Server written in Python
Experimenting with Application Messaging over email for Applications. I have already created my SMTP Server but now missing a centralised delivery mechanism. I can create a propriety delivery mechanism very easily but I am trying to use protocol standards. I am not interested in HTTP, FTP or SOAP but only the mail prot...
[ "Edit:\nA simple example of a POP3 server can be found here: http://code.activestate.com/recipes/534131-pypopper-python-pop3-server/ You will have to replace the message serving mechanism, but you would need to do that anyway. For an IMAP server implementation using Twisted, see https://github.com/davglass/twimapd ...
[ 6, 2, 1, 1 ]
[]
[]
[ "imap", "pop3", "python", "twisted" ]
stackoverflow_0004214800_imap_pop3_python_twisted.txt
Q: wxPython: Enabling and disabling widgets dynamically, getting settings from a csv file I have a small program with many widgets like checkboxes, textctrls, statictexts,... The values of all my widgets are stored in a dictionary. I'm saving the settings, e.g. this dictionary in a csv file. When I'm importing the se...
wxPython: Enabling and disabling widgets dynamically, getting settings from a csv file
I have a small program with many widgets like checkboxes, textctrls, statictexts,... The values of all my widgets are stored in a dictionary. I'm saving the settings, e.g. this dictionary in a csv file. When I'm importing the settings from this file and update my dictionary, all my widgets should be enabled or disabled...
[ "As I said up in the comments, don't use bool(config.StartValues['Checkbox2']) to do the data conversion. bool returns True for anything that does not evaluate to 0, 0.0 or an empty sequence or map. In this case, strings like \"True\" and \"False\" will both evaluate to True\nUsing string comparison or similar woul...
[ 2 ]
[]
[]
[ "casting", "dictionary", "python", "widget", "wxpython" ]
stackoverflow_0008694832_casting_dictionary_python_widget_wxpython.txt
Q: removing accent and special characters Possible Duplicate: What is the best way to remove accents in a python unicode string? Python and character normalization I would like to remove accents, turn all characters to lowercase, and delete any numbers and special characters. Example : Frédér8ic@ --> frederic Prop...
removing accent and special characters
Possible Duplicate: What is the best way to remove accents in a python unicode string? Python and character normalization I would like to remove accents, turn all characters to lowercase, and delete any numbers and special characters. Example : Frédér8ic@ --> frederic Proposal: def remove_accents(data): return ...
[ "A possible solution would be\ndef remove_accents(data):\n return ''.join(x for x in unicodedata.normalize('NFKD', data) if x in string.printable).lower()\n\nUsing NFKD AFAIK is the standard way to normalize unicode to convert it to compatible characters. The rest as to remove the special characters numbers and ...
[ 15, 1 ]
[]
[]
[ "diacritics", "python" ]
stackoverflow_0008694815_diacritics_python.txt
Q: ImportError when trying to install pygame 1.9.1 (32bit) on 64 bit Mac 10.6 machine with Python 2.7.2 ***Update: Here are the errors I am getting: >>> import pygame Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pygame File "/Library/Frameworks/Python.framework/Versions/2...
ImportError when trying to install pygame 1.9.1 (32bit) on 64 bit Mac 10.6 machine with Python 2.7.2
***Update: Here are the errors I am getting: >>> import pygame Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pygame File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in <module> from pygame.base import * Imp...
[ "As noted in the comments of the answer you linked to, solution 1 only works with the Apple-supplied Pythons, not Pythons installed from elsewhere. The Apple-installed Pythons are accessed from /usr/bin; generally, Pythons installed from python.org or elsewhere will be accessible as just python2.7 (no /usr/bin) or...
[ 2 ]
[]
[]
[ "32bit_64bit", "osx_snow_leopard", "pygame", "python" ]
stackoverflow_0008693758_32bit_64bit_osx_snow_leopard_pygame_python.txt
Q: Summarizing a Wikipedia Article I find myself having to learn new things all the time. I've been trying to think of ways I could expedite the process of learning new subjects. I thought it might be neat if I could write a program to parse a wikipedia article and remove everything but the most valuable informatio...
Summarizing a Wikipedia Article
I find myself having to learn new things all the time. I've been trying to think of ways I could expedite the process of learning new subjects. I thought it might be neat if I could write a program to parse a wikipedia article and remove everything but the most valuable information. I started by taking the Wikipedia ...
[ "Considering that your question relates more to a research activity than a programming problem, you should probably look at scientific literature. Here you will find published details of a number of algorithms that perform exactly what you want. A google search for \"keyword summarization\" finds the following:\nSi...
[ 14, 1 ]
[]
[]
[ "machine_learning", "python", "statistics", "summarization", "wikipedia" ]
stackoverflow_0008691537_machine_learning_python_statistics_summarization_wikipedia.txt
Q: Django meta admin ordering - Excluding grammatical articles I currently have this chunk of model code: class Book(models.Model): title = models.CharField(max_length=100) num_pages = models.IntegerField(blank=True, null=True) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Pub...
Django meta admin ordering - Excluding grammatical articles
I currently have this chunk of model code: class Book(models.Model): title = models.CharField(max_length=100) num_pages = models.IntegerField(blank=True, null=True) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unic...
[ "You could try,\nclass Book(models.Model):\n displayed_title = models.CharField(max_length=100)\n ordered_title = models.CharField(max_length=100)\n\n def __unicode__(self):\n return self.displayed_title\n\n class Meta:\n ordering = [\"ordered_title\"]\n\nAnd just make sure that you are pa...
[ 2, 1 ]
[ "Don't know if this is working....untested...just an idea to keep in mind that django is just python...I hope that helps to get you to the right track!?!\ndef splitter(title): \n list_title=[]\n a = split(title) \n for word in a:\n if len(word) > 3: # With this you filter \"a\" \"the\" e...
[ -1 ]
[ "admin", "django", "python" ]
stackoverflow_0008695086_admin_django_python.txt
Q: Django-Templated-Email: TemplateDoesNotExist when importing from a different file I have a Django project with two apps: email_app and landing_page_app. The landing_page_app.views includes email_app.views, so that it can use the new_lead_email function. In email_app.views: from datetime import datetime from tem...
Django-Templated-Email: TemplateDoesNotExist when importing from a different file
I have a Django project with two apps: email_app and landing_page_app. The landing_page_app.views includes email_app.views, so that it can use the new_lead_email function. In email_app.views: from datetime import datetime from templated_email import send_templated_mail def new_lead_email(email): send_templated_...
[ "You shouldn't be importing views from one app into views from another. Try creating a utils.py for email_app and putting your function in there. I am currently doing this for a generic email sending function for a project, using a globalutils.py file in project root. It sends txt/html emails from templates I have ...
[ 0 ]
[]
[]
[ "django", "email", "python" ]
stackoverflow_0008695145_django_email_python.txt
Q: In python shell, "b" letter does not work, what the? Well hello, this is the most interesting bug/conflict I've ever faced. In python shell, I cannot type lowercase "b". At first I thought something was under the key, but no, in everywhere else it functions very well. Also ctrl+b shift+b even with capslock b works...
In python shell, "b" letter does not work, what the?
Well hello, this is the most interesting bug/conflict I've ever faced. In python shell, I cannot type lowercase "b". At first I thought something was under the key, but no, in everywhere else it functions very well. Also ctrl+b shift+b even with capslock b works. Yet more, when I run the shell with sudo (ie. sudo pytho...
[ "The problematic line in your .pythonstartup is something like:\n readline.parse_and_bind(\"bind ^I rl_complete\") # darwin libedit\n\nThis .pythonstartup will fix it...\ntry:\n import readline\nexcept ImportError:\n print \"Module readline not available.\"\nelse:\n import rlcompleter\n if 'libedit' in ...
[ 14, 8 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0007124035_python_shell.txt
Q: Take control of interpreter in multithreaded program In python interpreter mode, i launched a thread that points to function that prints statements in an infinite loop. Now i would like to take control of the interpreter again to launch another thread. How can i take get back to the interperter >>? A: Let's supo...
Take control of interpreter in multithreaded program
In python interpreter mode, i launched a thread that points to function that prints statements in an infinite loop. Now i would like to take control of the interpreter again to launch another thread. How can i take get back to the interperter >>?
[ "Let's supose that this is your code (from http://mundogeek.net/ ¿QUÉ SON LOS PROCESOS Y LOS THREADS?):\nimport threading \n\nclass MiThread(threading.Thread): \n def __init__(self, num): \n threading.Thread.__init__(self) \n self.num = num \n\n def run(self): \n while tr...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008689216_python.txt
Q: Dictionary With Multiple Values To Nested List I have a dictionary with the following structure: {'ONE' : (4, 6, 9), 'TWO' : (3, 8, 10)} I'd like to sort this dictionary by the 3rd value of each tuple. I can't really think of a way to accomplish this with the data setup as a dictionary, but it should be fairly ea...
Dictionary With Multiple Values To Nested List
I have a dictionary with the following structure: {'ONE' : (4, 6, 9), 'TWO' : (3, 8, 10)} I'd like to sort this dictionary by the 3rd value of each tuple. I can't really think of a way to accomplish this with the data setup as a dictionary, but it should be fairly easy if I can convert the data to a nested list like t...
[ "Use the key argument of the built-in sorted function:\n>>> d = {'ONE' : (4, 6, 9), 'TWO' : (3, 8, 10), 'FOUR': (2, 5, 8)}\n>>> sorted(d.iteritems(), key=lambda i: i[1][2])\n[('FOUR', (2, 5, 8)), ('ONE', (4, 6, 9)), ('TWO', (3, 8, 10))]\n\nEDIT\nIf some of the values are ints rather than tuples, then something like...
[ 3, 0, 0 ]
[]
[]
[ "dictionary", "list", "nested_lists", "python", "python_3.x" ]
stackoverflow_0008695495_dictionary_list_nested_lists_python_python_3.x.txt
Q: Is there a way to get pywin32 to use vcvars32.bat instead of vcvarsall.bat? So, I'm just trying to build pywin32 on my Windows 7 machine. When running the setup script, I ran into the common error of "Unable to find vcvarsall.bat". I do have Visual C++ installed, so I was somewhat confused. After a bit of searchin...
Is there a way to get pywin32 to use vcvars32.bat instead of vcvarsall.bat?
So, I'm just trying to build pywin32 on my Windows 7 machine. When running the setup script, I ran into the common error of "Unable to find vcvarsall.bat". I do have Visual C++ installed, so I was somewhat confused. After a bit of searching around, here as well as other sites, I found that the best solution to my probl...
[ "\nIs there a way to get pywin32 to use vcvars32.bat instead of\n vcvarsall.bat?\n\nThere's no need.\n\nI realized that, since I have Visual Studio 2010 installed rather than\n 2008 or earlier, I have a file called \"vcvars32.bat\" instead of the\n usual \"vcvarsall.bat\".\n\nYou have both and vcvars32.bat is be...
[ 3, 1, 1 ]
[]
[]
[ "python", "pywin32" ]
stackoverflow_0004403119_python_pywin32.txt
Q: Why do I get a MemoryError with itertools.product? I would expect the following snippet to give me an iterator yielding pairs from the Cartesian product of the two input iterables: $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for...
Why do I get a MemoryError with itertools.product?
I would expect the following snippet to give me an iterator yielding pairs from the Cartesian product of the two input iterables: $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> one = xrange...
[ "It doesn't store intermediate results, but it has to store the input values because each of those might be needed several times for several output values.\nSince you can only iterate once over an iterator, product cannot be implemented equivalent to this:\ndef prod(a, b):\n for x in a:\n for y in b:\n yi...
[ 18, 7, 0 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0008695422_python_python_itertools.txt
Q: django urls.py cannot process the url i am creating a django app, my project name is domain_com and the application name is gallery. The project is mapped to domain.com, so that works, now when i create the urls.py with these redirects its giving me these errors (r'^domain_com/(?P<page_name>[^/]+)/edit/$', 'domain...
django urls.py cannot process the url
i am creating a django app, my project name is domain_com and the application name is gallery. The project is mapped to domain.com, so that works, now when i create the urls.py with these redirects its giving me these errors (r'^domain_com/(?P<page_name>[^/]+)/edit/$', 'domain_com.gallery.views.edit_page'), (r'^domain_...
[ "You have made a complicated URL of the form http://domain.com/domain_com/page_name/edit/. Yet you're testing with the URL http://domain.com/edit. Obviously, those don't match.\n", "after updated my answer:\ntry this:\n(r'^/edit/(?P<page_name>\\w+)$', 'gallery.views.edit_page'),\n(r'^/save/(?P<page_name>\\w+)$', ...
[ 3, 1, 0 ]
[]
[]
[ "debian", "django", "linux", "python" ]
stackoverflow_0008695352_debian_django_linux_python.txt
Q: convert keyboard azerty to qwerty and vice-versa is there a module for converting the letters of a AZERTY keyboard in a QWERTY keyboard letters and vice versa? To do this it must also be able to detect the keyboard type, possible? Example: 'data'. to_qwerty () -> 'dqtq' or 'dqtq'. to_azerty () -> 'data' Or a simpl...
convert keyboard azerty to qwerty and vice-versa
is there a module for converting the letters of a AZERTY keyboard in a QWERTY keyboard letters and vice versa? To do this it must also be able to detect the keyboard type, possible? Example: 'data'. to_qwerty () -> 'dqtq' or 'dqtq'. to_azerty () -> 'data' Or a simple solution without having to type all the letters of e...
[ "If you just want to convert one string to another, that's pretty simple:\n(it does however require you to specify how they translate from one to the other)\n>>> translate_dict = dict(zip(\"abcdef\", \"123456\"))\n>>> translate_this = \"deadbeef\"\n>>> ''.join([translate_dict.get(x) for x in translate_this])\n'4514...
[ 3 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0008695496_keyboard_python.txt
Q: Python list comprehension for Numpy I'm looking for list-comprehension method or similar in Numpy to eliminate use of a for-loop eg. index_values is a Python dictionary list of lists (each list containing a different number of index values) and s is a numpy vector: for i in range(33): s[index_values[i]] += 4.1...
Python list comprehension for Numpy
I'm looking for list-comprehension method or similar in Numpy to eliminate use of a for-loop eg. index_values is a Python dictionary list of lists (each list containing a different number of index values) and s is a numpy vector: for i in range(33): s[index_values[i]] += 4.1 Is there a method available that allows...
[ "I don't fully understand what kind of object index_values is. But if it were an ndarray, or could be converted to an ndarray, you could just do this:\n>>> s = numpy.arange(20)\n>>> index_values = (numpy.random.random((3, 3)) * 20).astype('i')\n>>> s[index_values] = 4\n>>> s\narray([ 0, 1, 4, 4, 4, 5, 6, 4, ...
[ 4, 1 ]
[]
[]
[ "for_loop", "list_comprehension", "numpy", "python" ]
stackoverflow_0008695806_for_loop_list_comprehension_numpy_python.txt
Q: Error using paypal sandbox API I'm trying to make Paypal's sandbox API work and I'm using a sample project and the error I get is response was: {"responseEnvelope":{"timestamp":"2011-12-26T12:35:19.560-08:00","ack":"Success","correlationId":"ea7c82ca4d096","build":"2279004"},"payKey":"AP-53K115241G5252300","payme...
Error using paypal sandbox API
I'm trying to make Paypal's sandbox API work and I'm using a sample project and the error I get is response was: {"responseEnvelope":{"timestamp":"2011-12-26T12:35:19.560-08:00","ack":"Success","correlationId":"ea7c82ca4d096","build":"2279004"},"payKey":"AP-53K115241G5252300","paymentExecStatus":"CREATED"} headers mus...
[ "I believe you're running into a bug/feature of webapp2.\nredirect() will not accept unicode it must be a str.\nTry changing line main.py #91 to: \n self.redirect( pay.next_url().encode('ascii') ) # go to paypal\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "paypal", "paypal_sandbox", "python" ]
stackoverflow_0008634446_google_app_engine_paypal_paypal_sandbox_python.txt
Q: How to distribute MongoDB test data over VCS? I'm working on a Python/MongoDB project in both my computer at home and my laptop. The schema in document stores, naturally, is best represented by the data itself - and that's why I want to distribute my test data over Mercurial, together with the code itself. Would t...
How to distribute MongoDB test data over VCS?
I'm working on a Python/MongoDB project in both my computer at home and my laptop. The schema in document stores, naturally, is best represented by the data itself - and that's why I want to distribute my test data over Mercurial, together with the code itself. Would the best way be to simply dump the BSONs in a file a...
[ "Dumping BSON and putting it into a VCS would not make much sense, since it's binary file and can't be viewed easily.\nYou can export a collection to a JSON, by using mongoexport tool. You can even pass it a query filter to limit number of exported documents.\nHere's an example (reformatted for readability):\nsergi...
[ 0 ]
[]
[]
[ "dvcs", "mercurial", "mongodb", "nosql", "python" ]
stackoverflow_0008693182_dvcs_mercurial_mongodb_nosql_python.txt
Q: Web application: Hold large object between requests I'm working on a web application related to genome searching. This application makes use of this suffix tree library through Cython bindings. Objects of this type are large (hundreds of MB up to ~10GB) and take as long to load from disk as it takes to process the...
Web application: Hold large object between requests
I'm working on a web application related to genome searching. This application makes use of this suffix tree library through Cython bindings. Objects of this type are large (hundreds of MB up to ~10GB) and take as long to load from disk as it takes to process them in response to a page request. I'm looking for a way to...
[ "I would suggest writing a small Flask (or even raw WSGI… But it's probably simpler to use Flask, as it will be easier to get up and running quickly) application which loads the genome database then exposes a simple API. Something like this:\napp = Flask(__name__)\ndatabase = load_database()\n\n@app.route('/get_gen...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0008696069_python.txt
Q: Check if python dictionary contains value and if so return related value I have a list of dicts, which contain filenames and modification dates in the following format: fileList = [{"fileName": "file1.txt", "fileMod": "0000048723"}, {"fileName": "file2.txt", "fileMod": "0000098573"}] I need to query ...
Check if python dictionary contains value and if so return related value
I have a list of dicts, which contain filenames and modification dates in the following format: fileList = [{"fileName": "file1.txt", "fileMod": "0000048723"}, {"fileName": "file2.txt", "fileMod": "0000098573"}] I need to query if a fileName exists in the dictionary and if so return the fileMod value for ...
[ "Using a list comprehension:\nfileMod = [item['fileMod'] for item in fileList if item['fileName'] == filename]\n\n", "You can use lambda with filter.\n>>> fileList = [{\"fileName\": \"filename1.typ\", \"fileMod\": \"0000000001\"}, {\"fileName\": \"filename2.typ\", \"fileMod\": \"0000000002\"}]\n>>> filter(lambda ...
[ 6, 3, 3, 2, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008695177_dictionary_python.txt
Q: Is matplotlib really only available for power pc OS X? The latest matplotlib download page only shows OS X 10.3 download options for mac. Wikipedia claims OS X 10.3 is Power PC only. It seems strange to me that there is no option for downloading matplotlib for Intel based macs. Is this correct? A: Matplotlib...
Is matplotlib really only available for power pc OS X?
The latest matplotlib download page only shows OS X 10.3 download options for mac. Wikipedia claims OS X 10.3 is Power PC only. It seems strange to me that there is no option for downloading matplotlib for Intel based macs. Is this correct?
[ "Matplotlib installation is a tricky beast and althought I have it installed in my python2.6 environment I cannot replicated that success (yet) under a new python2.7 (using virtualenv). So Far:\n\nusing the \"10.3\" dmg as suggested above appeared to install properly but throws an unknown architecture error when tr...
[ 1, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008696038_matplotlib_python.txt
Q: SDL/Pygame failing to load PNG images with cx_Freeze I'm running Python 3.1 on Windows and I'm trying to distribute my Pygame script as an executable via cx_Freeze. Right now it seems to be working except that the exe build can't load any of my images: Cannot load image: C:\path\to\build\exe.win32-3.1\resources\im...
SDL/Pygame failing to load PNG images with cx_Freeze
I'm running Python 3.1 on Windows and I'm trying to distribute my Pygame script as an executable via cx_Freeze. Right now it seems to be working except that the exe build can't load any of my images: Cannot load image: C:\path\to\build\exe.win32-3.1\resources\image.png File is not a Windows BMP file Googling has revea...
[ "I encountered the same issue many times, but I found out how to deal with it.\nThe problem \nIt seems that there is a conflict between two possible dependencies. The file jpeg.dll is included from the JRE (on Windows, something like C:\\Program Files\\Java\\jre6\\bin\\), but it is the wrong one. It should be inclu...
[ 2, 1 ]
[]
[]
[ "cx_freeze", "pygame", "python", "sdl" ]
stackoverflow_0002883237_cx_freeze_pygame_python_sdl.txt
Q: Creating Objects with variable object names from a mysql database I am trying to create objects with variable names, when I print out my objectname variable the correct name is assigned to it. But when i try and create an object using the objectname variable, the object created is literally called "objectname", no...
Creating Objects with variable object names from a mysql database
I am trying to create objects with variable names, when I print out my objectname variable the correct name is assigned to it. But when i try and create an object using the objectname variable, the object created is literally called "objectname", not using the string assigned to the variable. My code is below: class Cu...
[ "Each objectname should be added to a namespace so that the objects they refer to can be easily accessed later.\nThe simplest way to do this is to use a dictionary:\ncustomers = {}\nfor record in result: \n objectname = 'Customer' + str(record[0])\n customers[objectname] = Customer(str(record[1]))\ncustomerco...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008681802_python.txt
Q: Exposing passwords in django For a git repository that is shared with others, is it a vulnerability to expose your database password in the settings.py file? (My initial thought was no, since you still need the ssh password.) A: It depends on who has read access to the repository, but it's generally a good idea ...
Exposing passwords in django
For a git repository that is shared with others, is it a vulnerability to expose your database password in the settings.py file? (My initial thought was no, since you still need the ssh password.)
[ "It depends on who has read access to the repository, but it's generally a good idea not to put passwords into version control. It's probably better to put it in a seperate file like password.py with only the password in it, like this:\npassword = 'asdasd'\n\nand import or execfile this in your settings.py. You can...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008696469_django_python.txt
Q: Image Cropping using Python I am new to Python coding and I am writing a program in which I will be cropping an entered image and then saving it in a location. Now, I am being able to do this using a combination of PIL and pygame. But the problem is that, when I am selecting the image from the open pygame window, ...
Image Cropping using Python
I am new to Python coding and I am writing a program in which I will be cropping an entered image and then saving it in a location. Now, I am being able to do this using a combination of PIL and pygame. But the problem is that, when I am selecting the image from the open pygame window, the selection area is totally opa...
[ "I took a quick look and fixed a few other problems along the way. Essentially my changes do this:\n\nDraw the bounding box on a temporary image, set its alpha transparency, and then blit this over top of the main image.\nAvoid extraneous drawing cycles (when the mouse isn't moving, no sense in drawing the same ima...
[ 13, 1 ]
[]
[]
[ "crop", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0006136588_crop_image_processing_python_python_imaging_library.txt
Q: Python 3.2.1: exec('x = y()') sets a value in a toy example, but not in the full code I'm using an exec() statement to set a value, like so: foo = 3 def return_4(): return 4 instruction = 'foo = return_4()' exec(instruction) # <---- WHERE THE MAGIC HAPPENS print(foo) This comes out as 4, a...
Python 3.2.1: exec('x = y()') sets a value in a toy example, but not in the full code
I'm using an exec() statement to set a value, like so: foo = 3 def return_4(): return 4 instruction = 'foo = return_4()' exec(instruction) # <---- WHERE THE MAGIC HAPPENS print(foo) This comes out as 4, as I expect. My program has operations for manipulating a Rubik's cube. In this stripped do...
[ "On Python 2.x, exec was a statement that changed variable lookup from LOAD_GLOBAL and LOAD_FAST to LOAD_NAME to every name you access on your function.\nThat means it first search the local scope to see if can find the name to after check the global scope.\nNow, on Python 3.x, the exec function cannot change this ...
[ 5, 3 ]
[]
[]
[ "exec", "python", "rubiks_cube" ]
stackoverflow_0008696602_exec_python_rubiks_cube.txt
Q: Remove default "Python" submenu with Tkinter Menu on Mac OSX When creating a Menu in Tkinter on Mac OSX, the very first submenu is labeled "Python". Is there a way to remove this so that the only submenus are the ones that I have created or does that submenu always exist no matter what? Here is how I'm creating m...
Remove default "Python" submenu with Tkinter Menu on Mac OSX
When creating a Menu in Tkinter on Mac OSX, the very first submenu is labeled "Python". Is there a way to remove this so that the only submenus are the ones that I have created or does that submenu always exist no matter what? Here is how I'm creating my menu root = self.winfo_toplevel() self.menu = Menu(root) root['m...
[ "The only way I've been able to rename the first Menu title is to compile the python to an application. I did this using py2app.\nI have an example app you can see here:\nhttps://bitbucket.org/jgrigonis/mathfacts/overview\nThe key code is in this file:\nhttps://bitbucket.org/jgrigonis/mathfacts/src/b994b6225743/se...
[ 5 ]
[]
[]
[ "macos", "menu", "python", "tkinter" ]
stackoverflow_0008695926_macos_menu_python_tkinter.txt
Q: How to best deal with this Python numerical error? I have this code that throws a math domain error exception: v = -1.0 for i in range (201): print acos (v) v += 0.01 But if I change it to this, it works: v = -100 for i in range (201): print acos (v / 100.0) v += 1 Is this because of rounding? ...
How to best deal with this Python numerical error?
I have this code that throws a math domain error exception: v = -1.0 for i in range (201): print acos (v) v += 0.01 But if I change it to this, it works: v = -100 for i in range (201): print acos (v / 100.0) v += 1 Is this because of rounding? How to best solve this in Python? Or should I just do it...
[ "If you do:\n>>> format(0.01, '.30f')\n'0.010000000000000000208166817117'\n\nyou can see that 0.01 (as a floating point number with double precision) is bigger than the number 0.01 you learned at school.\nSo, when you sum it 100 times, the error gets bigger:\n>>> sum([0.01]*100)\n1.0000000000000007\n\nAnd that's en...
[ 8, 1 ]
[]
[]
[ "floating_point", "math", "python" ]
stackoverflow_0008696676_floating_point_math_python.txt
Q: Python class inheritance Happy new years guys! I'm new to Python and have been experimenting with class inheritance. I created the code below and have a few questions - Why is shDate3 of type numpy.datetime64 instead of SHDate3? shDate seems to be of type SHDate, which is the behavior I was expecting. Why can't s...
Python class inheritance
Happy new years guys! I'm new to Python and have been experimenting with class inheritance. I created the code below and have a few questions - Why is shDate3 of type numpy.datetime64 instead of SHDate3? shDate seems to be of type SHDate, which is the behavior I was expecting. Why can't shDate2 be created? I'm receivi...
[ "Quick answers:\n\nMake sure you know when you should use either type or isinstance, they are different. You may want to take a look at this question, it clarifies type and isinstance usage.\nYou shouldn't be using __init__ to custom your date class, because it is an immutable class. This question provides some dis...
[ 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0008696312_class_python.txt
Q: How to return nested dictionary to a Mako template in Pyramid? When I tried to return a nested dictionary to Mako template, it replaces single quotes with HTML code &#39; (I saw it in browser's source code). In views: @view_config(route_name='main', renderer='myproj:templates/main.mako') def main_view(request): ...
How to return nested dictionary to a Mako template in Pyramid?
When I tried to return a nested dictionary to Mako template, it replaces single quotes with HTML code &#39; (I saw it in browser's source code). In views: @view_config(route_name='main', renderer='myproj:templates/main.mako') def main_view(request): info = {'name': 'Some', 'age': 20} return {'info': info, 'cou...
[ "Mako is configured by default to escape strings. If you want to disable the filters this can be done via |n. Specifically ${info|n}.\nIn your example, however, you are trying to pass a python dictionary to a javascript function. This obviously doesn't add up and you need to turn the python dict into something usab...
[ 8 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008684156_pyramid_python.txt
Q: Automate Java applet with Python At work I need to run a Java applet every 20-30 min to re-connect to one of the internal applications. I would like to automate the login in the website of this application and then run this Java applet that does not require any input at all, just accept it so I can just run the s...
Automate Java applet with Python
At work I need to run a Java applet every 20-30 min to re-connect to one of the internal applications. I would like to automate the login in the website of this application and then run this Java applet that does not require any input at all, just accept it so I can just run the script every time the application logs ...
[ "A web application testing framework would be useful for what you ask, it allows you to simulate the interactions of an user (POST, GET, login, clicks, etc.) with a web site.\nThe tricky part of your question, is interacting with a Java applet - not many webapp testing frameworks will allow you to do that; in parti...
[ 1 ]
[]
[]
[ "applet", "automation", "python" ]
stackoverflow_0008696915_applet_automation_python.txt
Q: How to setup PyDev's python interpreter in eclipse using pip within a virtualenv I want to use pip to install new packages and they say to install pip in a virtualenv. I did that and installed some packages and use them no problem. But I have a problem setting up the simple google app engine helloworld app under ...
How to setup PyDev's python interpreter in eclipse using pip within a virtualenv
I want to use pip to install new packages and they say to install pip in a virtualenv. I did that and installed some packages and use them no problem. But I have a problem setting up the simple google app engine helloworld app under PyDev using python2.7. I set it up to use C:\Python27\env\Scripts\python.exe. But runn...
[ "I did some research on the google-appengine-python group and they say to go with option 3: Don't listen to the pip advice when using it with google appengine. appengine does not play nice with virtualenv.\nRefs:\nAppengine with virtualenv\nStrange imports (and WARNINGs) in development server\n" ]
[ 3 ]
[]
[]
[ "eclipse", "pip", "pydev", "python", "virtualenv" ]
stackoverflow_0008694741_eclipse_pip_pydev_python_virtualenv.txt
Q: Using a sublist to retrieve data from a larger list This is similar to this question with the answer: search = 'a' [item[1] for item in data if item[0] == search] ['x'] I modified it to extract all information associated with the search item: [item[1:] for item in data if item[0] == 'aa90_273024'] returns - [('F5...
Using a sublist to retrieve data from a larger list
This is similar to this question with the answer: search = 'a' [item[1] for item in data if item[0] == search] ['x'] I modified it to extract all information associated with the search item: [item[1:] for item in data if item[0] == 'aa90_273024'] returns - [('F5XKBWO01AQCVH', 'F5XKBWO01AQCVH')] Original list entry: [...
[ "I'm not quite sure what you're asking, but here is a solution for what I've understood:\nsearches = ('aa90_273024', 'another_search', 'yet_another_search')\nmy_result = [item[1:] for item in data if item[0] in searches]\n\n" ]
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008697150_list_python.txt
Q: Foursquare Oauth with Python I'm trying to figure out Foursquare's OAuth so I can have a user sign into my app. So far I found this tutorial: http://pkarl.com/articles/connect-foursquare-api-oauth-python/ Unfortunately, it doesn't work. I got the same error message the commenters were getting. If anyone knows wha...
Foursquare Oauth with Python
I'm trying to figure out Foursquare's OAuth so I can have a user sign into my app. So far I found this tutorial: http://pkarl.com/articles/connect-foursquare-api-oauth-python/ Unfortunately, it doesn't work. I got the same error message the commenters were getting. If anyone knows what the tutorial did wrong or knows ...
[ "Okay, I figured it out. Instead, I used this: http://github.com/wiseman/foursquare-python/tree/16138f7be20ec9ab6b58315dad9ee9765e73bb84\nI already had the user_key and user_secret on hand, so it was just a matter of a few lines:\nimport foursquare\nimport oauth\ncredentials = foursquare.OAuthCredentials(consumer_k...
[ 1, 1 ]
[]
[]
[ "foursquare", "oauth", "python" ]
stackoverflow_0003290739_foursquare_oauth_python.txt
Q: What's the most elegant way to write this for loop in Python? Basically I want to go from -1 to 1 in n steps, including -1 and 1: x = -1.0 n = 21 for i in range(n): print x x += 0.01 -1.0 -0.9 -0.8 ... 0.8 0.9 1.0 How can I write this in the most elegant, simplest way for any n value? A: There is no b...
What's the most elegant way to write this for loop in Python?
Basically I want to go from -1 to 1 in n steps, including -1 and 1: x = -1.0 n = 21 for i in range(n): print x x += 0.01 -1.0 -0.9 -0.8 ... 0.8 0.9 1.0 How can I write this in the most elegant, simplest way for any n value?
[ "There is no built-in solution, but probably a good way to solve it is to define your own range function:\ndef my_range(start, end, how_many):\n incr = float(end - start)/(how_many - 1)\n return [start + i*incr for i in range(how_many)]\n\nAnd you can use it in a for-loop:\n>>> for i in my_range(-1, 1, 10):\n...
[ 11, 11, 5, 3, 2 ]
[]
[]
[ "for_loop", "loops", "math", "python" ]
stackoverflow_0008697155_for_loop_loops_math_python.txt
Q: How can I mail decrypted 'current password' of a django user created How can I mail a decrypted 'current password' to a django user just created. eg I create a customer by inheriting the User model. Hence the user name and password get saved. Once the customer details are entered and saved. While overriding the sa...
How can I mail decrypted 'current password' of a django user created
How can I mail a decrypted 'current password' to a django user just created. eg I create a customer by inheriting the User model. Hence the user name and password get saved. Once the customer details are entered and saved. While overriding the save function for the customer form I trigger the send_mail function to send...
[ "Sending raw password is a bad idea, it's not secure. If user forgets his password, reset password form should be used instead of finding raw password in mail inbox.\nTo answer your question I could suggest using form for getting raw password. If you'll have own form, you'll get access to all user-entered text, inc...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008697664_django_python.txt
Q: Identify what type of database object is in django I have a function where I pass an object from the Car column or an object from the Plane column. In this function, I'd like to do slightly different things depending on what column it came from. Essentially, I'd like to say something like if object.is_car: # d...
Identify what type of database object is in django
I have a function where I pass an object from the Car column or an object from the Plane column. In this function, I'd like to do slightly different things depending on what column it came from. Essentially, I'd like to say something like if object.is_car: # do something elif object.is_plane: # do something els...
[ "isinstance()\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008698017_django_python.txt
Q: Python threading, new thread gets stuck I'm trying to write a python application with a gui, and I'm having trouble with python's threading package. import pygtk pygtk.require('2.0') import gtk import threading import time class gui: def main(self): print "starting gui" gtk.main() class logic...
Python threading, new thread gets stuck
I'm trying to write a python application with a gui, and I'm having trouble with python's threading package. import pygtk pygtk.require('2.0') import gtk import threading import time class gui: def main(self): print "starting gui" gtk.main() class logic: def __call__(self): time.sleep(...
[ "I dealt with this problem for the longest of times, here's where you'll find a solution:\nhttp://faq.pygtk.org/index.py?req=show&file=faq20.006.htp\n" ]
[ 4 ]
[]
[]
[ "multithreading", "pygtk", "python", "user_interface" ]
stackoverflow_0008698175_multithreading_pygtk_python_user_interface.txt
Q: lxml.etree.XMLSyntaxError: htmlParseEntityRef: expecting ';' I'm trying to figure out the python lxml api, but am running into a peculiar problem. I've installed the following library versions: libxml2 : 2.7.8 libxslt : 1.1.26 When I run the following code: html = open('file.html', 'r') context = etree.iterpars...
lxml.etree.XMLSyntaxError: htmlParseEntityRef: expecting ';'
I'm trying to figure out the python lxml api, but am running into a peculiar problem. I've installed the following library versions: libxml2 : 2.7.8 libxslt : 1.1.26 When I run the following code: html = open('file.html', 'r') context = etree.iterparse(StringIO(html), events=("start", "end"), html='true') for event,...
[ "The problem is that the HTML is malformed. To solve this, you can use BeautifulSoup (it's able to parse this HTML) or sanitize the HTML before trying to parse it.\nThe problems I've found are:\n\nAmpersand should be escaped as an HTML entity in links: & => &amp;\nClosing td tag after first a tag has to be removed ...
[ 8, 4 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0008664488_lxml_python.txt
Q: Django ModelForm I want to add multiple video_id(videolinks) simultaneously wtih same title and category here is my form code please do some help class AddVideoViaLinkForm(forms.ModelForm): title = forms.CharField(required=True,min_length=1,max_length=200) video_id = forms.CharField(required=True,min_leng...
Django ModelForm
I want to add multiple video_id(videolinks) simultaneously wtih same title and category here is my form code please do some help class AddVideoViaLinkForm(forms.ModelForm): title = forms.CharField(required=True,min_length=1,max_length=200) video_id = forms.CharField(required=True,min_length=1,max_length=20) ...
[ "First of all Meta should belong to AddVideoViaLinkForm. In this class you can add save function which will do this for you:\ndef save(self):\n ids = self.cleaned_data['video_id'].split(\",\")# it depends what is your id separator\n title = self.cleaned_data['title']\n for id in ids:\n Videos.object...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0008698005_django_django_forms_python.txt
Q: list comprehension equivalent without producing a throwaway list Possible Duplicate: Is it Pythonic to use list comprehensions for just side effects? proper use of list comprehensions - python Python has the useful and elegant list comprehension syntax. However AFAIK it always produces a list. Sometimes I feel t...
list comprehension equivalent without producing a throwaway list
Possible Duplicate: Is it Pythonic to use list comprehensions for just side effects? proper use of list comprehensions - python Python has the useful and elegant list comprehension syntax. However AFAIK it always produces a list. Sometimes I feel the urge to use list comprehension just for its compactness and elegan...
[ "I don't now if you will find it elegant, but there is a consume recipe in the itertools docs that is very fast and will run an iterator to completion without building-up a list:\n>>> consume(some_func(x) for x in some_list if x>5)\n\n", "Use a genex to get the appropriate values to iterate over.\nfor i in (x for...
[ 10, 3, 2, 0 ]
[]
[]
[ "list_comprehension", "python", "syntax" ]
stackoverflow_0008698288_list_comprehension_python_syntax.txt
Q: In Python, how can I enforce a timeout for a function call that sometimes hangs? I'm using a Python spider to crawl the internet using a urllib2 OpenerDirector. The problem is that a connection will inevitably hang on an https address, apparently ignoring the timeout value. One solution would be to run it in a thr...
In Python, how can I enforce a timeout for a function call that sometimes hangs?
I'm using a Python spider to crawl the internet using a urllib2 OpenerDirector. The problem is that a connection will inevitably hang on an https address, apparently ignoring the timeout value. One solution would be to run it in a thread and then kill and restart the thread if it hangs. Apparently Python doesn't suppor...
[ "Another StackOverflow question is similar here. When I faced something similar, I found it easier to convert what I was doing into defining & calling functions, which can subsequently return a value upon a timeout event. This can actually open up more possibility by utilizing various return values.\nAnother answer...
[ 2, 0 ]
[]
[]
[ "freeze", "python", "python_2.6", "timeout", "urllib2" ]
stackoverflow_0008649801_freeze_python_python_2.6_timeout_urllib2.txt