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: pygtk - how update a gtk.liststore? http://img824.imageshack.us/i/capturadetelag.png/ how update a gtk.liststore? i mean get a random number every second on a column just like example, such as a download manager list, i'd like to have a simple example to know how this Liststore works for update the list, because i...
pygtk - how update a gtk.liststore?
http://img824.imageshack.us/i/capturadetelag.png/ how update a gtk.liststore? i mean get a random number every second on a column just like example, such as a download manager list, i'd like to have a simple example to know how this Liststore works for update the list, because i can't find a effective way to do somethi...
[ "You can iterate over the rows in a list store (for row in liststore:...) as well as over the columns (values) in each row (for col_value in row:...).\nFor simple, direct updates:\nrow_n = 0\ncol_n = 2\nliststore[row_n][col_n] = 'new value'\n\nOtherwise, you can update using a gtk.TreeIter (row_iter):\nliststore.se...
[ 10, 4 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003109684_pygtk_python.txt
Q: Exchange Oauth Request Token for Access Token fails Google API I am having trouble exchanging my Oauth request token for an Access Token. My Python application successfully asks for a Request Token and then redirects to the Google login page asking to grant access to my website. When I grant access I retrieve a 20...
Exchange Oauth Request Token for Access Token fails Google API
I am having trouble exchanging my Oauth request token for an Access Token. My Python application successfully asks for a Request Token and then redirects to the Google login page asking to grant access to my website. When I grant access I retrieve a 200 status code but exchanging this authorized request token for an ac...
[ "When you're exchanging for the access token, the oauth_verifier parameter is required. If you don't provide that parameter, then google will tell you that the token is invalid.\n" ]
[ 1 ]
[]
[]
[ "google_api", "oauth", "python" ]
stackoverflow_0002306984_google_api_oauth_python.txt
Q: How to save user's daily progress? I'm building an app where I'm trying to store the user's progress on a game. I want to be able to store the score of a player on a daily basis, and then retrieve the day's score when I look for the date. I wanted to store a dictionary in the database, with keys being the dates wh...
How to save user's daily progress?
I'm building an app where I'm trying to store the user's progress on a game. I want to be able to store the score of a player on a daily basis, and then retrieve the day's score when I look for the date. I wanted to store a dictionary in the database, with keys being the dates when the user played and the values being ...
[ "I think an easy way would be to create a db.Model to represent an entry in the dictionary you were originally thinking about. Just to sketch it out, what I mean is something similar to this:\nclass DailyProgress(db.Model):\n date = db.DateTimeProperty(auto_now_add=True)\n score = db.IntegerProperty()\n\nThen...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003110892_google_app_engine_python.txt
Q: Python: Get name of shoutcast/internet radio station from url I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please correct me if I'm wrong. For example: http://89.238.1...
Python: Get name of shoutcast/internet radio station from url
I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please correct me if I'm wrong. For example: http://89.238.146.142:7030 Has the title: "Ibiza Global Radio" How can i store thi...
[ "From a little curl, it seems to be using shoutcast protocol, so you're looking for an early line starting with icy-name:\n$ curl http://89.238.146.142:7030 | head -5\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent L...
[ 8 ]
[]
[]
[ "internet_radio", "python", "shoutcast" ]
stackoverflow_0003110494_internet_radio_python_shoutcast.txt
Q: write sorted results to file I have a simple function that sorts a dictionary: data = inputfile.readlines() lineData = sorted(data, key=len, reverse=True)[:3] Printing the output: print sorted(data, key=len, reverse=True)[:3] generates the expected result, however writing to file: outputfile.writelines sorted(da...
write sorted results to file
I have a simple function that sorts a dictionary: data = inputfile.readlines() lineData = sorted(data, key=len, reverse=True)[:3] Printing the output: print sorted(data, key=len, reverse=True)[:3] generates the expected result, however writing to file: outputfile.writelines sorted(data, key=len, reverse=True)[:3] ge...
[ "writelines is a method, you need to call it:\noutputfile.writelines(sorted(data, key=len, reverse=True)[:3])\n\nETA\nFunction open provides file handle which could be iterated over once. You do it in your do_something_with_input function, after the inputfile iterated over, iterator is exhausted. Which means any fu...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003110920_python.txt
Q: how to import Java class with Python using Eclipse? I'm trying to write Jython where the Python file imports classes from Java I'm using Eclipse with PyDev. My Python code looks like: from eclipsejavatest import eclipseJavaTest from eclipsejavatest import JavaClass class eclipsePyPrint(eclipseJavaTest): de...
how to import Java class with Python using Eclipse?
I'm trying to write Jython where the Python file imports classes from Java I'm using Eclipse with PyDev. My Python code looks like: from eclipsejavatest import eclipseJavaTest from eclipsejavatest import JavaClass class eclipsePyPrint(eclipseJavaTest): def eclipsepyMain(self): print "python main method"...
[ "I am also using Eclipse with Pydev. I wanted to call Java classes from a Java project in my workspace from a program inside a Jython project folder. I did NOT have to right click on the java package and set it as a pydev project. In my setup the java source folder would not show up when I tried to add it to the...
[ 2, 1, 0 ]
[]
[]
[ "eclipse", "import", "java", "jython", "python" ]
stackoverflow_0002878468_eclipse_import_java_jython_python.txt
Q: Do a search-and-replace across all files in a folder through python? I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it. I have several files in a folder that I want to do a search-and-r...
Do a search-and-replace across all files in a folder through python?
I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it. I have several files in a folder that I want to do a search-and-replace on, within all of them. I'd like to do it with a python script. ...
[ "Welcome to StackOverflow. Since you want to learn yourself (+1) I'll just give you a few pointers.\nCheck out os.walk() to get at all the files.\nThen iterate over each line in the files (for line in currentfile: comes in handy here).\nNow you need to know if you want a \"stupid\" replace (find/replace each foo ev...
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0003110469_python_scripting.txt
Q: FTP and python question Can someone help me. Why it is not working import ftplib import os def readList(request): machine=[] login=[] password=[] for line in open("netrc"): #read netrc file old=line.strip() line=line.strip().split() if old.st...
FTP and python question
Can someone help me. Why it is not working import ftplib import os def readList(request): machine=[] login=[] password=[] for line in open("netrc"): #read netrc file old=line.strip() line=line.strip().split() if old.startswith("machine"): machine....
[ "(Apart from the horrid indentation problems, which are presumably due to botched copy and paste otherwise you'd get syntax errors up the wazoo...!)...:\nScoping problem, first: connectFtp makes a local variable ftp so that variables goes away as soon as the function's done. Then upload tries using the variable, b...
[ 0, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0003111038_ftp_ftplib_python.txt
Q: Django import problem with models.py and multiple ManyToManyFields() I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page. Each problem can be associated with multiple ...
Django import problem with models.py and multiple ManyToManyFields()
I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page. Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this...
[ "You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.\n", "Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.\nclass Problem(models.Model):\n name = models.Ch...
[ 2, 1 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0003110944_django_python_web_applications.txt
Q: Python performance: Try-except or not in? In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn't there, it has to call another method to make the value associated with that key. I currently have this impleme...
Python performance: Try-except or not in?
In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn't there, it has to call another method to make the value associated with that key. I currently have this implemented as follows, where findCrackDepth(tonnage) ...
[ "It's a delicate problem to time this because you need care to avoid \"lasting side effects\" and the performance tradeoff depends on the % of missing keys. So, consider a dil.py file as follows:\ndef make(percentmissing):\n global d\n d = dict.fromkeys(range(100-percentmissing), 1)\n\ndef addit(d, k):\n d[k] =...
[ 14, 3, 2, 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0003111195_performance_python.txt
Q: Which of these is a good way to request an API? Whenever looking at API libraries for Python, there seems to be about half of them simply using: response = urllib2.urlopen('https://www.example.com/api', data) and about half using: connection = httplib.HTTPSConnection('www.example.com/api') # ... rest omitted for ...
Which of these is a good way to request an API?
Whenever looking at API libraries for Python, there seems to be about half of them simply using: response = urllib2.urlopen('https://www.example.com/api', data) and about half using: connection = httplib.HTTPSConnection('www.example.com/api') # ... rest omitted for simplicity I tend to think the second version is "co...
[ "Yep, urllib2 uses HTTPSConnection (or whatever kind of connection is appropriate for the protocol) in its implementation. It's basically just a shortcut to do the most common thing people do with httplib.\nurllib2 also has some code to handle things like redirects and authentication requests, all stuff you might h...
[ 4 ]
[]
[]
[ "api", "python", "urlopen" ]
stackoverflow_0003112452_api_python_urlopen.txt
Q: Python - merging many url's and parsing them Below is script that I found on forum, and it is almost exactly what I need except I need to read like 30 different url's and print them all together.I have tried few options but script just breaks. How can I merge all 30's urls, parse, and than print them out. If you c...
Python - merging many url's and parsing them
Below is script that I found on forum, and it is almost exactly what I need except I need to read like 30 different url's and print them all together.I have tried few options but script just breaks. How can I merge all 30's urls, parse, and than print them out. If you can help me I would be very greatful, ty. import sy...
[ "If this is standard RSS, I'd encourage to use http://www.feedparser.org/ ; extracting all items there is straightforward. \n", "You are overwriting var_item, var_title, var_date. each loop. Make a list of these items, and put each var_item, var_title, var_date in the list. At the end, just print out your list.\n...
[ 0, 0 ]
[]
[]
[ "python", "rss", "urlopen", "xml" ]
stackoverflow_0003112548_python_rss_urlopen_xml.txt
Q: Where can I get Twisted ? Official site seems hacked the official site of Twisted is down (parked by advertisment). I just bought a book about Twisted Network Programming Essentials. Chapter 1 is getting Twisted and setting it up. But with the site down, I don't find where to download Twisted and get extra docs ab...
Where can I get Twisted ? Official site seems hacked
the official site of Twisted is down (parked by advertisment). I just bought a book about Twisted Network Programming Essentials. Chapter 1 is getting Twisted and setting it up. But with the site down, I don't find where to download Twisted and get extra docs about it. Could somebody point me to a mirror ?
[ "You could download it from pypi:\nhttp://pypi.python.org/pypi/Twisted\n", "Ok so thanks to the people at linuxfr.org and on twisted irc channel, we now know we can access the site from http://66.35.39.65/trac/ and that the site will be back shortly. Thanks everyone.\n", "The official site was not \"hacked\", i...
[ 0, 0, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003110025_python_twisted.txt
Q: os.path.exists() lies I'm running a number of python scripts on a linux cluster, and the output from one job is generally the input to another script, potentially run on another node. I find that there is some not insignificant lag before python notices files that have been created on other nodes -- os.path.exists...
os.path.exists() lies
I'm running a number of python scripts on a linux cluster, and the output from one job is generally the input to another script, potentially run on another node. I find that there is some not insignificant lag before python notices files that have been created on other nodes -- os.path.exists() returns false and open()...
[ "os.path.exists() just calls the C library's stat() function. \nI believe you're running into a cache in the kernel's NFS implementation. Below is a link to a page that describes the problem as well as some methods to flush the cache.\n\nFile Handle Caching\nDirectories cache file names to file handles mapping. ...
[ 16, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003112546_python.txt
Q: Making Python sockets visible for outside world? i already have a post which is quite similiar, but i am getting more and more frustrated because it seems nothing is wrong with my network setup. Other software can be seen from the outside (netcat listen servers etc.) but not my scripts.. How can this be?? Note: I...
Making Python sockets visible for outside world?
i already have a post which is quite similiar, but i am getting more and more frustrated because it seems nothing is wrong with my network setup. Other software can be seen from the outside (netcat listen servers etc.) but not my scripts.. How can this be?? Note: It works on LAN but not over the internet. Server: impo...
[ "Edited again to add:\nI think you may be missing some basics on socket communication. In order for sockets to work, you need to ensure that the sockets on both your client and server will meet. With your latest revision, your server is now bound to port 63001, but on the local loopback adapter: 127.0.0.1\nComputer...
[ 9, 1 ]
[]
[]
[ "client", "python", "sockets" ]
stackoverflow_0003112980_client_python_sockets.txt
Q: Determine MP3 bit depth in Python via Mutagen Is there a way to determine an MP3 file's encoded bit depth (ie 8, 16, 24, 32) in Python using the Mutagen library? A: The transformations done by the MP3 encoding process drop completely the concept of “bit depth”. You can only know the bit depth of the source audi...
Determine MP3 bit depth in Python via Mutagen
Is there a way to determine an MP3 file's encoded bit depth (ie 8, 16, 24, 32) in Python using the Mutagen library?
[ "The transformations done by the MP3 encoding process drop completely the concept of “bit depth”. You can only know the bit depth of the source audio if such information was stored in a tag of the MP3 file. Otherwise, you can take the MP3 data and produce 8-bit, 16-bit or 24-bit audio.\n", "I've not heard \"bit d...
[ 4, 0 ]
[]
[]
[ "lame", "mp3", "mutagen", "python" ]
stackoverflow_0002909605_lame_mp3_mutagen_python.txt
Q: Path in variable How can I add letter to path? For example if i have a path like 'c:\example2\media\uploads\test5.txt' (stored in a variable), but I need something like r'c:\example2\media\uploads\test5.txt', how can I add letter `r? Because the function open() does not want to open the first path. When I try add ...
Path in variable
How can I add letter to path? For example if i have a path like 'c:\example2\media\uploads\test5.txt' (stored in a variable), but I need something like r'c:\example2\media\uploads\test5.txt', how can I add letter `r? Because the function open() does not want to open the first path. When I try add path to function open(...
[ "From the error message it is clear that the string is stored in the correct format (backslashes are escaped by doubling). So it seems the path is wrong, and the file is indeed absent.\nOn the other hand, in your second example that you added in your edit, you use open('c:\\example2\\media\\uploads\\test5.txt') - t...
[ 6, 2, 0 ]
[]
[]
[ "python", "string", "variables" ]
stackoverflow_0003113095_python_string_variables.txt
Q: Of web service implementation I am trying to implement a small, very flexible REST web service. I've done it in the past, but I didn't like the approach and I still don't like. How can one parse the query variables in a more elegant way ? Doing things like: if query_variable in uri: do_things_based_on_query_variab...
Of web service implementation
I am trying to implement a small, very flexible REST web service. I've done it in the past, but I didn't like the approach and I still don't like. How can one parse the query variables in a more elegant way ? Doing things like: if query_variable in uri: do_things_based_on_query_variable look fairly ugly to me, especial...
[ "Have you looked at Routes?\n" ]
[ 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003113188_python_web_services.txt
Q: Linking using OpenMp with ctypes I have a c99 function that uses openmp, which works as expected. I also wrote a python interface using ctypes which causes the problem. Ctypes/python can not find the library for openmp. Here is the error message: File "foo.py", line 2, in <module> foobar=cdll.LoadLibrary("./li...
Linking using OpenMp with ctypes
I have a c99 function that uses openmp, which works as expected. I also wrote a python interface using ctypes which causes the problem. Ctypes/python can not find the library for openmp. Here is the error message: File "foo.py", line 2, in <module> foobar=cdll.LoadLibrary("./libfoo.so") File "/usr/lib/python2.6/c...
[ "Try adding -lgomp option in order to link with openmp library. From here.\n" ]
[ 3 ]
[]
[]
[ "c", "ctypes", "linux", "openmp", "python" ]
stackoverflow_0003111810_c_ctypes_linux_openmp_python.txt
Q: Optimize algorithm for creating a list of items rated together, in Python given a list of purchase events (customer_id,item) 1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws i'm trying to build a data structure that tells how many times an item was bought with another item. ...
Optimize algorithm for creating a list of items rated together, in Python
given a list of purchase events (customer_id,item) 1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws i'm trying to build a data structure that tells how many times an item was bought with another item. Not bought at the same time, but bought since I started saving data. the result...
[ "Do you really need to precompute all the possible pairs? What if you were to do it lazily, i.e. on an on-demand basis?\nThis can be represented as a 2D matrix. The rows correspond to the customers and the columns correspond to the products.\nEach entry is either 0 or 1, saying whether the product corresponding to ...
[ 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "optimization", "python", "similarity" ]
stackoverflow_0003109755_algorithm_optimization_python_similarity.txt
Q: Python subprocess Help I'm testing python subprocess and I keep getting this error: $ python subprocess-test.py Traceback (most recent call last): File "subprocess-test.py", line 3, in <module> p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd...
Python subprocess Help
I'm testing python subprocess and I keep getting this error: $ python subprocess-test.py Traceback (most recent call last): File "subprocess-test.py", line 3, in <module> p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/roaksoax/Des...
[ "Wild guess: you have your own file called subprocess.py which is masking the standard library module.\nWhat do you see with this?:\nimport subprocess\nprint subprocess.__file__\n\nThis will show what file is being imported as subprocess.\n" ]
[ 27 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003113544_python_subprocess.txt
Q: PHP vs. Other Languages in Hadoop/MapReduce implementations, and in the Cloud generally I'm beginning to learn some Hadoop/MapReduce, coming mostly from a PHP background, with a little bit of Java and Python. But, it seems like most implementations of MapReduce out there are in Java, Ruby, C++ or Python. I've lo...
PHP vs. Other Languages in Hadoop/MapReduce implementations, and in the Cloud generally
I'm beginning to learn some Hadoop/MapReduce, coming mostly from a PHP background, with a little bit of Java and Python. But, it seems like most implementations of MapReduce out there are in Java, Ruby, C++ or Python. I've looked, and it looks like there are some Hadoop/MapReduce in PHP, but the overwhelming body of ...
[ "PHP is designed primarily as a language for displaying output to a browser. Most jobs being run on MapReduce/Hadoop clusters have nothing to do with displaying output.\nThey instead tend to lean much more heavily towards data processing. PHP is not the most commonly supported language for data processing, by far. ...
[ 10, 2, 1 ]
[]
[]
[ "hadoop", "java", "mapreduce", "php", "python" ]
stackoverflow_0003113573_hadoop_java_mapreduce_php_python.txt
Q: Update datastore in Google App Engine from the iPhone I'm working on an app that communicates with Google App Engine to update and retrieve user information, but I can't think of a way to modify elements in the datastore. For example, every user for my app is represented by a User object in the datastore. If this ...
Update datastore in Google App Engine from the iPhone
I'm working on an app that communicates with Google App Engine to update and retrieve user information, but I can't think of a way to modify elements in the datastore. For example, every user for my app is represented by a User object in the datastore. If this user inputs things like email, phone number, etc into field...
[ "Why not have the iPhone application communicate this information to app engine by making a simple HTTP request?\nSpecifically, I would do an HTTP POST to the server and include the relevant fields. Then your app engine request handler would simply store the information in the datastore.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "iphone", "java", "python" ]
stackoverflow_0003113734_google_app_engine_google_cloud_datastore_iphone_java_python.txt
Q: How can I know the name of the exception in C++? With Python, I could get the name of the exception easily as follows. run the code, i.e. x = 3/0 to get the exception from python "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError Modify the code i.e. try: x=3/0 except ZeroD...
How can I know the name of the exception in C++?
With Python, I could get the name of the exception easily as follows. run the code, i.e. x = 3/0 to get the exception from python "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something Is there any similar way t...
[ "While you can't easily ask for the name of the exception, if the exception derives from std::exception you can find out the specified reason it was shown with what():\ntry\n{\n ...\n}\ncatch (const std::exception &exc)\n{\n std::err << exc.what() << std::endl;\n}\n\nOn a side note, dividing by 0 is not guara...
[ 4, 1, 1, 1 ]
[]
[]
[ "c++", "exception_handling", "python" ]
stackoverflow_0003113929_c++_exception_handling_python.txt
Q: Python - Why the use of assert(required_param)? I found this today while looking at a library for an API . def my_function(self, required_param=None): assert(required_param) ... Do cool function stuff Wouldn't it be easier to do this: def my_function(self, required_param): ... Do cool function stuff ...
Python - Why the use of assert(required_param)?
I found this today while looking at a library for an API . def my_function(self, required_param=None): assert(required_param) ... Do cool function stuff Wouldn't it be easier to do this: def my_function(self, required_param): ... Do cool function stuff Or, am I missing something? The assert() of course gi...
[ "The only reason I can imagine for the situation you've described is to also reject False, 0, [], (,), etc. But that doesn't make sense to assert against the default value.\nIf the author wasn't intending to reject other false-ish values, then that assert is even more dubious.\n" ]
[ 2 ]
[]
[]
[ "assert", "assertions", "python" ]
stackoverflow_0003114016_assert_assertions_python.txt
Q: Spawning multiple browsers from Selenium RC utilizing Python I've been trying to develop an automated test case solution using Selenium RC and Python and after lengthy testing I've hit a pretty hard block in the road, so to speak. I have three files: unit.py, case1.py, and case1m.py unit.py configures instances o...
Spawning multiple browsers from Selenium RC utilizing Python
I've been trying to develop an automated test case solution using Selenium RC and Python and after lengthy testing I've hit a pretty hard block in the road, so to speak. I have three files: unit.py, case1.py, and case1m.py unit.py configures instances of case1m.py with a browser and a port, then runs the test by sendi...
[ "Looking at the 2 code snippets side by side, I think you have inverted the browser and port arguments. This is probably the source of your error.\ncase1.py (runs fine):\nself.selenium = selenium(\"localhost\", 4444, \"*chrome\", \"http://megagate-ffcdcb.xl_net.internal/\")\n\ncase1m.py (socket error):\nself.seleni...
[ 1 ]
[]
[]
[ "browser", "python", "selenium", "selenium_rc" ]
stackoverflow_0003112673_browser_python_selenium_selenium_rc.txt
Q: Classifying Documents into Categories I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've ...
Classifying Documents into Categories
I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've been exploring NLTK and its Naive Bayes Cla...
[ "You should start by converting your documents into TF-log(1 + IDF) vectors: term frequencies are sparse so you should use python dict with term as keys and count as values and then divide by total count to get the global frequencies.\nAnother solution is to use the abs(hash(term)) for instance as positive integer ...
[ 33, 11, 2 ]
[]
[]
[ "machine_learning", "naivebayes", "nlp", "nltk", "python" ]
stackoverflow_0003113428_machine_learning_naivebayes_nlp_nltk_python.txt
Q: wxPython App - Ensure All Dialogs are Destroyed I'm working on an application that will need to use a variety of Dialogs. I'm having trouble getting events bound in a way that ensures that my Dialogs are destroyed properly if someone closes the application before dismissing the dialogs. I would expect to use som...
wxPython App - Ensure All Dialogs are Destroyed
I'm working on an application that will need to use a variety of Dialogs. I'm having trouble getting events bound in a way that ensures that my Dialogs are destroyed properly if someone closes the application before dismissing the dialogs. I would expect to use something like this: class Form(wx.Dialog): def __init_...
[ "I was attempting to use event bubbling incorrectly. The solution is to make sure the Dialogs are children of the Top Level Window so that the Application exiting forces the Dialogs to destroy as well.\nclass Form(wx.Dialog):\n def __init__(self):\n wx.Dialog.__init__(MAIN_WINDOW, -1, \"Dialog\")\n self.Bind(wx....
[ 2 ]
[]
[]
[ "destructor", "event_handling", "python", "wxpython" ]
stackoverflow_0003112456_destructor_event_handling_python_wxpython.txt
Q: Is there a nice way to handle exceptions in Python? I have a bunch of code that looks similar to this: try: auth = page.ItemAttributes.Author except: try: auth = page.ItemAttributes.Creator ...
Is there a nice way to handle exceptions in Python?
I have a bunch of code that looks similar to this: try: auth = page.ItemAttributes.Author except: try: auth = page.ItemAttributes.Creator except: auth = None I...
[ "You can use hasattr to avoid the try/except blocks:\nauth = None\nfor attrname in ['Author', 'Creator']:\n if hasattr(page.ItemAttributes, attrname):\n auth = getattr(page.ItemAttributes, attrname)\n break\n\nAn alternate way to write the above is to use the else clause of a Python for loop:\nfor ...
[ 11, 3, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0003114246_exception_python.txt
Q: python/django unittest function override I have a time-consuming method with non-predefined number of iterations inside it that I need to test: def testmethod(): objects = get_objects() for objects in objects: # Time-consuming iterations do_something(object) One iteration is sufficient to ...
python/django unittest function override
I have a time-consuming method with non-predefined number of iterations inside it that I need to test: def testmethod(): objects = get_objects() for objects in objects: # Time-consuming iterations do_something(object) One iteration is sufficient to test for me. What is the best practice to test...
[ "Perhaps turn your method into\ndef my_method(self, objs=None):\n if objs is None:\n objs = get_objects()\n for obj in objs:\n do_something(obj)\n\nThen in your test you can call it with a custom objs parameter.\n", "Update:\nI misread the original question, so here's how I would solve the pro...
[ 2, 2 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0003114326_django_python_unit_testing.txt
Q: Call python function as if it were inline I want to have a function in a different module, that when called, has access to all variables that its caller has access to, and functions just as if its body had been pasted into the caller rather than having its own context, basically like a C Macro instead of a normal ...
Call python function as if it were inline
I want to have a function in a different module, that when called, has access to all variables that its caller has access to, and functions just as if its body had been pasted into the caller rather than having its own context, basically like a C Macro instead of a normal function. I know I can pass locals() into the f...
[ "And another, even uglier way to do it -- please don't do this, even if it's possible --\nimport sys\n\ndef insp():\n l = sys._getframe(1).f_locals\n expression = l[\"expression\"]\n ofs = expression.rfind(\".\")\n expofs = expression[:ofs]\n obj = eval(expofs, globals(), l)\n print \"The part of ...
[ 3, 2, 2, 2 ]
[]
[]
[ "inline", "namespaces", "python" ]
stackoverflow_0003114015_inline_namespaces_python.txt
Q: Calling a Python program from PHP I've got a version of the A* algorithm that builds a graph of the UK road and cycle network in Python lists. It takes about 30 seconds to initialise, but once done can very quickly find the shortest route between any two vertices. The start and finish vertex ids are provided by PH...
Calling a Python program from PHP
I've got a version of the A* algorithm that builds a graph of the UK road and cycle network in Python lists. It takes about 30 seconds to initialise, but once done can very quickly find the shortest route between any two vertices. The start and finish vertex ids are provided by PHP. I'm trying to work out the best way ...
[ "Easiest way that I can think of would be XMLRPC. Python makes it horribly easy to set up an XMLRPC server, and there's php_xmlrpc for bindings on the PHP side...\ndef calculate_path(v1, v2):\n return [v1, ..., v2]\n\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nserver = SimpleXMLRPCServer(('localhost', 9393...
[ 2, 0, 0, 0 ]
[]
[]
[ "ipc", "php", "python" ]
stackoverflow_0003114532_ipc_php_python.txt
Q: How do I parse a listing of files to get just the filenames in Python? So lets say I'm using Python's ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output. A: Using retrlin...
How do I parse a listing of files to get just the filenames in Python?
So lets say I'm using Python's ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.
[ "Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.\n", "This best answer\nYou may want to ...
[ 9, 8, 1, 1, 1, 1, 0 ]
[]
[]
[ "ftp", "ftplib", "parsing", "python", "scripting" ]
stackoverflow_0000237699_ftp_ftplib_parsing_python_scripting.txt
Q: mod_python and subpackages importing issues: ImportError: No module named I'm exploring mod_python and I'm having trouble with the package importing. I've a structure like this: my base dir | +- __init__.py +- index.py +- package (directory) | +- __init__.py +- pac...
mod_python and subpackages importing issues: ImportError: No module named
I'm exploring mod_python and I'm having trouble with the package importing. I've a structure like this: my base dir | +- __init__.py +- index.py +- package (directory) | +- __init__.py +- package.py (file) and an Apache Virtual Host like this: <VirtualHost *:80> ...
[ "Firstly, if you're just beginning with Python web deployment you should not be using mod_python. It is now officially a dead project and is deprecated. Use mod_wsgi instead.\nThe actual issue with your code is that you haven't put your root directory on the Python path, so mod_python doesn't know where to find it....
[ 3, 0, 0 ]
[]
[]
[ "apache", "mod_python", "python" ]
stackoverflow_0003109474_apache_mod_python_python.txt
Q: How to convert a Foreignkey field into ManyToMany field in Django? Possible Duplicate: Django data migration when changing a field to ManyToMany how I can accomplish this without losing data? someone know how to do that? thanks to all. A: Look at south
How to convert a Foreignkey field into ManyToMany field in Django?
Possible Duplicate: Django data migration when changing a field to ManyToMany how I can accomplish this without losing data? someone know how to do that? thanks to all.
[ "Look at south\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003114097_django_django_models_python.txt
Q: Google App Engine - headers[] and headers.add_header() for cache control What is the proper way to set cache control? Sometimes I see the use of headers[] self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response...
Google App Engine - headers[] and headers.add_header() for cache control
What is the proper way to set cache control? Sometimes I see the use of headers[] self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00" Other times, I see headers.ad...
[ "The difference is that using headers[] will overwrite previous values, while add_header won't.\nFrom the wsgiref.headers docs (referred to by the GAE docs), \"Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list.\"\n" ]
[ 10 ]
[]
[]
[ "google_app_engine", "header", "no_cache", "python" ]
stackoverflow_0003114803_google_app_engine_header_no_cache_python.txt
Q: What's a good swiss-army framework for the next 5 years? Basically, we want to use no flash, and eschew php where possible (for marketing reasons). Right now, I'm looking at Ruby on Rails and like what I see... but I'm not really a programmer, having working primarily with Wordpress, Drupal, and Joomla for the pas...
What's a good swiss-army framework for the next 5 years?
Basically, we want to use no flash, and eschew php where possible (for marketing reasons). Right now, I'm looking at Ruby on Rails and like what I see... but I'm not really a programmer, having working primarily with Wordpress, Drupal, and Joomla for the past 10 years. Our sites need to have a lot of custom apps built ...
[ "HTML5 \nWhile we can't predict the future, we could work in learning well the currently available technologies.\n", "I'd say python/Django over RoR. \nIf you weren't avoiding PHP, Zend would be a safe(ish) bet for the next 5 years (probably).\nMind you, you're by your own admission not a programmer and you're a...
[ 1, 1, 0 ]
[]
[]
[ "frameworks", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0003114788_frameworks_python_ruby_ruby_on_rails.txt
Q: Automatic task execution on google app engine development server (python) The docs for the python dev server say this about running tasks: When your app is running in the development server, task queues are not processed automatically. Instead, task queues accrue tasks which you can examine and execute fr...
Automatic task execution on google app engine development server (python)
The docs for the python dev server say this about running tasks: When your app is running in the development server, task queues are not processed automatically. Instead, task queues accrue tasks which you can examine and execute from the developer console... But the release notes for version 1.3.4 of the p...
[ "It seems the problem was that I was running the dev server with python 2.6 instead of 2.5. When using 2.5, everything worked.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "task" ]
stackoverflow_0003115053_google_app_engine_python_task.txt
Q: I have a serial Python application that takes hours to process, how can I decrease the time it takes to run? Could someone please post a few examples of multi-threaded python? I am searching all over the internet but cannot find a simple, easy-to-replicate tutorial. Simple examples are fine. I have written a progr...
I have a serial Python application that takes hours to process, how can I decrease the time it takes to run?
Could someone please post a few examples of multi-threaded python? I am searching all over the internet but cannot find a simple, easy-to-replicate tutorial. Simple examples are fine. I have written a program which takes a few hours to run serially--I am hoping I can bring it's run time down to minutes after multi-thre...
[ "I see you got a lot of examples, all so far from @Noctis, but I'm not sure how they're going to help you. Addressing your question more directly: the only way multithreading can speed your application up, in today's CPython, is if your slow-down is due in good part to \"blocking I/O\" operations, e.g. due to inte...
[ 6, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003114924_python.txt
Q: Python syntax for and/or'ing things together? I'm trying to devise a scheme for validating form fields. I've decided you can pass in a list of validators to each field like, Field(validators=[email_validator, required_validator]) But then I thought, what if you wanted to or the validators together, rather than an...
Python syntax for and/or'ing things together?
I'm trying to devise a scheme for validating form fields. I've decided you can pass in a list of validators to each field like, Field(validators=[email_validator, required_validator]) But then I thought, what if you wanted to or the validators together, rather than anding them? For example, a field that accepts either...
[ "Django solves this by using Q objects which can be combined using & and | to create more complex conditions. Mimicing what they use is probably an acceptable solution.\n", "What about a list whose items are either single validators, or list of validators to be anded together -- the top-level list does an or on a...
[ 4, 1, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003115170_python_syntax.txt
Q: How do i test django ratings in my application? I have installed django-ratings application in my django project. Am wondering how best can i test my app voting functionality because django ratings is only allowing me to vote once for the same user, object and Ip address. Is there a way i can disable this checks...
How do i test django ratings in my application?
I have installed django-ratings application in my django project. Am wondering how best can i test my app voting functionality because django ratings is only allowing me to vote once for the same user, object and Ip address. Is there a way i can disable this checks so that i can just insert votes, test my applicatio...
[ "You cannot 'disable' these checks because they're specified in the Vote model:\nunique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address'))\n\nYou could edit it but that'd be monkey-patching (and maybe would brake the app).\nConsider writing tests, or if you just want to have some votes filled j...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003109150_django_python.txt
Q: Creating multiple sites with django I have to create a project in django where the admin can create the sites dynamically and assign the administrators for the same, which would manage that particular site. Can someone please suggest with some hint on how it can be done? Thanks in advance. A: If you are already...
Creating multiple sites with django
I have to create a project in django where the admin can create the sites dynamically and assign the administrators for the same, which would manage that particular site. Can someone please suggest with some hint on how it can be done? Thanks in advance.
[ "If you are already familiar with django sites, extend the User profile and write a custom auth in a similar way as in this question: 1404131/how-to-get-unique-users-across-multiple-django-sites-powered-by-the-sites-frame\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003107434_django_python.txt
Q: Python write to file I've got a little problem here. I'm converting binary to ascii, in order to compress data. All seems to work fine, but when I convert '11011011' to ascii and try to write it into file, I keep getting error UnicodeEncodeError: 'charmap' codec can't encode character '\xdb' in position 0: charact...
Python write to file
I've got a little problem here. I'm converting binary to ascii, in order to compress data. All seems to work fine, but when I convert '11011011' to ascii and try to write it into file, I keep getting error UnicodeEncodeError: 'charmap' codec can't encode character '\xdb' in position 0: character maps to Here's my cod...
[ "I think you want:\nhandleR = open(self.getInput(), 'rb')\nhandleW = open(self.getOutput(), 'wb')\n\nThat will ensure you're reading and writing byte streams. Also, you can parse binary strings without eval:\nchar = chr(int(byte, 2))\n\nAnd of course, it would be faster to use bit manipulation. Instead of appendi...
[ 2 ]
[]
[]
[ "ascii", "binary", "python" ]
stackoverflow_0003115734_ascii_binary_python.txt
Q: python search from tag i need help with python programming: i need a command which can search all the words between tags from a text file. for example in the text file has <concept> food </concept>. i need to search all the words between <concept> and </concept> and display them. can anybody help please....... A:...
python search from tag
i need help with python programming: i need a command which can search all the words between tags from a text file. for example in the text file has <concept> food </concept>. i need to search all the words between <concept> and </concept> and display them. can anybody help please.......
[ "\nLoad the text file into a string.\nSearch the string for the first occurrence of <concept> using pos1 = s.find('<concept>')\nSearch for </concept> using pos2 = s.find('</concept>', pos1)\n\nThe words you seek are then s[pos1+len('<concept>'):pos2]\n", "There is a great library for HTML/XML traversing named Bea...
[ 3, 3, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003116195_parsing_python.txt
Q: Automate or send kepresses to application running in background with PyS60 I'm running PyS60 on a Nokia N95 phone, and I want to find a way of having my script interact with an application running in the background. I found this http://wiki.forum.nokia.com/index.php/How_to_simulate_a_keypress_in_PyS60 .. but it do...
Automate or send kepresses to application running in background with PyS60
I'm running PyS60 on a Nokia N95 phone, and I want to find a way of having my script interact with an application running in the background. I found this http://wiki.forum.nokia.com/index.php/How_to_simulate_a_keypress_in_PyS60 .. but it doesn't mention anything about sending the keypresses to a specific target. The re...
[ "You could use apptools to switch to a specific applications and then use the keypress module to emulate key presses.\n" ]
[ 1 ]
[]
[]
[ "automation", "keypress", "n95", "pys60", "python" ]
stackoverflow_0003091074_automation_keypress_n95_pys60_python.txt
Q: ide code information I've been annoyed lately by the fact that PyDev doesn't information about classes and function when it code completes wxPython code. Can anybody tell me FOSS IDE's or extensions that offer code information (function params, returns etc.) when it code completes for C/C++ and Python. I am a fan ...
ide code information
I've been annoyed lately by the fact that PyDev doesn't information about classes and function when it code completes wxPython code. Can anybody tell me FOSS IDE's or extensions that offer code information (function params, returns etc.) when it code completes for C/C++ and Python. I am a fan of CodeLite, Eclipse CDT a...
[ "Vim + Exuberant Ctags\nSee here, here and here for C++ autocompletion (also referred to as IntelliSense, taken from the name for Visual Studio's autocomplete).\nAnd here for Python autocomplete/\"intellisense\" for vim. (I should point out I found the link to that from this post on SO).\nIf that doesn't include th...
[ 2, 0 ]
[]
[]
[ "c", "c++", "code_completion", "ide", "python" ]
stackoverflow_0003101160_c_c++_code_completion_ide_python.txt
Q: How to split strings based on capitalization? Possible Duplicate: Python: Split a string at uppercase letters I'm trying to figure out how to change TwoWords into Two Words and I can't think of a way to do it. I need to split based on where it's capitalized, that will always be a new word. Does anyone have any s...
How to split strings based on capitalization?
Possible Duplicate: Python: Split a string at uppercase letters I'm trying to figure out how to change TwoWords into Two Words and I can't think of a way to do it. I need to split based on where it's capitalized, that will always be a new word. Does anyone have any suggestions? In python.
[ "You can use regular expressions to do this:\nimport re\nwords = re.findall('[A-Z][a-z]*', 'TheWords')\n\n", "You can use regular expressions:\nimport re\nre.findall(\"[A-Z][a-z]*\",\"TwoWordsAATest\")\n\nre.findall(\"[A-Z][^A-Z]*\",\"TwoWordsAATest\")\n\nhttp://docs.python.org/library/re.html\n" ]
[ 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003116363_python_string.txt
Q: I/O Reading from a file I'm using code like this: f = open('boo.txt') line = f.readline() print line f.close() How can I make it read a different line or a random line every time I open the script, instead of just printing out the first line? A: f = open('boo.txt') lines = [line for line in f] f.close() import ...
I/O Reading from a file
I'm using code like this: f = open('boo.txt') line = f.readline() print line f.close() How can I make it read a different line or a random line every time I open the script, instead of just printing out the first line?
[ "f = open('boo.txt')\nlines = [line for line in f]\nf.close()\nimport random\nselectedline = random.choice(lines)\nprint (selectedline)\n\n", "Another way with use of context managers:\nimport random\n\nwith open(\"boo.txt\", \"r\") as f:\n print random.choice(f.readlines()) \n\n", "f = open('boo.txt')\nimpo...
[ 6, 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003116487_python.txt
Q: How can I check if there exist any reverse element in list of dict without looping on it My list is like l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ] Is there any better way to check if any dictionary in the list is having reverse pair? A: I would suggest to transform the dictionaries in tuple and put the tuple in a set...
How can I check if there exist any reverse element in list of dict without looping on it
My list is like l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ] Is there any better way to check if any dictionary in the list is having reverse pair?
[ "I would suggest to transform the dictionaries in tuple and put the tuple in a set. And look in the set if the reverse tuple is in the set. That would have a complexity of O(n) instead of O(n^2).\n", "This code seems to work without loop:\nk1 = 'k1'\nk2 = 'k2'\nv1 = 'v1'\nv2 = 'v2'\nl1 = [ {k1:v1} , {k2:v2}, {v1:...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python", "reverse" ]
stackoverflow_0003116249_dictionary_list_python_reverse.txt
Q: Django form is throwing error: "takes exactly 1 argument (0 given)" I'm working on a basic event form created from a model, but I keep getting the following error message: TypeError at /addlaundry/ addlaundry() takes exactly 1 argument (0 given) I think it's because I'm not passing the argument through on views, ...
Django form is throwing error: "takes exactly 1 argument (0 given)"
I'm working on a basic event form created from a model, but I keep getting the following error message: TypeError at /addlaundry/ addlaundry() takes exactly 1 argument (0 given) I think it's because I'm not passing the argument through on views, but I can't find documented anywhere how to do this right, at least not w...
[ "The problem is here:\nform = addlaundry()\n\nYou're calling your view function addlaundry which takes 1 required argument (request), but you're not passing it any arguments.\nOf course, that's not the right way to construct a form, anyway. You'll want to take a look at the examples given in the Django forms docume...
[ 3, 1, 1, 1, 1 ]
[ "else:\n form = addlaundry()\n\nJust as the exception says: The view function needs 1 argument, but you didn't supply any.\n" ]
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0003105495_django_django_forms_python.txt
Q: Python FTP Most Recent File How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.lo...
Python FTP Most Recent File
How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.appe...
[ "Just to make some corrections:\ndate_str = ' '.join(line.split()[5:8])\ntime.strptime(date_str, '%b %d %H:%M') # import time\n\nAnd to find the most recent file\nfor line in data:\n col_list = line.split()\n date_str = ' '.join(line.split()[5:8])\n if datePattern.search(col_list[8]):\n file_dict[ti...
[ 4, 4, 2, 0 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0001335552_ftp_python.txt
Q: "Annotating" querysets with model function returns Basically I want to do something similar to annotating a queryset but with a call on a function in the model attached to the response. Currently I have something like: objs = WebSvc.objects.all().order_by('content_type', 'id') for o in objs: o.state = o.cast()...
"Annotating" querysets with model function returns
Basically I want to do something similar to annotating a queryset but with a call on a function in the model attached to the response. Currently I have something like: objs = WebSvc.objects.all().order_by('content_type', 'id') for o in objs: o.state = o.cast().get_state() where get_state() is a function in the mod...
[ "One way to do this, using python properties:\nclass WebSvc(models.Model):\n ...\n\n def _get_state():\n return self.cast().get_state()\n\n state = property(_get_state)\n\nAdvantages: will only run when the property is needed.\nPossible disadvantage: when you call the property multiple times, the we...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003117063_django_python.txt
Q: How to test jquery ajax tabs with selenium? I'm testing a django app with selenium, and one of my pages uses the jquery ui tabs element. One of the tabs contains a simple table listing some users, and is loaded via ajax. When using the app, the tab works just fine, but when automating the test with selenium, the t...
How to test jquery ajax tabs with selenium?
I'm testing a django app with selenium, and one of my pages uses the jquery ui tabs element. One of the tabs contains a simple table listing some users, and is loaded via ajax. When using the app, the tab works just fine, but when automating the test with selenium, the tab doesn't appear to load it's content! I'm writi...
[ "This could be a few things. It could be that Selenium is having trouble clicking the anchor but I actually haven't heard of that trouble and it sounds less likely. It sounds like the click() method returns OK, it doesn't give you \"element not found\", right? When you do the click the jquery tab javascript just is...
[ 5 ]
[]
[]
[ "django", "jquery_ui", "python", "selenium_rc", "unit_testing" ]
stackoverflow_0003114731_django_jquery_ui_python_selenium_rc_unit_testing.txt
Q: How can I ensure good test-coverage of my big Python proejct I have a very large python project with a very large test suite. Recently we have decided to quantify the quality of our test-coverage. I'm looking for a tool to automate the test coverage report generation. Ideally I'd like to have attractive, easy to ...
How can I ensure good test-coverage of my big Python proejct
I have a very large python project with a very large test suite. Recently we have decided to quantify the quality of our test-coverage. I'm looking for a tool to automate the test coverage report generation. Ideally I'd like to have attractive, easy to read reports but I'd settle for less attractive reports if I could...
[ "Have you tried using coverage.py? It underlies \"nose coverage\", but can be run perfectly well outside of nose if you need to.\nIf you run your tests with (hypothetically) python run_my_tests.py, then you can measure coverage with coverage run run_my_tests.py, then get HTML reports with coverage html.\nFrom your...
[ 4, 1 ]
[]
[]
[ "code_coverage", "python", "python_coverage", "unit_testing" ]
stackoverflow_0003117011_code_coverage_python_python_coverage_unit_testing.txt
Q: Sort a list of tuples without case sensitivity How can I efficiently and easily sort a list of tuples without being sensitive to case? For example this: [('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] Should look like this once sorted: [('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')] The regular lexicographic sort ...
Sort a list of tuples without case sensitivity
How can I efficiently and easily sort a list of tuples without being sensitive to case? For example this: [('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] Should look like this once sorted: [('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')] The regular lexicographic sort will put 'A' before 'a' and yield this: [('A', 'b'),...
[ "You can use sort's key argument to define how you wish to regard each element with respect to sorting:\ndef lower_if_possible(x):\n try:\n return x.lower()\n except AttributeError:\n return x\n\nL=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]\n\nL.sort(key=lambda x: map(lower_if_possible,x))\n...
[ 12, 2, 0, 0, 0 ]
[]
[]
[ "case_insensitive", "python", "sorting", "tuples" ]
stackoverflow_0002494740_case_insensitive_python_sorting_tuples.txt
Q: Is this use of isinstance pythonic/"good"? A side effect of this question is that I was lead to this post, which states: Whenever isinstance is used, control flow forks; one type of object goes down one code path, and other types of object go down the other --- even if they implement the same interface! and sugg...
Is this use of isinstance pythonic/"good"?
A side effect of this question is that I was lead to this post, which states: Whenever isinstance is used, control flow forks; one type of object goes down one code path, and other types of object go down the other --- even if they implement the same interface! and suggests that this is a bad thing. However, I've use...
[ "Not in general. An object's interface should define its behavior. In your example above, it would be better if other used a consistent interface:\ndef __iadd__(self, other):\n self.h += other.h\n self.m += other.m\n self.s += other.s\n\nEven though this looks like it is less functional, conceptually it is...
[ 7, 4, 2, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003111611_oop_python.txt
Q: Sending emails with sendmail doesn't work for large emails I'm using python's sendmail in the following way: msg = <SOME MESSAGE> s = smtplib.SMTP('localhost') s.sendmail(me, you, msg.as_string()) s.quit() This usually works fine (I.e I get the email) but it fails (I.e no exception is shown but the email just doe...
Sending emails with sendmail doesn't work for large emails
I'm using python's sendmail in the following way: msg = <SOME MESSAGE> s = smtplib.SMTP('localhost') s.sendmail(me, you, msg.as_string()) s.quit() This usually works fine (I.e I get the email) but it fails (I.e no exception is shown but the email just doesn't arrive) when the message is pretty big (around 200 lines). ...
[ "Who are you sending to? You should consider some email servers (such as Yahoo and Hotmail) quarantine incoming email for a period of time if the email is categorized as potential spam. Spamminess is going to be a function of the content, image to text ratio, nature of attachments, nature of html links, sending rat...
[ 2, 1, 0, 0 ]
[]
[]
[ "email", "python", "sendmail", "smtp" ]
stackoverflow_0003031528_email_python_sendmail_smtp.txt
Q: Conquering Complexity, Eckel on Java and Python and Chunk Theory In the introduction to Bruce Eckel's Thinking In Java, he says, in 1998: Programming is about managing complexity: the complexity of the problem you want to solve, laid upon the complexity of the machine in which it is solved. Because of thi...
Conquering Complexity, Eckel on Java and Python and Chunk Theory
In the introduction to Bruce Eckel's Thinking In Java, he says, in 1998: Programming is about managing complexity: the complexity of the problem you want to solve, laid upon the complexity of the machine in which it is solved. Because of this complexity, most of our programming projects fail. And yet, of a...
[ "\nBruce Eckel: They say you can hold\n seven plus or minus two pieces of\n information in your mind. I can't\n remember how to open files in Java.\n\nI can:\nnew FileInputStream(filename);\n\n\nI've written chapters on it. I've done\n it a bunch of times, but it's too many\n steps. And when I actually analyze...
[ 5, 5, 4, 3, 2 ]
[]
[]
[ "complexity_theory", "java", "python" ]
stackoverflow_0003113409_complexity_theory_java_python.txt
Q: Capture the last occurrence of a tag My text is of the form: <Story> <Sentence id="1"> some text </Sentence> <Sentence id="2"> some text </Sentence> <Sentence id="3"> some text </Sentence> My task is to insert a closing tag </Story> after the last </Sentence>. In the text, every </Sentence> is followe...
Capture the last occurrence of a tag
My text is of the form: <Story> <Sentence id="1"> some text </Sentence> <Sentence id="2"> some text </Sentence> <Sentence id="3"> some text </Sentence> My task is to insert a closing tag </Story> after the last </Sentence>. In the text, every </Sentence> is followed by 3 spaces. I tried capturing the last ...
[ "Is the same code producing the whole file - if so then use an xml library to generate it then all tags will be nested correctly - if not fix the code producing it so that it is valid XML.\nregexes and xml do not go together well.\n", "You really should use a parser like BeautifulSoup to do the job. BeautifulSoup...
[ 3, 1, 0, 0 ]
[]
[]
[ "last_occurrence", "python", "regex", "xml" ]
stackoverflow_0003107588_last_occurrence_python_regex_xml.txt
Q: Entity exists, empty template is returned I got the following very basic template: <html> <head> </head> <body> <div> <!-- Using "for" to iterate through potential pages would prevent getting empty strings even if only one page is returned because the "page" is not equal the query, it is a subcomponent of the que...
Entity exists, empty template is returned
I got the following very basic template: <html> <head> </head> <body> <div> <!-- Using "for" to iterate through potential pages would prevent getting empty strings even if only one page is returned because the "page" is not equal the query, it is a subcomponent of the query --> <div>{{ page.name }}</div> <div>{{ page....
[ "Your properties are called 'leftText', 'rightText', and 'imageURL', but you're trying to print out 'left_text', 'right_text' and 'image_url'. Django, in its infinite wisdom, simply returns an empty string when you try to access a property that doesn't exist, rather than throwing an exception.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003118327_google_app_engine_google_cloud_datastore_python.txt
Q: Python tar generation question I'm creating a tar file from a directory as such /home/user/bla/mydir/ Now I want to create a tar.gz file which starts from mydir/, not having directory list of the archieve content listing starting from /home/user/bla/mydir/. How can this be done? Here is my original one: tar = tarf...
Python tar generation question
I'm creating a tar file from a directory as such /home/user/bla/mydir/ Now I want to create a tar.gz file which starts from mydir/, not having directory list of the archieve content listing starting from /home/user/bla/mydir/. How can this be done? Here is my original one: tar = tarfile.open("/home/user/mytar.tar.gz", ...
[ "Use the add() method's arcname parameter:\ntar.add(\"/home/user/bla/mydir/\", arcname=\"mydir\")\n\n" ]
[ 2 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0003118473_python_tar.txt
Q: How to declare a C struct with a pointer to array in ctypes? I read the official ctypes tutorial and also searched SO, but I could not find a way to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for. typedef struct{ int i; float *...
How to declare a C struct with a pointer to array in ctypes?
I read the official ctypes tutorial and also searched SO, but I could not find a way to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for. typedef struct{ int i; float *b1; float (*w1)[]; }foo; This is what I have so far: class fo...
[ "In C, a pointer to an array stores the same memory address as a pointer to the first element in the array. Therefore:\nclass foo(Structure):\n _fields_=[(\"i\",c_int),\n (\"b1\",POINTER(c_int)),\n (\"w1\",POINTER(c_float))]\n\nYou can access the elements of the array using integer ind...
[ 1 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0003118071_c_ctypes_python.txt
Q: why does python os.path.isfile seem to ignore certain file types? simple script on a unix system (Mac) which seems to only return certain files True. Can't figure out why: workdir = '/Volumes/place/sub place' def myFunc(bla, dir, flist): for f in flist: print f, os.path.isfile(f) os.path.walk(workd...
why does python os.path.isfile seem to ignore certain file types?
simple script on a unix system (Mac) which seems to only return certain files True. Can't figure out why: workdir = '/Volumes/place/sub place' def myFunc(bla, dir, flist): for f in flist: print f, os.path.isfile(f) os.path.walk(workdir,myFunc,None) Returns: tests.py False utils.py False utils.pyc False...
[ "You're using the function wrong:\nworkdir = '/Volumes/place/sub place'\n\ndef myFunc(_, dir, flist):\n for f in flist:\n fpath = os.path.join(dir, f) # need to make a full path first\n print f, fpath, os.path.isfile(fpath)\n\nos.path.walk(workdir,myFunc,None)\n\nsee also os.walk, its nicer.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003118521_python.txt
Q: Emitting Cythonic warnings? In Cython, the usual raise keyword emits C code that contains a reference to the line and name of the Cython source file, allowing a useful error message to be generated. However, I haven't seen anything for warnings. Simply calling warnings.warn leaves the interpreter confused as to wh...
Emitting Cythonic warnings?
In Cython, the usual raise keyword emits C code that contains a reference to the line and name of the Cython source file, allowing a useful error message to be generated. However, I haven't seen anything for warnings. Simply calling warnings.warn leaves the interpreter confused as to where the warning came from. I coul...
[ "Here's something that works OK\nwarn.pyx:\nimport warnings\n\ncdef extern from \"Python.h\":\n char* __FILE__\n\ncdef extern from \"Python.h\":\n int __LINE__\n\ndef dowarn():\n warnings.warn_explicit(\"a warning\", category=UserWarning, filename=__FILE__, lineno=__LINE__)\n\nsetup.py:\nfrom distutils.cor...
[ 4 ]
[]
[]
[ "cython", "python", "warnings" ]
stackoverflow_0002647128_cython_python_warnings.txt
Q: Problems calling Python from C++ test.py def add(a,b): """ """ print a,b,a+b return a+b c program #include <python.h> int _tmain(int argc, _TCHAR* argv[]) { try { PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput; Py_Initialize(); if(!Py_IsInitialized()) return -1; pModule=PyImport...
Problems calling Python from C++
test.py def add(a,b): """ """ print a,b,a+b return a+b c program #include <python.h> int _tmain(int argc, _TCHAR* argv[]) { try { PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput; Py_Initialize(); if(!Py_IsInitialized()) return -1; pModule=PyImport_ImportModule("test"); pDict=PyModu...
[ "Last I checked, C doesn't have exceptions. Surely, you're not going to get any exceptions thrown by calls to the Python lib.\nFirst, since you're using C++, you may need to include the Python lib with an extern declaration.\nextern \"C\" {\n #include \"python.h\"\n}\n\nNext, since you don't have exceptions in C...
[ 3, 0 ]
[]
[]
[ "api", "c++", "python" ]
stackoverflow_0003101225_api_c++_python.txt
Q: Python 3.1 Installation missing Tkinter on OS 10.6.4 Has anyone else had this problem? I have re-installed twice with the same result. The pre-install of 2.6 on the Mac had a lib-tk folder with the correct modules. Nothing like this is being created for 3.1. There is a Tkinter folder but it contains only a few obs...
Python 3.1 Installation missing Tkinter on OS 10.6.4
Has anyone else had this problem? I have re-installed twice with the same result. The pre-install of 2.6 on the Mac had a lib-tk folder with the correct modules. Nothing like this is being created for 3.1. There is a Tkinter folder but it contains only a few obscure modules. Importing _tkinter and tkinter works but not...
[ "Tkinter was substantially refactored in Python 3 from a set of modules into packages. Tkinter is now tkinter and the lib-tk folder no longer exists. At least some of the example tkinter programs included in the OS X 3.1 distribution work if you ensure they are being launched under Python 3 and not Python 2. See ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003118880_python.txt
Q: datetime issue with xlrd & xlwt python libs I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right...
datetime issue with xlrd & xlwt python libs
I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right writing to the excel spreadsheet -- the data mus...
[ "You can write the floating point number directly to the spreadsheet and set the number format of the cell. Set the format using the num_format_str of an XFStyle object when you write the value.\nhttps://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html#xlwt.Worksheet.write-method\nThe following example wri...
[ 9 ]
[]
[]
[ "datetime", "excel", "python", "xlrd", "xlwt" ]
stackoverflow_0003118940_datetime_excel_python_xlrd_xlwt.txt
Q: Python global variable insanity You have three files: main.py, second.py, and common.py common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" GLOBAL_ON...
Python global variable insanity
You have three files: main.py, second.py, and common.py common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" GLOBAL_ONE = "Bob" print GLOBAL_ONE #Print...
[ "global means global for this module, not for whole program. When you do\nfrom lala import *\n\nyou add all definitions of lala as locals to this module.\nSo in your case you get two copies of GLOBAL_ONE\n", "The first and obvious question is why?\nThere are a few situations in which global variables are necessar...
[ 11, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003119287_python.txt
Q: Jython project in Eclipse can't find the xml module, but works in an identical project I have two projects in Eclipse with Java and Python code, using Jython. Also I'm using PyDev. One project can import and use the xml module just fine, and the other gives the error ImportError: No module named xml. As far as I c...
Jython project in Eclipse can't find the xml module, but works in an identical project
I have two projects in Eclipse with Java and Python code, using Jython. Also I'm using PyDev. One project can import and use the xml module just fine, and the other gives the error ImportError: No module named xml. As far as I can tell, all the project properties are set identically. The working project was created fro...
[ "eclipse stores project data in files like\n\n.project \n.pydevprojct\n.classpath\n\nwith checkin / checkout via svn it is possible to lost some of these files\ncheck your dot-files\n" ]
[ 2 ]
[]
[]
[ "eclipse", "java", "jython", "pydev", "python" ]
stackoverflow_0003057382_eclipse_java_jython_pydev_python.txt
Q: How to select an item in a gtk.IconView (Python) In a gtk.IconView I can use get_selected_items() to find the paths of the items a user selected in the view. I'm now looking for the corresponding method to set the selection of an IconView. But I can't find any!? What am I missing? A: There's a select_path() meth...
How to select an item in a gtk.IconView (Python)
In a gtk.IconView I can use get_selected_items() to find the paths of the items a user selected in the view. I'm now looking for the corresponding method to set the selection of an IconView. But I can't find any!? What am I missing?
[ "There's a select_path() method. I somehow missed it on scanning through the docs.\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python", "selection" ]
stackoverflow_0003118909_gtk_pygtk_python_selection.txt
Q: Python: deepcopy(list) vs new_list = old_list[:] I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense. The exercise suggests using copy.deepcopy() to make my task easier but I don't see how it could. def add_row(matrix): ""...
Python: deepcopy(list) vs new_list = old_list[:]
I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense. The exercise suggests using copy.deepcopy() to make my task easier but I don't see how it could. def add_row(matrix): """ >>> m = [[0, 0], [0, 0]] >>> add_row...
[ "You asked two questions:\nDeep vs. shallow copy\nmatrix[:] is a shallow copy -- it only copies the elements directly stored in it, and doesn't recursively duplicate the elements of arrays or other references within itself. That means:\na = [[4]]\nb = a[:]\na[0].append(5)\nprint b[0] # Outputs [4, 5], as a[0] and b...
[ 23, 2 ]
[]
[]
[ "copy", "list", "python" ]
stackoverflow_0003119901_copy_list_python.txt
Q: library for text rendering that supports text-on-path I need a good, reliable library or toolchain for programatically rendering text to png, with different sizes, fonts, weights, etc. It also needs to be able to render text in an arc or to a path. I would like it to be fast, because I'd be running it as on a serv...
library for text rendering that supports text-on-path
I need a good, reliable library or toolchain for programatically rendering text to png, with different sizes, fonts, weights, etc. It also needs to be able to render text in an arc or to a path. I would like it to be fast, because I'd be running it as on a server. I've tried using SVG and librsvg, but that doesn't rend...
[ "Qt has a SVG module, i believe it supports the textPath element.\nhttp://doc.trolltech.com/4.1/qtsvg.html\n" ]
[ 0 ]
[]
[]
[ "python", "rendering", "text_rendering" ]
stackoverflow_0003119882_python_rendering_text_rendering.txt
Q: Tips on Python MIL-STD-1553 Has anyone ever worked with MIL-STD-1553 in Python? How did you do it? A: If the 1553 interface has a Windows DLL, you can use the ctypes library to access it. I've done this for Python and my organization's 1553 products. To start, I would write a quick test that accesses a DLL fun...
Tips on Python MIL-STD-1553
Has anyone ever worked with MIL-STD-1553 in Python? How did you do it?
[ "If the 1553 interface has a Windows DLL, you can use the ctypes library to access it. I've done this for Python and my organization's 1553 products. \nTo start, I would write a quick test that accesses a DLL function that doesn't access the 1553 hardware, or accesses the hardware in a very simple manner. If that s...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003119027_python.txt
Q: How to lazily evaluate ORM call after fixtures are loaded into db in Django? I've got a module pagetypes.py that extracts a couple of constants (I shouldn't really use word constant here) from the db for later reuse: def _get_page_type_(type): return PageType.objects.get(type=type) PAGE_TYPE_MAIN = _get_page_...
How to lazily evaluate ORM call after fixtures are loaded into db in Django?
I've got a module pagetypes.py that extracts a couple of constants (I shouldn't really use word constant here) from the db for later reuse: def _get_page_type_(type): return PageType.objects.get(type=type) PAGE_TYPE_MAIN = _get_page_type_('Main') PAGE_TYPE_OTHER = _get_page_type_('Other') then somewhere in views ...
[ "I would use the functions instead of the constants, but memoize them:\n_cache = {}\n\ndef get_page_type(type_name):\n if type_name not in _cache:\n _cache[type_name] = PageType.objects.get(type=type_name)\n return _cache[type_name]\n\nSo now you'd call get_page_type('Main') directly when necessary.\n"...
[ 2 ]
[]
[]
[ "django", "fixtures", "lazy_loading", "python", "unit_testing" ]
stackoverflow_0003119606_django_fixtures_lazy_loading_python_unit_testing.txt
Q: parsing a line of text to get a specific number I have a line of text in the form " some spaces variable = 7 = '0x07' some more data" I want to parse it and get the number 7 from "some variable = 7". How can this be done in python? A: I would use a simpler solution, avoiding regular expres...
parsing a line of text to get a specific number
I have a line of text in the form " some spaces variable = 7 = '0x07' some more data" I want to parse it and get the number 7 from "some variable = 7". How can this be done in python?
[ "I would use a simpler solution, avoiding regular expressions.\nSplit on '=' and get the value at the position you expect\ntext = 'some spaces variable = 7 = ...'\nif '=' in text:\n chunks = text.split('=')\n assignedval = chunks[1]#second value, 7\n print 'assigned value is', assignedval\nelse:\n print...
[ 4, 2, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003120426_parsing_python.txt
Q: Is there an Objective-C equivalent to Python urllib and urllib2? Are there any equivalents in objective-c to the following python urllib2 functions? Request, urlopen, HTTPError, HTTPCookieProRequest, urlopen, HTTPError, HTTPCookieProcessor Also, how would I able to to this and change the method from "get" to "post...
Is there an Objective-C equivalent to Python urllib and urllib2?
Are there any equivalents in objective-c to the following python urllib2 functions? Request, urlopen, HTTPError, HTTPCookieProRequest, urlopen, HTTPError, HTTPCookieProcessor Also, how would I able to to this and change the method from "get" to "post"?
[ "You're looking for some combination of NSURL, NSURLRequest, NSURLConnection, NSHTTPConnection, etc. Check out the URL Loading System Programming Guide for all the information you need.\n", "NSMutableHTTPURLRequest, a category of NSMutableURLRequest, is how you set up an HTTP request. Using that class you will ...
[ 1, 1 ]
[]
[]
[ "objective_c", "python" ]
stackoverflow_0003120430_objective_c_python.txt
Q: Python, subclassing immutable types I've the following class: class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) This works as expected (initialising the set with the words of the string rather than the letters...
Python, subclassing immutable types
I've the following class: class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) This works as expected (initialising the set with the words of the string rather than the letters). However when I want to do the same wi...
[ "Yes, you need to override __new__ special method:\nclass MySet(frozenset):\n\n def __new__(cls, *args):\n if args and isinstance (args[0], basestring):\n args = (args[0].split (),) + args[1:]\n return super (MySet, cls).__new__(cls, *args)\n\nprint MySet ('foo bar baz')\n\nAnd the outpu...
[ 14 ]
[]
[]
[ "immutability", "python", "set" ]
stackoverflow_0003120562_immutability_python_set.txt
Q: How to copy matplotlib figure? I have FigureCanvasWxAgg instance with a figure displayed on a frame. If user clicks on the canvas another frame with a new FigureCanvasWxAgg containing the same figure will be shown. By now closing the new frame can result in destroying the C++ part of the figure so that it won't be...
How to copy matplotlib figure?
I have FigureCanvasWxAgg instance with a figure displayed on a frame. If user clicks on the canvas another frame with a new FigureCanvasWxAgg containing the same figure will be shown. By now closing the new frame can result in destroying the C++ part of the figure so that it won't be available for the first frame. How...
[ "I'm not familiar with the inner workings, but could easily imagine how disposing of a frame damages the figure data. Is it expensive to draw? Otherwise I'd take the somewhat chickenish approach of simply redrawing it ;)\n" ]
[ 1 ]
[]
[]
[ "copy", "matplotlib", "python", "wxpython" ]
stackoverflow_0002513786_copy_matplotlib_python_wxpython.txt
Q: How to improve performance through Python multithreading I'm new to Python and multithreading, so please bear with me. I'm writing a script to process domains in a list through Web of Trust, a service that ranks websites from 1-100 on a scale of "trustworthiness", and write them to a CSV. Unfortunately Web of Trus...
How to improve performance through Python multithreading
I'm new to Python and multithreading, so please bear with me. I'm writing a script to process domains in a list through Web of Trust, a service that ranks websites from 1-100 on a scale of "trustworthiness", and write them to a CSV. Unfortunately Web of Trust's servers can take quite a while to respond, and processing ...
[ "A quick scan through the WoT API documentation shows that as well as the public_query2 request that you are using, there is a public_query_json request that lets you get the data in batches of up to 100. I would suggest using that before you start flooding their server with lots of requests in parallel.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003120438_multithreading_python.txt
Q: Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way: #from data.models import Program import basehandler class ProgramViewHandler(basehandler.BaseHand...
Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine
I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way: #from data.models import Program import basehandler class ProgramViewHandler(basehandler.BaseHandler): def get(self,slug): # query = Program.all() # query.filter('slug =...
[ "You are getting this error because ProgramViewHandler.get() is being called without the slug parameter.\nMost likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this:\napplication = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)])\n\nThe par...
[ 9, 1 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003119562_google_app_engine_python_web_applications.txt
Q: How can I use common code in python? I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one pla...
How can I use common code in python?
I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which...
[ "There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH, or you add their location to sys.path. See this.\nSay you have \n~/python/project1\n~/python/project2\n~/python/libs/stuff.py\n~/python/libs/other.py\n\nYou can e...
[ 18, 4, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003118008_module_python.txt
Q: How to enable custom string in Django.po for Localization? I use this code to create a zh-CN: django-admin.py makemessages -l zh-CN I add some string to Django.po: msgid "zjm1126" msgstr "哈哈哈!!!" And then compile it: django-admin.py compilemessages But I don't find it become chinese words. Why? A: You need to...
How to enable custom string in Django.po for Localization?
I use this code to create a zh-CN: django-admin.py makemessages -l zh-CN I add some string to Django.po: msgid "zjm1126" msgstr "哈哈哈!!!" And then compile it: django-admin.py compilemessages But I don't find it become chinese words. Why?
[ "You need to also take two more steps:\n\nMark the string \"zjm1126\" for translation in your template, for example with {% trans \"zjm1126\" %}.\nActivate Chinese as the current language. This is often done for you by Django, but you can do it explicitly if you need to.\n\n", "use django-admin.py makemessages -...
[ 0, 0 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0003116871_django_localization_python.txt
Q: How do I send an email from a non-gmail account using the appengine I have successfully sent an email using the Google App Engine. However the only email address I can get to work is the gmail address I have listed as the admin of the site. I'm running the app on my own domain (bought and maintained using Google A...
How do I send an email from a non-gmail account using the appengine
I have successfully sent an email using the Google App Engine. However the only email address I can get to work is the gmail address I have listed as the admin of the site. I'm running the app on my own domain (bought and maintained using Google Apps). I would like to send the email from my own domain. Here's the code ...
[ "That's a restriction of App Engine's mail API:\n\nThe sender address can be either the email address of a registered administrator for the application, or the email address of the current signed-in user (the user making the request that is sending the message).\n\nIf you've got Google Apps running on that domain, ...
[ 7 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0003120941_email_google_app_engine_python.txt
Q: Check if some game is currently running and on top I am creating a keybind program for one game. So far it works perfectly but I constantly minimize this game to IM or do something else. So.. How do I make my program work when I got this game on top and when the game is minimized the program shouldn't work. A: I...
Check if some game is currently running and on top
I am creating a keybind program for one game. So far it works perfectly but I constantly minimize this game to IM or do something else. So.. How do I make my program work when I got this game on top and when the game is minimized the program shouldn't work.
[ "If you're talking about the app that currently has the focus (like, WOW when it is full screen and you're playing, for example), then you should check out this tutorial. It's a tutorial on how to build an app that keeps track of what applications have been actively used. In the tutorial it explains how to use \"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003121095_python.txt
Q: Optimizing appengine entity key usage Should I care about locality of entities on the Google App Engine datastore? Should I use custom entity key names for that? For example, I could use "$article_uuid,$comment_id" as the key name of a Comment entity. Will it improve the speed of fetching all comments for an artic...
Optimizing appengine entity key usage
Should I care about locality of entities on the Google App Engine datastore? Should I use custom entity key names for that? For example, I could use "$article_uuid,$comment_id" as the key name of a Comment entity. Will it improve the speed of fetching all comments for an article? Or is it better to use shorter keys? Is...
[ "The locality of your data will be improved with your key_name scheme (ref, see slide 40) - since your key_name is prefixed with the corresponding article's ID, comments for a given article should be stored near each other.\nThe key_name you proposed doesn't seem like it would be too long. I don't think you'll see...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003121333_google_app_engine_google_cloud_datastore_python.txt
Q: How to serve PHP together with Django? i have a Bluehost hosting account, and i manually configure django with this tutorial, but now i need to run php scripts into a subdomain or in subfolder, how can i do that? my root .htaccess look like this AddHandler fcgid-script .fcgi # For security reasons, Option follows...
How to serve PHP together with Django?
i have a Bluehost hosting account, and i manually configure django with this tutorial, but now i need to run php scripts into a subdomain or in subfolder, how can i do that? my root .htaccess look like this AddHandler fcgid-script .fcgi # For security reasons, Option followsymlinks cannot be overridden. #Options +Foll...
[ "I got it, just change a little htaccess and ready, stay this way for those who have the same problem:\nAddHandler fcgid-script .fcgi\nAddHandler application/x-httpd-php5s .php\n# For security reasons, Option followsymlinks cannot be overridden.\n#Options +FollowSymLinks\nOptions +SymLinksIfOwnerMatch\nRewriteEngin...
[ 1, 1 ]
[]
[]
[ ".htaccess", "django", "fastcgi", "php", "python" ]
stackoverflow_0003121259_.htaccess_django_fastcgi_php_python.txt
Q: Invoke make from different directory with python script I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do: build_ret = subprocess.Popen("../dir1/dir2/dir3/make", shell = True, stdout = subprocess.PIPE) I get the ...
Invoke make from different directory with python script
I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do: build_ret = subprocess.Popen("../dir1/dir2/dir3/make", shell = True, stdout = subprocess.PIPE) I get the following: /bin/sh: ../dir1/dir2/dir3/make: No such file or d...
[ "I'd go with @Philipp's solution of using cwd, but as a side note you could also use the -C option to make:\nmake -C ../dir1/dir2/dir3/make\n\n-C dir, --directory=dir\n\nChange to directory dir before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpreted relative t...
[ 11, 9, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003121555_linux_python.txt
Q: Which Python should I use? Possible Duplicates: Is it advisable to go with Python 3.1 for a beginner? What version of Python should I use if I’m a new to Python? Haven't really made anything in Python... Which Python should I take ahold of? 2.X or 3.X? A: 2.X still offers a far wider variety of third-party lib...
Which Python should I use?
Possible Duplicates: Is it advisable to go with Python 3.1 for a beginner? What version of Python should I use if I’m a new to Python? Haven't really made anything in Python... Which Python should I take ahold of? 2.X or 3.X?
[ "2.X still offers a far wider variety of third-party libraries / frameworks, instructional websites and books, and experts to help you out -- I expect this will continue for a few years until 3.X gradually overtakes it. Right now, therefore, I would still recommend 2.X despite 3.x's even-greater \"clean-ness\" and...
[ 7, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003121693_python.txt
Q: How do I count the number of occurrences of a list of items in another .txt file? I have a list of words and I want to find how many times they occur in a .txt file. The word list is something like as follows: wordlist = ['cup', 'bike', 'run'] I want to be able to not only pick up these words, but also things li...
How do I count the number of occurrences of a list of items in another .txt file?
I have a list of words and I want to find how many times they occur in a .txt file. The word list is something like as follows: wordlist = ['cup', 'bike', 'run'] I want to be able to not only pick up these words, but also things like CUP, biker, running, Cups, etc. So I think I need a regular expression. Here is wh...
[ "You're close. But re.findall takes a pattern and a string, not a wordlist and a filename. \nBut, if you read your file into a string and turn your wordlist into a pattern, then you'll get it.\nThe pattern you need will look like this: r\"cup|bike|run\". You could do \"|\".join(wordlist) to get this.\nThat's a very...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003120388_python.txt
Q: Byte precision of value in Python? I have a hash function in Python. It returns a value. How do I see the byte-size of this return value? I want to know if it is 4-bytes or 8 or what. Reason: I want to make sure that the min value is 0 and the max value is 2**32, otherwise my calculations are incorrect. I want to...
Byte precision of value in Python?
I have a hash function in Python. It returns a value. How do I see the byte-size of this return value? I want to know if it is 4-bytes or 8 or what. Reason: I want to make sure that the min value is 0 and the max value is 2**32, otherwise my calculations are incorrect. I want to make sure that packing it to a I struct...
[ "If it's an arbitrary function that returns a number, there are only 4 standard types of numbers in Python: small integers (C long, at least 32 bits), long integers (\"unlimited\" precision), floats (C double), and complex numbers.\nIf you are referring to the builtin hash, it returns a standard integer (C long):\n...
[ 1, 1 ]
[]
[]
[ "byte", "precision", "python" ]
stackoverflow_0003120868_byte_precision_python.txt
Q: Python Performance - have you ever had to rewrite in something else? Has anyone ever had code in Python, that turned out not to perform fast enough? I mean, you were forced to choose another language because of it? We are investigating using Python for a couple of larger projects, and my feeling is that in most ca...
Python Performance - have you ever had to rewrite in something else?
Has anyone ever had code in Python, that turned out not to perform fast enough? I mean, you were forced to choose another language because of it? We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Jav...
[ "Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybri...
[ 34, 19, 16, 7, 7, 5, 4, 4, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "optimization", "performance", "python", "rewrite" ]
stackoverflow_0000386655_optimization_performance_python_rewrite.txt
Q: How to define column headers when reading a csv file in Python I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I ne...
How to define column headers when reading a csv file in Python
I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I need to build an array out of the data and the first column is non-int...
[ "You can use the csv module for this sort of thing. It will read in each row as a list of strings representing the different fields.\nHow exactly you'd want to use it depends on how you're going to process the data afterwards, but you might consider making a Reader object (from the csv.reader() function), calling n...
[ 27 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003122206_csv_python.txt
Q: How can I fix this multithreaded Python script? I'm writing a python script to read through a list of domains, find out what rating Mcafee's Siteadvisor service gives, then output the domain and result to a CSV. I've based my script off this previous answer. It uses the urllib to scrape Siteadvisor's page for the ...
How can I fix this multithreaded Python script?
I'm writing a python script to read through a list of domains, find out what rating Mcafee's Siteadvisor service gives, then output the domain and result to a CSV. I've based my script off this previous answer. It uses the urllib to scrape Siteadvisor's page for the domain in question (not the best method, I know, but ...
[ "It looks like you are trying to start too many threads.\nYou can check how many items are in [address.strip() for address in intext if address.strip()] list. I quess this is a problem here. Basically there is a limit of available resources that allows to start new threads.\nThe solution for this is to chunk your l...
[ 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003122209_multithreading_python.txt
Q: how to init binary buffer in python so, I read from DB binary field i.e. 'field1' to var Buf1, and then do something like: unpack_from('I', Buf1, 0) so, all is ok. but question is how can I ini Buf1 without going to DB? I can get value from DB manually and init my var statically, but how? in DB field 'field1' I ...
how to init binary buffer in python
so, I read from DB binary field i.e. 'field1' to var Buf1, and then do something like: unpack_from('I', Buf1, 0) so, all is ok. but question is how can I ini Buf1 without going to DB? I can get value from DB manually and init my var statically, but how? in DB field 'field1' I see something like '0x7B05000001000000640...
[ "Just use pack or pack_into it's the python's opposite of unpack_from.\nSee also that answer.\nBut you should elaborate on your question and give more sample code. The value you say you see from field is too large to read it into an integer. I wonder if you get the complete value.\n" ]
[ 0 ]
[]
[]
[ "binary", "buffer", "init", "python" ]
stackoverflow_0002907012_binary_buffer_init_python.txt
Q: GUI layout -how? I've been working with a few RAD gui builders lately. I absolutely despise CSS ( camel is a horse designed by committee etc.) What algorithms are used by packing managers(java/tk). Most GUI toolkits I've used have some alternative to absolute positioning, sorry for the ambiguity but how do you sta...
GUI layout -how?
I've been working with a few RAD gui builders lately. I absolutely despise CSS ( camel is a horse designed by committee etc.) What algorithms are used by packing managers(java/tk). Most GUI toolkits I've used have some alternative to absolute positioning, sorry for the ambiguity but how do you start thinking about impl...
[ "Tk has three methods. One is absolute positioning, the other two are called \"grid\" and \"pack\". \ngrid is just what it sounds like: you lay out your widgets in a grid. There are options for spanning rows and columns, expanding (or not) to fill a cell, designating rows or columns which can grow, etc. You can acc...
[ 3 ]
[]
[]
[ "grid", "python", "rad", "tcl" ]
stackoverflow_0003122291_grid_python_rad_tcl.txt
Q: Python Unicode ajax form posting error i got a n00b problem with python and i've been searching here for a while and i couldnt find a proper solution... i got a utf8 form that i ajax post to a python page. i read the json simplejson with utf-8 charset. the text is fine as long as there is no mixed utf8 and latin c...
Python Unicode ajax form posting error
i got a n00b problem with python and i've been searching here for a while and i couldnt find a proper solution... i got a utf8 form that i ajax post to a python page. i read the json simplejson with utf-8 charset. the text is fine as long as there is no mixed utf8 and latin chars like ?!;, etc... UnicodeDecodeError: 'a...
[ "The situation you've described works fine for me (with the standard library json on Python 2.6), either with or without the explicit encoding (which is not needed for a utf-8 encoded bytestring, as utf-8 is the default here):\n>> s = u'{\"valá\":\"macché?!\"}'.encode('utf8')\n>>> json.loads(s)\n{u'val\\xe1': u'mac...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003122404_django_python.txt
Q: python implementation of patricia tries Looking around for python implementations of tries just so that I can understand what they are and how they work, I came across Justin Peel's patricia trie and found it very instructive: it's straightforward enough for one as new as I am to play around with it and learn from...
python implementation of patricia tries
Looking around for python implementations of tries just so that I can understand what they are and how they work, I came across Justin Peel's patricia trie and found it very instructive: it's straightforward enough for one as new as I am to play around with it and learn from it. However there's something I think I'm no...
[ "I believe the bug is in the following snippet of the code you're looking at:\n if w.startswith(node[0][:wlen-i],i):\n if wlen - i > len(node[0]):\n i += len(node[0])\n d = node[1]\n return True\n\nit should actually be:\n if w.startswith(node[0][:wlen...
[ 4 ]
[]
[]
[ "patricia_trie", "python" ]
stackoverflow_0003121916_patricia_trie_python.txt
Q: Using urllib2 with Jython 2.2 I'm working with a product that has a built-in Jython 2.2 instance. It comes with none of the Python standard libraries. When I run this instance of Jython, the default path is ['./run/Jython/Lib', './run/Jython', '__classpath__'] I added all of the .py module files from Python 2....
Using urllib2 with Jython 2.2
I'm working with a product that has a built-in Jython 2.2 instance. It comes with none of the Python standard libraries. When I run this instance of Jython, the default path is ['./run/Jython/Lib', './run/Jython', '__classpath__'] I added all of the .py module files from Python 2.2 to the ./run/Jython/Lib directory...
[ "Andy,\nI got a clean Jython 2.2.1 install and ran the following script successfully.\n$ ./jython\nJython 2.2.1 on java1.6.0_17\nType \"copyright\", \"credits\" or \"license\" for more information.\n>>> import urllib2\n>>> f = urllib2.urlopen('http://www.python.org/')\n>>> print f.read(100)\n<!DOCTYPE html PUBLIC \...
[ 2 ]
[]
[]
[ "jython", "libraries", "python", "urllib2" ]
stackoverflow_0003121446_jython_libraries_python_urllib2.txt
Q: python modules appearing out of no where Today one peculiar thing happened to me .I was trying to get a hang of appengine and Django on www.shell.appspot.com when i entered dir(django) the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'template', 'u...
python modules appearing out of no where
Today one peculiar thing happened to me .I was trying to get a hang of appengine and Django on www.shell.appspot.com when i entered dir(django) the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'template', 'utils'] but still i tried from django import ...
[ "The statement from package import module loads (if it had not been previously loaded) package/module.py (after first loading package/__init__.py if it hadn't previously loaded it already) and adds 'module' as an entry in the package (as well as a variable in the current scope). So dir(package) will show a 'module...
[ 8 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003122638_google_app_engine_python.txt
Q: Python how to read and split a line to several integers For input file separate by space/tab like: 1 2 3 4 5 6 7 8 9 How to read the line and split the integers, then save into either lists or tuples? Thanks. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] A: One way to do this, assuming t...
Python how to read and split a line to several integers
For input file separate by space/tab like: 1 2 3 4 5 6 7 8 9 How to read the line and split the integers, then save into either lists or tuples? Thanks. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)]
[ "One way to do this, assuming the sublists are on separate lines:\nwith open(\"filename.txt\", 'r') as f:\n data = [map(int, line.split()) for line in f]\n\nNote that the with statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do\nfrom __future__ import with_s...
[ 11, 3, 2, 1, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003122121_file_io_python.txt