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: trouble with regular expressions I need to find a string inside of a file; I copied and pasted the exact string from the file into the pattern spot, but I still can't find it. The print commands return empty strings, except for the first name. Here is my code: def fillWindow(self,student): global fileDirectory...
trouble with regular expressions
I need to find a string inside of a file; I copied and pasted the exact string from the file into the pattern spot, but I still can't find it. The print commands return empty strings, except for the first name. Here is my code: def fillWindow(self,student): global fileDirectory location = path.join(fileDirector...
[ "I think file.read() will move the cursor so subsequent calls will attempt to read from the end of the file.\nYou could read the contents of the file into a variable first, and then perform the regex searches in that.\n", "Your better bet would be to read the lines of the file in using readlines() or xreadlines()...
[ 5, 1, 0, 0 ]
[]
[]
[ "file_io", "python", "regex" ]
stackoverflow_0005107223_file_io_python_regex.txt
Q: how to close db connections in except clause originally, I didn't have a main() function. I just had a whole bunch of code in: if __name__ == '__main__': I'm trying to refactor the code a bit so that it's a little cleaner and does come clean up in case the code raises an exception. So, now my code looks like this...
how to close db connections in except clause
originally, I didn't have a main() function. I just had a whole bunch of code in: if __name__ == '__main__': I'm trying to refactor the code a bit so that it's a little cleaner and does come clean up in case the code raises an exception. So, now my code looks like this: if __name__ == '__main__': try: main...
[ "Use either the with statement with an appropriate context manager or try ... finally to make sure that your connections are closed.\n", "Put your exception handling inside main.\n", "The other answers really are much better, but you can also pass data inside Exception objects if you raise them yourself or catc...
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005108501_python.txt
Q: Profiling Python - Streaming Audio and spectrum I'm trying to modify this example: https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/advanced/spectrum.py. Unfortunately I have not been able to get it to scale. If I double the sampling rate, the graph lags from the sound input. I'd like to find out w...
Profiling Python - Streaming Audio and spectrum
I'm trying to modify this example: https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/advanced/spectrum.py. Unfortunately I have not been able to get it to scale. If I double the sampling rate, the graph lags from the sound input. I'd like to find out which part of the code is the bottleneck. I tried to u...
[ "I wrote the original version of spectrum.py, and I believe that the bottleneck is in the drawing, in particular the spectrogram plot. If you change the code to not draw every time it computes an FFT, it should keep up better.\n" ]
[ 2 ]
[]
[]
[ "chaco", "enthought", "python", "scientific_computing", "signal_processing" ]
stackoverflow_0004717221_chaco_enthought_python_scientific_computing_signal_processing.txt
Q: changing data in a struct in python I am pretty new in python, and I have a problem I don't know how to solve. For example, I have this struct with members such as administrator, berit, etc: DEFAULT_DATA = { 'administrator': { 'name': 'Admin', 'pw': 'secret', 'is_author': False, 'is_admin': True } ...
changing data in a struct in python
I am pretty new in python, and I have a problem I don't know how to solve. For example, I have this struct with members such as administrator, berit, etc: DEFAULT_DATA = { 'administrator': { 'name': 'Admin', 'pw': 'secret', 'is_author': False, 'is_admin': True } 'berit': { 'name': 'berit', 'pw'...
[ "You access it through the dictionary interface.\nstored_data = data.DefaultData()\nfor member in stored_data.itervalues():\n member['pw'] = md5.new(salt + member['pw']).hexdigest()\n\nTwo comments:\n\nFirst, this doesn't change the value in data, because you're returning a copy of it in DefaultData.\nSecond, a...
[ 1, 1 ]
[]
[]
[ "data_structures", "iterator", "python", "string" ]
stackoverflow_0005107952_data_structures_iterator_python_string.txt
Q: Users interfering with each others instances In my multiple choice Quiz show project on google app engine multiple users can use the webapp simultaneously once they are login. But due to some reason they are interfering with each others instances. Scenario example: Suppose user A wants to use the quiz show for 10 ...
Users interfering with each others instances
In my multiple choice Quiz show project on google app engine multiple users can use the webapp simultaneously once they are login. But due to some reason they are interfering with each others instances. Scenario example: Suppose user A wants to use the quiz show for 10 questions and at the same time user B wants to run...
[ "Without some concrete details about what kind of data your application stores to make one session different from any other, it is impossible to give you anything really useful, but one approach would be to store it in memcache keyed off of the user's user_id.\nCompletely hypothetical for-example code:\ndef get_ses...
[ 2 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0005108625_django_django_nonrel_google_app_engine_python.txt
Q: put sentences into list - python I understand that nltk can split sentences and print it out using the following code. but how do i put the sentences into a list instead of outputing onto the screen? import nltk.data from nltk.tokenize import sent_tokenize import os, sys, re, glob cwd = './extract_en' #os.getcwd()...
put sentences into list - python
I understand that nltk can split sentences and print it out using the following code. but how do i put the sentences into a list instead of outputing onto the screen? import nltk.data from nltk.tokenize import sent_tokenize import os, sys, re, glob cwd = './extract_en' #os.getcwd() for infile in glob.glob(os.path.join(...
[ "Here's a simplified version that I used to test the code:\nimport nltk.data\nfrom nltk.tokenize import sent_tokenize\nimport sys\ninfile = open(sys.argv[1])\nslist = []\nfor line in infile:\n slist.append(sent_tokenize(line))\nprint slist\ninfile.close()\n\nWhen called like so, it prints the following:\nme@mine...
[ 2, 1 ]
[]
[]
[ "nlp", "nltk", "python", "tokenize" ]
stackoverflow_0005108682_nlp_nltk_python_tokenize.txt
Q: python readlines stop then continue in the nextline Ok i've a problem. I need to read the lines of a file with a very large number of lines. When i find a result i stop and exit the loop then call another function. How can i save my "line number" so when i come back i just resume reading from this line, and i don'...
python readlines stop then continue in the nextline
Ok i've a problem. I need to read the lines of a file with a very large number of lines. When i find a result i stop and exit the loop then call another function. How can i save my "line number" so when i come back i just resume reading from this line, and i don't read again all the lines above. Ok you're right i was n...
[ "As commenters said, it's not clear why you're exiting the loop, but take a look at the enumerate built-in. For example:\nfor line_num, line in enumerate(f.readlines()):\n print line_num, line\n\n", "The simplest way is to use the same iterator in all the loops. Then when you get to the second loop, you will st...
[ 3, 3, 2 ]
[]
[]
[ "line", "loops", "numbers", "python", "readline" ]
stackoverflow_0005108734_line_loops_numbers_python_readline.txt
Q: Python profiler not giving enough information I am trying to find out why some function is taking a long time to complete. I am using the profiler like this: ipdb> import profile ipdb> profile.runctx('report.generateOutput()', globals(), locals()) 1 function calls in 40.783 CPU seconds Ordered by: s...
Python profiler not giving enough information
I am trying to find out why some function is taking a long time to complete. I am using the profiler like this: ipdb> import profile ipdb> profile.runctx('report.generateOutput()', globals(), locals()) 1 function calls in 40.783 CPU seconds Ordered by: standard name ncalls tottime percall cumtime ...
[ "Profile report.generateOutput(), instead of the function call.\nTo profile an application with a main entry point of foo(), you would add the following to your module:\nimport cProfile\ncProfile.run('foo()')\n\nMaybe the python docs on profiling are helpful.\n", "You say two different things:\n\n\"What I need is...
[ 2, 0 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0005107975_profiling_python.txt
Q: Loading cookies in python I am a novice programmer attempting to access google insights using python. I can access sites which dont require cookies fine, but i cant seem to properly pass the cookies along. The cookines file was exported from mozilla firefox, is in the Z: drive which is also where im running pyth...
Loading cookies in python
I am a novice programmer attempting to access google insights using python. I can access sites which dont require cookies fine, but i cant seem to properly pass the cookies along. The cookines file was exported from mozilla firefox, is in the Z: drive which is also where im running python from. Im also pretty sure my...
[ "I haven't tested your code however:\nAs far as I can tell there seems to be nothing wrong with your code\nI've tried the url you're searching and had no problems downloading the csv without any cookies\nIn my previous experience with google, you might be looking at the problem the wrong way, it is not that you don...
[ 1 ]
[]
[]
[ "cookies", "python" ]
stackoverflow_0005109352_cookies_python.txt
Q: MSMQ Transaction with COM (python)? I'm attempting to use MSMQ from Python using the win32com library, similar to this example. I'm able to put messages onto the queue, but in this case it's a transactional queue, so I need to create a transaction around the message send. Basically I'm attempting to do this VB exa...
MSMQ Transaction with COM (python)?
I'm attempting to use MSMQ from Python using the win32com library, similar to this example. I'm able to put messages onto the queue, but in this case it's a transactional queue, so I need to create a transaction around the message send. Basically I'm attempting to do this VB example in python using COM. I can't figure ...
[ "You don't need an MSMQtransaction object to send a transactional message to a transactional queue.\nJust set the transaction parameter to MQ_SINGLE_MESSAGE when you call Send().\nCheers\nJohn Breakwell\n" ]
[ 4 ]
[]
[]
[ "com", "dynamics_gp", "msmq", "msmq_transaction", "python" ]
stackoverflow_0005109285_com_dynamics_gp_msmq_msmq_transaction_python.txt
Q: how to publish photos to facebook without using facebook sdk but only by POST to the URL ..? In python facebook SDK , we are missing to upload photos , rather i want to upload photos without using the existing SDKs .. so how can implments thsese steps in python ?? You can publish a photo to a specific, existing p...
how to publish photos to facebook without using facebook sdk but only by POST to the URL ..?
In python facebook SDK , we are missing to upload photos , rather i want to upload photos without using the existing SDKs .. so how can implments thsese steps in python ?? You can publish a photo to a specific, existing photo album with a POST to http://graph.facebook.com/ALBUM_ID/photos. curl -F 'access_token=...' \...
[ "You can use urllib2 or the poster module to make post requests, take a look at these questions:\npython urllib2 file send problem\nUsing MultipartPostHandler to POST form-data with Python\n", "This isn't a place to get work done cheaply but to learn about programming, so doubtful that someone will do your work f...
[ 2, 2 ]
[]
[]
[ "facebook_graph_api", "python", "url" ]
stackoverflow_0005109427_facebook_graph_api_python_url.txt
Q: Python, web log data mining for frequent patterns I need to develop a tool for web log data mining. Having many sequences of urls, requested in a particular user session (retrieved from web-application logs), I need to figure out the patterns of usage and groups (clusters) of users of the website. I am new to Data...
Python, web log data mining for frequent patterns
I need to develop a tool for web log data mining. Having many sequences of urls, requested in a particular user session (retrieved from web-application logs), I need to figure out the patterns of usage and groups (clusters) of users of the website. I am new to Data Mining, and now examining Google a lot. Found some use...
[ "1&2: Orange has a frequent pattern mining module. It also supports clustering. \n3.I have just check the content of the book. There is not a chapter for frequent pattern mining. Anyway, it is generally a good book for beginners in data mining. You will find it very useful to help you define your problem precisely....
[ 3, 1 ]
[]
[]
[ "data_mining", "python" ]
stackoverflow_0002925555_data_mining_python.txt
Q: Unable to get Mercurial's hgweb.cgi working on IIS7 I have been using this guide http://tinyurl.com/mercurial-iis to attempt to setup Mercurial on IIS 7. I have followed every step however when I try to access the site I get the following error: Error Summary HTTP Error 500.0 - Internal Server Error There is a p...
Unable to get Mercurial's hgweb.cgi working on IIS7
I have been using this guide http://tinyurl.com/mercurial-iis to attempt to setup Mercurial on IIS 7. I have followed every step however when I try to access the site I get the following error: Error Summary HTTP Error 500.0 - Internal Server Error There is a problem with the resource you are looking for, so it canno...
[ "I would recommend dropping the ISAPI and try going down the CGI route. That's what we did - and it has been working flawlessly. It's not like the performance difference is going to be noticeable anyway.\nUseful links:\n\nhttp://www.jeremyskinner.co.uk/mercurial-on-iis7/ (we followed this guide almost religiously)...
[ 2, 1 ]
[]
[]
[ "hgweb", "iis", "mercurial", "python", "sql_server_2008_r2" ]
stackoverflow_0005109725_hgweb_iis_mercurial_python_sql_server_2008_r2.txt
Q: Keeping track of time I need my functions to get updated with new time values each second, is there a better way of keeping track than setting t1 the checking if t2 - t1 = 1 ? Edit hopefully for better clarity: The orbit code: def orbit(center, radius, speed, t): theta = math.fmod(t * speed, math.pi * 2) c...
Keeping track of time
I need my functions to get updated with new time values each second, is there a better way of keeping track than setting t1 the checking if t2 - t1 = 1 ? Edit hopefully for better clarity: The orbit code: def orbit(center, radius, speed, t): theta = math.fmod(t * speed, math.pi * 2) c = math.cos(theta) s = ...
[ "You can use threading's Timer Object:\nhttp://docs.python.org/library/threading.html#timer-objects\n", "You haven't specified anything about the needs of your code, so we have no way of telling what is \"better\" in your scenario. E.g. what does your app do with time, and why would you imagine there is a better...
[ 4, 3 ]
[]
[]
[ "python", "time" ]
stackoverflow_0005110138_python_time.txt
Q: python path for setting Django app Believe me or not but after searching the web for half an hour I couldn't find the answer: How to install django app (ex. django-profile) to the specific python path? The problem is I installed it with pip but it was installed on the "global" path. I don't want it. I want it to b...
python path for setting Django app
Believe me or not but after searching the web for half an hour I couldn't find the answer: How to install django app (ex. django-profile) to the specific python path? The problem is I installed it with pip but it was installed on the "global" path. I don't want it. I want it to be installed in /home/usr/Dev/lib folder ...
[ "From the author of pip himself:\nInstall a Python package into a different directory using pip?\nPREFIX_PATH=/path/to/folder\npip install --install-option=\"--prefix=$PREFIX_PATH\" django-profile\n\nThis would install django-profile in /path/to/folder/lib/pythonX/site-packages\n", "With virtualenv you can custo...
[ 2, 2 ]
[]
[]
[ "django", "django_apps", "python" ]
stackoverflow_0005110418_django_django_apps_python.txt
Q: SWIG Python and C++ std::string null-termination problem Possible Duplicate: How Python can get binary data(char*) from C++ by SWIG? I have a SWIG based C++ interface that can called from Python. There is a function in it, that has one std::string argument. It looks like this: WrapperGet(const std::string& key);...
SWIG Python and C++ std::string null-termination problem
Possible Duplicate: How Python can get binary data(char*) from C++ by SWIG? I have a SWIG based C++ interface that can called from Python. There is a function in it, that has one std::string argument. It looks like this: WrapperGet(const std::string& key); If it is called from Python with a string argument that con...
[ "I've had to deal with this in the past, and I just grabbed the std::string conversion template from SWIG and tailored it a bit to use PyString_FromStringAndSize when creating a Python string from a std::string and the std::string constructor that accepts a size argument when going the other way.\nThat was with a r...
[ 3, 1 ]
[]
[]
[ "c++", "python", "string", "swig" ]
stackoverflow_0005108789_c++_python_string_swig.txt
Q: Problem building libsvm-3.0 on CentOs 5.5 for Python-2.7.1 trying to install libsvm-3.0 for an alternative python build (python-2.7.1 instead of default 2.4) on CentOs 5.5. This python is installed in /opt/python2.7. I downloaded the source files and ran MAKE in the main dir and the python subdir. Then I copied...
Problem building libsvm-3.0 on CentOs 5.5 for Python-2.7.1
trying to install libsvm-3.0 for an alternative python build (python-2.7.1 instead of default 2.4) on CentOs 5.5. This python is installed in /opt/python2.7. I downloaded the source files and ran MAKE in the main dir and the python subdir. Then I copied everything to /opt/python2.7/lib/python2.7/site-packages/libsvm...
[ "Okay, problem solved. Stupid me. Instead of adding __init__.py\n to the libsvm dir, I added init.py. Once I changed that, it works. Still, the need to add __init__.py should be included in the libsvm-3.0 installation notes IMHO.\n" ]
[ 0 ]
[]
[]
[ "centos", "libsvm", "python" ]
stackoverflow_0005110578_centos_libsvm_python.txt
Q: Low Autocorrelation Binary Sequence problem? Python troubleshooting I'm trying to model this problem (for details on it, http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php) I've seen that the proven minimum for a sequence of 10 digits is 13. However, my application seems to be getting 12 quite frequently...
Low Autocorrelation Binary Sequence problem? Python troubleshooting
I'm trying to model this problem (for details on it, http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php) I've seen that the proven minimum for a sequence of 10 digits is 13. However, my application seems to be getting 12 quite frequently. This implies some kind of error in my program. Is there an obvious er...
[ "I can't spot any obvious bug offhand, but you're making things really complicated, so maybe a bug's lurking and hiding somewhere. What about\ndef evaluateHelper(self, g):\n return sum(a*b for a, b in zip(self.chromosome, self.chomosome[g:]))\n\nthis should return the same values you're computing in that subtle l...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002269831_python.txt
Q: Manipulate table values with PyObjC and Core Data I recently started programming with xCode and PyObjC and I'm trying to create a logistics application. I have a table with the store's items and a second table with the expenses. Until now everything worked ok by using just the interface builder to link values to c...
Manipulate table values with PyObjC and Core Data
I recently started programming with xCode and PyObjC and I'm trying to create a logistics application. I have a table with the store's items and a second table with the expenses. Until now everything worked ok by using just the interface builder to link values to core data information and I didn't have to write any cod...
[ "You'll need to write some code. \nThe usually way of doing this is to put the logic into a transitional attribute in your entity. Then code a custom getter for the transitional attribute such that the value of the attribute can change as other data changes. \nIn this case, cost would be your transitional attribute...
[ 0 ]
[]
[]
[ "core_data", "pyobjc", "python", "xcode" ]
stackoverflow_0002234540_core_data_pyobjc_python_xcode.txt
Q: Python sockets - keep socket alive? I'm having a little trouble with sockets in Python. Whenever someone connects it works fine but if they disconnect the server program closes. I want the server program to remain open after the client closes. I'm using a while True loop to keep the connection alive but once the c...
Python sockets - keep socket alive?
I'm having a little trouble with sockets in Python. Whenever someone connects it works fine but if they disconnect the server program closes. I want the server program to remain open after the client closes. I'm using a while True loop to keep the connection alive but once the client closes the connection the server cl...
[ "If a client closes a connection, you want it to close the socket.\nIt seems like there's a bit of a disconnect here that I'll try to elaborate on. When you create a socket, bind, and listen, you've established an open door for others to come and make connections to you.\nOnce a client connects to you, and you use ...
[ 9, 3 ]
[]
[]
[ "client", "python", "sockets", "tcp" ]
stackoverflow_0005110911_client_python_sockets_tcp.txt
Q: Python: Scapy: How to read IP flags I am trying to figure out how to read IP flags (not TCP) using scapy library. I know it is stored in "flags" and it is FlagsField type. According to IP protocol specification there are 3 flags R, MF, and DF. I've search, and searched and could not find any info on how to read th...
Python: Scapy: How to read IP flags
I am trying to figure out how to read IP flags (not TCP) using scapy library. I know it is stored in "flags" and it is FlagsField type. According to IP protocol specification there are 3 flags R, MF, and DF. I've search, and searched and could not find any info on how to read these flags. Any ideas? Thank you all for y...
[ "For example, creating an IP packet with the DF (Don't Fragment) flag set:\n>>> packet = IP(flags=2) # alternatively, IP(flags='DF')\n>>> packet\n<IP flags=DF |>\n\nReading a packet's flags:\n>>> packet.flags\n2\n\nAs for the flag bits, Wikipedia outlines this succinctly. It's a three-bit value with the following...
[ 6 ]
[]
[]
[ "ip", "python", "scapy" ]
stackoverflow_0005106542_ip_python_scapy.txt
Q: async http request on Google App Engine Python Does anybody know how to make http request from Google App Engine without waiting a response? It should be like a push data with http without latency for response. A: I think that this section of the AppEngine docs is what you are looking for. A: Use the taskqueue...
async http request on Google App Engine Python
Does anybody know how to make http request from Google App Engine without waiting a response? It should be like a push data with http without latency for response.
[ "I think that this section of the AppEngine docs is what you are looking for.\n", "Use the taskqueue. If you're just pushing data, there's no sense in waiting for the response.\n", "What you could do is in the request handler enqueue a task with whatever data was received (using the deferred library). As soon ...
[ 3, 2, 1, 0 ]
[]
[]
[ "asynchronous", "google_app_engine", "http", "python", "request" ]
stackoverflow_0005107675_asynchronous_google_app_engine_http_python_request.txt
Q: Storing a python set in a database with django I have a need to store a python set in a database for accessing later. What's the best way to go about doing this? My initial plan was to use a textfield on my model and just store the set as a comma or pipe delimited string, then when I need to pull it back out for...
Storing a python set in a database with django
I have a need to store a python set in a database for accessing later. What's the best way to go about doing this? My initial plan was to use a textfield on my model and just store the set as a comma or pipe delimited string, then when I need to pull it back out for use in my app I could initialize a set by calling s...
[ "If your database is better at storing blobs of binary data, you can pickle your set. Actually, pickle stores data as text by default, so it might be better than the delimited string approach anyway. Just pickle.dumps(your_set) and unpickled = pickle.loads(database_string) later.\n", "There are a number of option...
[ 4, 2, 1, 0 ]
[]
[]
[ "django", "python", "serialization", "set" ]
stackoverflow_0005110607_django_python_serialization_set.txt
Q: get_or_create django model with ManyToMany field Suppose I have three django models: class Section(models.Model): name = models.CharField() class Size(models.Model): section = models.ForeignKey(Section) size = models.IntegerField() class Obj(models.Model): name = models.CharField() sizes = mo...
get_or_create django model with ManyToMany field
Suppose I have three django models: class Section(models.Model): name = models.CharField() class Size(models.Model): section = models.ForeignKey(Section) size = models.IntegerField() class Obj(models.Model): name = models.CharField() sizes = models.ManyToManyField(Size) I would like to import a l...
[ "Use a through model and then .get() against that.\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\nOnce you have a through model, you can .get() or .filter() or .exists() to determine the existence of an object that you might otherwise want to create. Note that ....
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005108623_django_python.txt
Q: Best way to parse large XML document in Jython I need to parse a large (>800MB) XML file from Jython. The XML is not deeply nested, containing about a million relevant elements. I need to convert these elements into real objects. I've used nu.xom.* successfully before, but now that I've switched from Java to Jyth...
Best way to parse large XML document in Jython
I need to parse a large (>800MB) XML file from Jython. The XML is not deeply nested, containing about a million relevant elements. I need to convert these elements into real objects. I've used nu.xom.* successfully before, but now that I've switched from Java to Jython, the library fails with the following message: T...
[ "Sax is the best way to parse large documents. \nSounds like you're hitting the default expansion limit. \nSee this note:\nhttp://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4843787\nYou need to set System property \"entityExpansionLimit\" to change \nthe default. \n(added) see also the answer to this question.\n",...
[ 4, 3, 3, 0 ]
[]
[]
[ "java", "jython", "python", "xml", "xom" ]
stackoverflow_0005094042_java_jython_python_xml_xom.txt
Q: Algorithm to get every possible subset of a list, in order of their product, without building and sorting the entire list (i.e Generators) Practically, I've got a set of objects with probabilities, and I want to look at each possible group of them, in order of how likely it is that they're all true assuming they'r...
Algorithm to get every possible subset of a list, in order of their product, without building and sorting the entire list (i.e Generators)
Practically, I've got a set of objects with probabilities, and I want to look at each possible group of them, in order of how likely it is that they're all true assuming they're independent -- i.e. in descending order of the product of the elements of the subsets -- or in order of length if the probabilities are the sa...
[ "Nice question, it was quite tricky to solve. I can't think of a way to generate the combinations in order either, but I wield the mighty heapq (aka a priority queue) to keep the candidates sorted.\nfrom heapq import heappush, heappop\nimport operator\n\ndef prob(ps):\n \"\"\" returns the probability that *not* ...
[ 5 ]
[]
[]
[ "dynamic_programming", "generator", "knapsack_problem", "powerset", "python" ]
stackoverflow_0005111395_dynamic_programming_generator_knapsack_problem_powerset_python.txt
Q: Arbitrary Number of File Uploads in Django What is the best way to allow a user to do an arbitrary number of file uploads with Django? If I knew I was going to allow the user to do up to two file uploads then I could just do this in my forms.py... from django import forms class UploaderForm(forms.Form): file1...
Arbitrary Number of File Uploads in Django
What is the best way to allow a user to do an arbitrary number of file uploads with Django? If I knew I was going to allow the user to do up to two file uploads then I could just do this in my forms.py... from django import forms class UploaderForm(forms.Form): file1 = forms.FileField(upload_to='user_files') f...
[ "Formsets are exactly what you need.\nhttp://docs.djangoproject.com/en/dev/topics/forms/formsets/#formsets\nAll you have to do is follow the field naming format that the formset uses 'form-0-field' in your javascript instead of fileN\nAlso modify the form-TOTAL_FORMS accordingly. Check the docs, they are especially...
[ 3 ]
[]
[]
[ "django", "forms", "http_upload", "javascript", "python" ]
stackoverflow_0005112017_django_forms_http_upload_javascript_python.txt
Q: Saving Binary Data To MySQLdb - Python I have googled and searched this site, but nothing specific appears and cannot get this working. Here is the code: binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll)) sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattac...
Saving Binary Data To MySQLdb - Python
I have googled and searched this site, but nothing specific appears and cannot get this working. Here is the code: binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll)) sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment) \ VALUES ('%s','%s','%s','%s','%s...
[ "Bunch of things here:\nbinData = ''.join(map(lambda x: chr(x % 256), attach.attcoll))\nsql_stmt = \"\"\"INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment)\nVALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE filename=%s,fileextension=%s\"\"\" \n\nparams = (attach.attno,attach.filename...
[ 1 ]
[]
[]
[ "binary", "blob", "mysql", "python" ]
stackoverflow_0005112072_binary_blob_mysql_python.txt
Q: Matching abbreviated first names using regular expressions I'm trying to match the name R. Buckminster Fuller in a wikipedia dump that has |name = R. Buckminster Fuller and I have the following regular expression: (?<=[n|N]ame = )[\w\W\.\s]+?(?=[^A-Za-z0-9_\s]) It doesn't seem to work - it gets hung on the period ...
Matching abbreviated first names using regular expressions
I'm trying to match the name R. Buckminster Fuller in a wikipedia dump that has |name = R. Buckminster Fuller and I have the following regular expression: (?<=[n|N]ame = )[\w\W\.\s]+?(?=[^A-Za-z0-9_\s]) It doesn't seem to work - it gets hung on the period after the R. What am I missing?
[ "remove the ^ in your regex. it doesn't make sense. inside the [] it indicates exclusion of following characters.\nwouldn't this do?\n[n|N]ame = ([\\w\\.\\s]+)\n\n", "Looking at your regular expression, it's not really clear what you want to do.\nThe following expression match the full name : \n(?<=[n|N]ame = )[\...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005112029_python_regex.txt
Q: Customize Python Slicing, please advise I have a class that subclasses the list object. Now I need to handle slicing. From everything I read on the intertubes this has to be done using the __getitem__ method. At least in Python 2.7+ which is what I'm using. I have done this (see below), but the __getitem__ met...
Customize Python Slicing, please advise
I have a class that subclasses the list object. Now I need to handle slicing. From everything I read on the intertubes this has to be done using the __getitem__ method. At least in Python 2.7+ which is what I'm using. I have done this (see below), but the __getitem__ method isn't called when I pass in a slice. Ins...
[ "See this note:\n\nobject.__getslice__(self, i, j)\nDeprecated since version 2.0: Support\n slice objects as parameters to the\n __getitem__() method. (However, built-in types in CPython currently\n still implement __getslice__().\n Therefore, you have to override it in\n derived classes when implementing\n s...
[ 17 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0005112019_list_python_slice.txt
Q: Python RGB array to HSL and back well i've seen some code to convert RGB to HSL; but how to do it fast in python. Its strange to me, that for example photoshop does this within a second on a image, while in python this often takes forever. Well at least the code i use; so think i'm using wrong code to do it In my ...
Python RGB array to HSL and back
well i've seen some code to convert RGB to HSL; but how to do it fast in python. Its strange to me, that for example photoshop does this within a second on a image, while in python this often takes forever. Well at least the code i use; so think i'm using wrong code to do it In my case my image is a simple but big raw ...
[ "For manipulating image data, many use the Python Imaging Library. However, it doesn't handle HSL colour. Luckily, Python comes with a library called colorsys. Here's an example of colorsys being used to convert between colour modes on a per-pixel level: http://effbot.org/librarybook/colorsys.htm\ncolorsys also pro...
[ 6, 4, 1 ]
[]
[]
[ "c", "python", "rgb" ]
stackoverflow_0005112248_c_python_rgb.txt
Q: for loop in python inFile = open("subjects.txt","r") global subArray subArray = [] global line for line in inFile: subArray.append(line) inFile.close() return subArray This how I get the data when in is in different lines in the text file like math science art I nee...
for loop in python
inFile = open("subjects.txt","r") global subArray subArray = [] global line for line in inFile: subArray.append(line) inFile.close() return subArray This how I get the data when in is in different lines in the text file like math science art I need to know how to do it w...
[ "line.split(\" , \") will turn the string into an array a list of strings. You might also look at the standard \"csv\" module.\n", "This will work if the entire file is just one line:\nsubArray = [subj.strip() for subj in open(\"subjects.txt\",\"r\").read().split(',')]\n\nor if you want to do it in a loop:\n inFi...
[ 4, 3 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0005112514_for_loop_loops_python.txt
Q: Preventing blurring of fast-moving objects on the screen I'm writing a desktop application in Python using the Qt framework, and it involves whisking images across the screen at a fairly quick pace. I do this in a pretty straightforward way: For each item, create a Qlabel object with the associated image Start a ...
Preventing blurring of fast-moving objects on the screen
I'm writing a desktop application in Python using the Qt framework, and it involves whisking images across the screen at a fairly quick pace. I do this in a pretty straightforward way: For each item, create a Qlabel object with the associated image Start a timer for each Qlabel using startTimer timerEvent leads to a c...
[ "It looks like flicker from a lack of double buffering. I'm not sure exactly how to solve it in your particular toolkit, but that should point you in the right direction.\n" ]
[ 1 ]
[]
[]
[ "animation", "antialiasing", "image", "python", "qt" ]
stackoverflow_0005112110_animation_antialiasing_image_python_qt.txt
Q: python script for android scripting environment so i have this script that i pulled from a website, and am trying to get a barcode scanner working... the site says it can be done in these 6 lines of python: import android droid = android.Android() code = droid.scanBarcode() isbn = int(code['result']['SCAN_RESULT']...
python script for android scripting environment
so i have this script that i pulled from a website, and am trying to get a barcode scanner working... the site says it can be done in these 6 lines of python: import android droid = android.Android() code = droid.scanBarcode() isbn = int(code['result']['SCAN_RESULT']) url = ?http://books.google.com?q=%d? % isbn droid.s...
[ "Change all the ? to \" might work. I guess when you copy from the website, something funny happens.\n" ]
[ 1 ]
[]
[]
[ "android", "api", "python", "scripting" ]
stackoverflow_0005112558_android_api_python_scripting.txt
Q: Python - Validation with multiple schemas using lxml I'm working with a schema that was built by a third party and I'd like to validate it with lxml. The problem is that such a schema is split over different xsd files, which reference themselves. For example, a file called "extension.xsd" (which builds upon the "m...
Python - Validation with multiple schemas using lxml
I'm working with a schema that was built by a third party and I'd like to validate it with lxml. The problem is that such a schema is split over different xsd files, which reference themselves. For example, a file called "extension.xsd" (which builds upon the "master" schema) has a line like: <redefine schemaLocation="...
[ "If lxml doesn't support \"redefine\", the best option would be to fix it and submit a patch. :)\nFailing that, the workaround would be to parse the master.xsd file yourself, and then apply the changes from extension.xsd, and output a single xsd file with the combined schema.\n" ]
[ 1 ]
[]
[]
[ "lxml", "python", "xsd" ]
stackoverflow_0003147636_lxml_python_xsd.txt
Q: Reading data from 3d models with python I want to extract the vertices and faces (as lists of vertices) from a 3d model. The format of the 3d model doesn't matter as long as it's generatable in Maya. I would like to do this in Python. Are there any libraries, file types, etc. that you would recommend? A: I'm pre...
Reading data from 3d models with python
I want to extract the vertices and faces (as lists of vertices) from a 3d model. The format of the 3d model doesn't matter as long as it's generatable in Maya. I would like to do this in Python. Are there any libraries, file types, etc. that you would recommend?
[ "I'm pretty sure Maya exports in OBJ file format, which is very heavily documented and implemented. Python's cgkit implements an OBJ parser, which you can find here: http://cgkit.sourceforge.net/doc2/objmtl.html\nEdit: Actually, cgkit can read a lot more formats from Maya than just OBJ. I searched for OBJ since I k...
[ 7 ]
[]
[]
[ "3d", "parsing", "python" ]
stackoverflow_0005112739_3d_parsing_python.txt
Q: How to customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django? Customizing a queryset of a form field in Django isn't a hard job. Like this But, assuming I have the following models: #models.py class Work(Model): name = models.CharfField(...) #some fields class G...
How to customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django?
Customizing a queryset of a form field in Django isn't a hard job. Like this But, assuming I have the following models: #models.py class Work(Model): name = models.CharfField(...) #some fields class Gallery(Model): work = models.ForeignKey(Work) class Photo(Model): gallery = models.ForeignKey(Gallery)...
[ "The only way I have been able to do it is pass in the data you need into the instantiaton of the form class.\ni.e., in your view:\ndef view(request):\n ...\n work = <whatever>\n form = StageOfWorkForm(work, request.POST)\n ...\n\nThen, your form needs to the work object:\nclass StageOfWorkForm(ModelFor...
[ 4, 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005108994_django_django_forms_python.txt
Q: using python and IActiveDesktop to set wallpaper in windows 7 I have been searching for how to use IActiveDesktop to change the wallpaper and have pieced together the following code from various sources. sys.coinit_flags = 0 pythoncom.CoInitialize() iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None,...
using python and IActiveDesktop to set wallpaper in windows 7
I have been searching for how to use IActiveDesktop to change the wallpaper and have pieced together the following code from various sources. sys.coinit_flags = 0 pythoncom.CoInitialize() iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop) iad.SetW...
[ "I think you're just missing the second parameter to SetWallPaper, which should always be 0.\nThis works for me:\nimport pythoncom\nfrom win32com.shell import shell, shellcon\n\nimagePath = \"c:\\\\temp\\\\bug.png\"\n\niad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None,\n pythoncom.CLSCTX_INP...
[ 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0005108325_python_windows.txt
Q: Retain the "\n" >>> t = "first%s\n" >>> t = t %("second") >>> print t firstsecond Is there anyway I could retain the "\n" at the end and get "firstsecond\n" as the output? A: You need to escape the slash >>> t = "first%s\\n" >>> t = t %("second") >>> print t or use raw strings: >>> t = r"first%s\n" >>> t = t %...
Retain the "\n"
>>> t = "first%s\n" >>> t = t %("second") >>> print t firstsecond Is there anyway I could retain the "\n" at the end and get "firstsecond\n" as the output?
[ "You need to escape the slash\n>>> t = \"first%s\\\\n\"\n>>> t = t %(\"second\")\n>>> print t\n\nor use raw strings:\n>>> t = r\"first%s\\n\"\n>>> t = t %(\"second\")\n>>> print t \n\n", "print \"firstsecond\\n\" displays \"firstsecond\" and the cursor is pushed to the next new line. So you don't see any backsl...
[ 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005112291_python.txt
Q: Unexpected behaviour in python random number generation I have the following code: import random rand1 = random.Random() rand2 = random.Random() rand1.seed(0) rand2.seed(0) rand1.jumpahead(1) rand2.jumpahead(2) x = [rand1.random() for _ in range(0,5)] y = [rand2.random() for _ in range(0,5)] According to the ...
Unexpected behaviour in python random number generation
I have the following code: import random rand1 = random.Random() rand2 = random.Random() rand1.seed(0) rand2.seed(0) rand1.jumpahead(1) rand2.jumpahead(2) x = [rand1.random() for _ in range(0,5)] y = [rand2.random() for _ in range(0,5)] According to the documentation of jumpahead() function I expected x and y to b...
[ "rand1.seed(0)\nrand2.seed(0)\n\nYou initialize them with the same values so you get the same (non-)randomness. Use some value like the current unix timestamp to seed it and you will get better values. But note that if you initialize two RNGs at the same time with the current time though, you will get the same \"ra...
[ 4, 2 ]
[]
[]
[ "python", "random" ]
stackoverflow_0005112578_python_random.txt
Q: adding menubar to wxpython.grid Table How one can add a menubar to a wx.grid frame? I have searched a lot and cannot find any solution to this problem. A: You don't add it to the grid, you add the grid and a menu bar to a frame, like so: #!/usr/bin/python import wx import wx.grid class GridAndMenuFrame(wx.Frame...
adding menubar to wxpython.grid Table
How one can add a menubar to a wx.grid frame? I have searched a lot and cannot find any solution to this problem.
[ "You don't add it to the grid, you add the grid and a menu bar to a frame, like so:\n#!/usr/bin/python\nimport wx\nimport wx.grid\n\nclass GridAndMenuFrame(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title, \n wx.DefaultPosition, wx.Si...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005063465_python.txt
Q: pyparsing: extracting strings containing specific text I am trying to learn pyparsing. It sounds promising and something that would be fun to use for text processing. Anyhow, here is my question: I have a list of course names. For example, courselist = ["Project Based CALC", "CALCULUS I", "Ca...
pyparsing: extracting strings containing specific text
I am trying to learn pyparsing. It sounds promising and something that would be fun to use for text processing. Anyhow, here is my question: I have a list of course names. For example, courselist = ["Project Based CALC", "CALCULUS I", "Calculus II", "Intermediate MICRO", "Int...
[ "calc = pp.CaselessLiteral('calc')\nfor entry in courselist:\n if calc.searchString(entry, 1):\n print entry\n\nThe effect is similar to:\nfor entry in courselist:\n if 'calc' in entry.lower():\n print entry\n\n" ]
[ 2 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005112858_pyparsing_python.txt
Q: Python script invocation weirdness on Windows (aka why PATH did not get inherited?) I've encountered a behavior I did not expect when executing the following Python script (I named it repro.py): import os print os.environ['PATH'].replace(';', '\n') If invoked by python repro.py, I get this: C:\Python26\ C:\Pytho...
Python script invocation weirdness on Windows (aka why PATH did not get inherited?)
I've encountered a behavior I did not expect when executing the following Python script (I named it repro.py): import os print os.environ['PATH'].replace(';', '\n') If invoked by python repro.py, I get this: C:\Python26\ C:\Python26\Scripts C:\Windows\system32 C:\Windows C:\Windows\System32\Wbem C:\Program Files\MySQ...
[ "That is bizarre. I'm running the standard python 2.7 from python.org on windows 7, and both invocations print the full PATH, as expected.\nIt may be a bug, or \"feature\" in ActivePython. :)\nAlthough, are you opening them both in the same command prompt window? Perhaps your path really had been changed?\n" ]
[ 0 ]
[]
[]
[ "activestate", "python", "windows" ]
stackoverflow_0005071733_activestate_python_windows.txt
Q: My set/dictionary-based script is stuttering...dictionary rehashing? I've got a script that performs a large AI computation using sets and dictionaries, outputting a line every thousand states, and it has the tendency to stutter. The larger the searched space, the longer the stuttering, so I'm thinking it's probab...
My set/dictionary-based script is stuttering...dictionary rehashing?
I've got a script that performs a large AI computation using sets and dictionaries, outputting a line every thousand states, and it has the tendency to stutter. The larger the searched space, the longer the stuttering, so I'm thinking it's probably the sets and dictionaries being rehashed. Is there anyway that I can ma...
[ "There seems to be no way to force a dictionary to pre-allocate. It might not be dictionary re-hashing, it could be the garbage collector. There are functions in the gc module that you might be able to use to control or at least observe the collector behavior.\n" ]
[ 2 ]
[]
[]
[ "dictionary", "python", "set" ]
stackoverflow_0005113000_dictionary_python_set.txt
Q: How does one indicate invalid arguments in Python? Possible Duplicate: python: Should I use ValueError or create my own subclass to handle invalid strings? Reading Built-in Exceptions I read: All user-defined exceptions should also be derived from this class" with regards to Exception. I also see a ValueError ...
How does one indicate invalid arguments in Python?
Possible Duplicate: python: Should I use ValueError or create my own subclass to handle invalid strings? Reading Built-in Exceptions I read: All user-defined exceptions should also be derived from this class" with regards to Exception. I also see a ValueError which says: Raised when a built-in operation or functi...
[ "I think the general idea is this: ValueError should almost always denote some sort of client error (where 'client' means the programmer using your interface). There are two high-level types of exceptions in Python:\n\nuncommon cases for otherwise normally functioning code; the client is not to blame\nusage errors ...
[ 10, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0005113014_exception_python.txt
Q: why do python strings not have __iter__ function? How is it that we can iterate over python strings when strings don't have an __iter__ function? $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "asdf".__iter...
why do python strings not have __iter__ function?
How is it that we can iterate over python strings when strings don't have an __iter__ function? $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "asdf".__iter__ Traceback (most recent call last): File "<stdin>",...
[ "From your link:\n\nor it must support the sequence\n protocol (the __getitem__() method\n with integer arguments starting at 0).\n\nIn [1]: 'foo'.__getitem__(0)\nOut[1]: 'f'\n\n", "Probably because Python isn't a langage that has a \"char\" type. The natural thing to return, if string did have __iter__ would b...
[ 39, 0 ]
[]
[]
[ "iteration", "python", "string" ]
stackoverflow_0005113133_iteration_python_string.txt
Q: something wrong with my pythonpath I know this is a dumb question but i'm stumped. My directory structure used to look like this: -src | -module.py -program.py when this what my directory structure, I referenced module from program and all was well. I've since changed my directory structure to this: -src ...
something wrong with my pythonpath
I know this is a dumb question but i'm stumped. My directory structure used to look like this: -src | -module.py -program.py when this what my directory structure, I referenced module from program and all was well. I've since changed my directory structure to this: -src | -__init.py -module.py | -progr...
[ "For starters, I recommend reading the entry Modifying Python's Search Path in the docs.\nIt might be frowned upon by some, but if you wish to modify the PYTHONPATH from within your program, according to the documentation's standard modules entry you can use the sys.path.append method:\nimport sys\nsys.path.append(...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "pythonpath" ]
stackoverflow_0005110325_python_pythonpath.txt
Q: pycairo "ImportError: DLL load failed: The specified module could not be found." even after DLLs installed I'm following the pycairo installation instructions here : http://www.cs.rhul.ac.uk/home/tamas/development/igraph/tutorial/install.html to install pycairo for use with igraph. However, even after running the...
pycairo "ImportError: DLL load failed: The specified module could not be found." even after DLLs installed
I'm following the pycairo installation instructions here : http://www.cs.rhul.ac.uk/home/tamas/development/igraph/tutorial/install.html to install pycairo for use with igraph. However, even after running the installer and unzipping/copying all DLL's into the site-packages cairo directory according to the instructions,...
[ "Open _cairo.pyd in Dependency Walker and figure out what it's missing.\n", "I kinda solved the problem installing the Gtk-Bundle for Windows, wich had the third party dll dependencies.\n(I did a dirty solution by pasting the dlls directly into c:/Python27/lib/dist-packages/cairo, because I am not used to Windows...
[ 20, 0 ]
[]
[]
[ "igraph", "pycairo", "python", "windows_7" ]
stackoverflow_0004731786_igraph_pycairo_python_windows_7.txt
Q: Meshgrid and confusion regarding X and Y coordinates import numpy as np def L2Norm(f, x, y, d=0.00001): dudx = (f(x+d,y) - f(x-d,y)) / (2*d) dudy = (f(x,y+d) - f(x,y-d)) / (2*d) L2Norm = np.float128(np.sqrt(dudx**2 + dudy**2)) return L2Norm def f(x,y): return np.float128((1.0 + np.sin(np.pi*x))*(...
Meshgrid and confusion regarding X and Y coordinates
import numpy as np def L2Norm(f, x, y, d=0.00001): dudx = (f(x+d,y) - f(x-d,y)) / (2*d) dudy = (f(x,y+d) - f(x,y-d)) / (2*d) L2Norm = np.float128(np.sqrt(dudx**2 + dudy**2)) return L2Norm def f(x,y): return np.float128((1.0 + np.sin(np.pi*x))*((3.0 + np.cos(2.011*y))**2)*np.e**((-x**2)-((y**2)/4))) #...
[ "If you call L2_Norm.shape, you'll see that the dimensions of the array is (40,20) so as the error states, L2_Norm[19,39] is out of range because 39 > the max index in that dimension of 19. Take a look at the shape of X and Y as well to see why L2_Norm has the shape that it does -- the reason is clear if you look i...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005113317_numpy_python.txt
Q: Deploying database changes with Python I'm wondering if someone can recommend a good pattern for deploying database changes via python. In my scenario, I've got one or more PostgreSQL databases and I'm trying to deploy a code base to each one. Here's an example of the directory structure for my SQL scripts: my...
Deploying database changes with Python
I'm wondering if someone can recommend a good pattern for deploying database changes via python. In my scenario, I've got one or more PostgreSQL databases and I'm trying to deploy a code base to each one. Here's an example of the directory structure for my SQL scripts: my_db/ main.sql some_directory/ ...
[ "What you're doing is actually a decent approach if you control all the servers and they're all postgresql servers.\nA more general approach is to have a directory of \"migrations\" which are generally classes with an apply() and undo() that actually do the work in your database, and often come with \nabstractions ...
[ 1, 1 ]
[]
[]
[ "continuous_integration", "postgresql", "python", "sql" ]
stackoverflow_0005112225_continuous_integration_postgresql_python_sql.txt
Q: Does List and dictionary in python have a limited capacity ? if yes,how much is it? Does List and dictionary in python have a limited capacity ? if yes,how much is it ? A: Yes, It is sys.maxsize. import sys print sys.maxsize
Does List and dictionary in python have a limited capacity ? if yes,how much is it?
Does List and dictionary in python have a limited capacity ? if yes,how much is it ?
[ "Yes, It is sys.maxsize.\nimport sys\nprint sys.maxsize\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0005113628_python.txt
Q: What is the use of Django setting the ETag header? What is the ETag header, why does Django set it and how should I use it? A: An ETag, or entity tag, is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for cache validation, and which allows a client to make ...
What is the use of Django setting the ETag header?
What is the ETag header, why does Django set it and how should I use it?
[ "\nAn ETag, or entity tag, is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for cache validation, and which allows a client to make conditional requests.\n\nSource.\nBasically, you do a md5 or something of the file, and if the file changes, the ETags do not ma...
[ 2 ]
[]
[]
[ "django", "etag", "python" ]
stackoverflow_0005113761_django_etag_python.txt
Q: list comprehension to merge various lists in python I need to plot a lot of data samples, each stored in a list of integers. I want to create a list from a lot of concatenated lists, in order to plot it with enumerate(big_list) in order to get a fixed-offset x coordinate. My current code is: biglist = [] for n in ...
list comprehension to merge various lists in python
I need to plot a lot of data samples, each stored in a list of integers. I want to create a list from a lot of concatenated lists, in order to plot it with enumerate(big_list) in order to get a fixed-offset x coordinate. My current code is: biglist = [] for n in xrange(number_of_lists): biglist.extend(recordings[n]...
[ "import itertools\nfor x,y in enumerate(itertools.chain(*(recordings[n][chosen_channel] for n in xrange(number_of_lists))):\n print x,y\n\nYou can think of itertools.chain() as managing an iterator over the individual lists. It remembers which list and where in the list you are. This saves you all memory you wou...
[ 4, 3 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0005113822_list_list_comprehension_python.txt
Q: Server process closes the connection as soon as one client is done executing I am implementing basic socket program , but in this case i want the server process to keep on running . But the problem is as soon as client is executed , the server also closes the connection . here`s the server code : # Echo server pr...
Server process closes the connection as soon as one client is done executing
I am implementing basic socket program , but in this case i want the server process to keep on running . But the problem is as soon as client is executed , the server also closes the connection . here`s the server code : # Echo server program import socket HOST = '' # Symbolic name meaning all availab...
[ "I think you may be able to find your answer from this post on keeping sockets alive.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005114379_python.txt
Q: How do I filter by a ForeignKey's db_column field without going through the foreign object in Django I have a legacy database with non-django naming conventions. If I have the following (cut down) models: class Registration(models.Model): projectId=models.IntegerField(primary_key=True) class Application(model...
How do I filter by a ForeignKey's db_column field without going through the foreign object in Django
I have a legacy database with non-django naming conventions. If I have the following (cut down) models: class Registration(models.Model): projectId=models.IntegerField(primary_key=True) class Application(models.Model): applicationId=models.IntegerField(primary_key=True) registration=models.ForeignKey(Regis...
[ "I think just doing Application.objects.registration.get(projectId=1234) should do what you want.\n", "Have you tried this?\nApplication.objects.get(registration=1234)\n\n" ]
[ 0, 0 ]
[]
[]
[ "django_models", "django_queryset", "python" ]
stackoverflow_0005113689_django_models_django_queryset_python.txt
Q: Python Not Importing So i downloaded the lastfm api for python made by people. found here: http://code.google.com/p/python-lastfm/ I have a website hosting through dreamhost. I wasnt able to build the module using: python setup.py build in my shell that i used putty to get into. But when i would run python s...
Python Not Importing
So i downloaded the lastfm api for python made by people. found here: http://code.google.com/p/python-lastfm/ I have a website hosting through dreamhost. I wasnt able to build the module using: python setup.py build in my shell that i used putty to get into. But when i would run python setup.py install it would...
[ "Python packages are searched in your PYTHONPATH. If you do echo $PYTHONPATH or\nimport sys\nprint sys.path\n\nyou will get a list of directories from where the modules are being imported.\nIn your case with python-lastfm, you are installing using one version of Python and trying to run the program using another ve...
[ 0, 0, 0 ]
[]
[]
[ "api", "import", "last.fm", "python" ]
stackoverflow_0005114536_api_import_last.fm_python.txt
Q: Dynamic image creation using Python over a web page I'm new to learning Python and I've been trying to implement a text to image converter that runs on a web page. I have succeeded in making the functional code that converts the text into image in Python, using the PIL module (i.e., user enters input text at run...
Dynamic image creation using Python over a web page
I'm new to learning Python and I've been trying to implement a text to image converter that runs on a web page. I have succeeded in making the functional code that converts the text into image in Python, using the PIL module (i.e., user enters input text at run time and that gets converted into an image and is stored...
[ "Check out webpy, just about the simplest Python web framework. In the web.py module, import your PIL image converter, grab the text from the submitted form (via web.input()), convert the text and render a page with the new image on it. You should be able to get a simple page up in a dozen or so lines.\n", "You c...
[ 0, 0 ]
[]
[]
[ "dynamic", "html", "image", "python" ]
stackoverflow_0004009380_dynamic_html_image_python.txt
Q: Pymssql, How to use it to read unicode data from MSSQL2008 I've used pymssql-1.0.2 and freetds-0.82.7 on ubuntu-10.10. Also, I have a mssql2008 server on windows-7. I can connect with mssql from ubuntu using pymssql and freetds. But I can't get unicode data from mssql database. Database collation is Cyrillic_Gene...
Pymssql, How to use it to read unicode data from MSSQL2008
I've used pymssql-1.0.2 and freetds-0.82.7 on ubuntu-10.10. Also, I have a mssql2008 server on windows-7. I can connect with mssql from ubuntu using pymssql and freetds. But I can't get unicode data from mssql database. Database collation is Cyrillic_General_CI_AS. My freetds.conf file looks like this: [mssql2008] ...
[ "Is it really Unicode data? I.e., is the cc_Name column varchar or nvarchar? It sounds like it's varchar--in which case, try using cp1251 or windows-1251 as the charset instead of iso-8859-1.\n" ]
[ 2 ]
[]
[]
[ "freetds", "pymssql", "python", "sql_server", "unicode" ]
stackoverflow_0005099710_freetds_pymssql_python_sql_server_unicode.txt
Q: Import statement in library definition does not seem to be executed I am having a problem that may be quite a basic thing, but as a Python learner I've been struggling with it for hours. The documentation has not provided me with an answer so far. The problem is that an import statement included in a module does n...
Import statement in library definition does not seem to be executed
I am having a problem that may be quite a basic thing, but as a Python learner I've been struggling with it for hours. The documentation has not provided me with an answer so far. The problem is that an import statement included in a module does not seem to be executed when I import this module from a python script. Wh...
[ "The datetime module is only imported into the project namespace. So you could access it as project.datetime.datetime.min, but really you should import it into your script directly.\nEvery symbol (name) that you create in your project.py file (like your Project class) ends up in the project namespace, which includ...
[ 4, 0 ]
[]
[]
[ "import", "nameerror", "python" ]
stackoverflow_0005114981_import_nameerror_python.txt
Q: How to get cyrillic string from document How to get cyrillic string from document? I have fallowing code: import urllib from BeautifulSoup import BeautifulSoup page = urllib.urlopen("http://habrahabr.ru/") soup = BeautifulSoup(page.read()) for topic in soup.findAll(True, 'topic'): print topic print raw_in...
How to get cyrillic string from document
How to get cyrillic string from document? I have fallowing code: import urllib from BeautifulSoup import BeautifulSoup page = urllib.urlopen("http://habrahabr.ru/") soup = BeautifulSoup(page.read()) for topic in soup.findAll(True, 'topic'): print topic print raw_input() There is cyrillic words on the site but...
[ "The data on the HTML page is encoded in UTF-8. It appears that you are printing it to your console, where sys.stdout.encoding is cp1251. That accounts for the rubbish that you are seeing.\nHere are the results of inspecting the first 8 bytes of the first topic, using IDLE:\n>>> raw = '\\xd0\\x90\\xd0\\xbb\\xd0\\xb...
[ 3, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0005110574_parsing_python.txt
Q: Algorithm for sorting numbers summing to a total and respecting criterions in python I am trying to do a feed optimisation calculation for animal feeding but I am a rookie in term of python coding. Actually what I try to achieve is compute the less expensive combination of n ingredients by groups of k or less that...
Algorithm for sorting numbers summing to a total and respecting criterions in python
I am trying to do a feed optimisation calculation for animal feeding but I am a rookie in term of python coding. Actually what I try to achieve is compute the less expensive combination of n ingredients by groups of k or less that supply enough of A and B criterions. My problem is that when ingredients number start goi...
[ "I think you should be looking at scipy.optimize - it will quite happily deal with numpy arrays and is generally quite fast. See ref http://docs.scipy.org/doc/scipy-0.8.x/reference/tutorial/optimize.html\nIf you have an input vector A which specifies the amount of each ingredient, and an ingredient matrix I which s...
[ 1, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0005106358_algorithm_python.txt
Q: How to decorate (monkeypatch...) a Python class with methods from another class? Both httplib.HTTPMessage and email.message.Message classes[1] implements methods for RFC822 headers parsing. Unfortunately, they have different implementations[2] and they do not provide the same level of functionality. One example th...
How to decorate (monkeypatch...) a Python class with methods from another class?
Both httplib.HTTPMessage and email.message.Message classes[1] implements methods for RFC822 headers parsing. Unfortunately, they have different implementations[2] and they do not provide the same level of functionality. One example that is bugging me is that: httplib.HTTPMessage is missing the get_filename method pres...
[ "In Python 3.x, unbound methods go away so you'll just get the file objects in this case and your second example will work:\n>>> class C():\n... def demo(): pass\n... \n>>> C.demo\n<function demo at 0x1fed6d8>\n\nIn Python 2.x, you can either access the underlying function via the unbound method or by retrieving ...
[ 2, 1 ]
[]
[]
[ "class", "decorator", "monkeypatching", "python", "rfc822" ]
stackoverflow_0005106356_class_decorator_monkeypatching_python_rfc822.txt
Q: child subprocess kill in python daemon I have damon in python which runs external program: subprocess.call(["java", "-jar", "start.jar"]) when I kill daemon, the child process (java) is still running how can I make so that child process is also killed ? A: Use subprocess.Popen() instead of subprocess.call(). Fo...
child subprocess kill in python daemon
I have damon in python which runs external program: subprocess.call(["java", "-jar", "start.jar"]) when I kill daemon, the child process (java) is still running how can I make so that child process is also killed ?
[ "Use subprocess.Popen() instead of subprocess.call(). For example:\nimport subprocess\nmy_process = subprocess.Popen(['ls', '-l'])\n\nTo terminate the child:\nmy_process.kill()\n\nTo capture the kill signal, you could so something like this:\nimport signal\nimport sys\ndef signal_handler(signal, frame):\n sys.ex...
[ 8 ]
[]
[]
[ "daemon", "python", "subprocess" ]
stackoverflow_0005114812_daemon_python_subprocess.txt
Q: using print() with compound operators in python The following code doesn't work in python x = 11 print(x += 5) while this code does x = 11 x += 5 print(x) why is that? A: x += 5 is a statement, not an expression. You can only use expressions as arguments in function calls. I'm assuming you are used to a C-like...
using print() with compound operators in python
The following code doesn't work in python x = 11 print(x += 5) while this code does x = 11 x += 5 print(x) why is that?
[ "x += 5 is a statement, not an expression. You can only use expressions as arguments in function calls.\nI'm assuming you are used to a C-like language, where x += 5 is an expression, but in Python it's not.\n", "The problem is the due to the difference between a Statement and an Expression. This question has an...
[ 8, 8, 1 ]
[]
[]
[ "compound_operator", "python", "python_3.x" ]
stackoverflow_0005115551_compound_operator_python_python_3.x.txt
Q: Math Expression Evaluation What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simp...
Math Expression Evaluation
What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one. clarification: I need so...
[ "If you're \"academically interested\", you want to learn about how to write a parser with operator precedence.\nSimple Top-Down Parsing in Python is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathematical expressions.\nI can highly recommend having a go at writing your...
[ 16, 2, 1, 1 ]
[ "This receipe gives the proper answer to your problem:\nhttp://code.activestate.com/recipes/496746-restricted-safe-eval/\nIt allows you to eval limited statement that can not harm your computer or your program.\n" ]
[ -1 ]
[ "evaluation", "expression", "math", "parsing", "python" ]
stackoverflow_0001545403_evaluation_expression_math_parsing_python.txt
Q: Reading and running a mathematical expression in Python Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? Aside from grabbing a string, file or url I have no idea of where to start with this. A: Because python suppor...
Reading and running a mathematical expression in Python
Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? Aside from grabbing a string, file or url I have no idea of where to start with this.
[ "Because python supports some algebraic forms, you could do:\neval(\"1 + 1\")\n\nBut this allows the input to execute about anything defined in your env:\neval(\"__import__('sys').exit(1)\")\n\nAlso, if you want to support something python doesn't support, the approach fails:\nx³ + y² + c\n----------- = 0\n z\n...
[ 7, 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000400050_python.txt
Q: Some characters (trademark sign, etc) unable to write to a file but is printable on the screen I've been trying to scrape data from a website and write out the data that I find to a file. More than 90% of the time, I don't run into Unicode errors but when the data has the following characters such as "Burger King®...
Some characters (trademark sign, etc) unable to write to a file but is printable on the screen
I've been trying to scrape data from a website and write out the data that I find to a file. More than 90% of the time, I don't run into Unicode errors but when the data has the following characters such as "Burger King®, Hans Café", it doesn't like writing that into the file so my error handling prints it to the scree...
[ "Your f.write() line doesn't make sense to me - stream will be a unicode since it's made indirectly from from tag.text and BeautifulSoup gives you Unicode, so you shouldn't call decode on stream. (You use decode to turn a str with a particular character encoding into a unicode.) You've opened the file for writing...
[ 1, 0 ]
[]
[]
[ "character_encoding", "encoding", "python", "unicode_string" ]
stackoverflow_0005115717_character_encoding_encoding_python_unicode_string.txt
Q: Seem to have a problem with returning an order.pk value with Django (r'^search/(?P<client_id>\d+)/(?P<order_no>\d+)/test_items/$', views.test_items), I want a link that can go to this url views.service_order2, Unfortunately, I keep getting a NoReverseMatch error. (r'^quote/service_order/(?P<client_id>\d+)/(?P<o...
Seem to have a problem with returning an order.pk value with Django
(r'^search/(?P<client_id>\d+)/(?P<order_no>\d+)/test_items/$', views.test_items), I want a link that can go to this url views.service_order2, Unfortunately, I keep getting a NoReverseMatch error. (r'^quote/service_order/(?P<client_id>\d+)/(?P<order_no>\d+)/(?P<request_type>\d+)/$', views.service_order2), Caught NoR...
[ "From the error message it seems that client_id is empty.\n" ]
[ 0 ]
[]
[]
[ "django", "parameters", "python", "templates", "views" ]
stackoverflow_0005103056_django_parameters_python_templates_views.txt
Q: Django question: need help using HttpResponseRedirect I have a view called save_service_request. At the end of the code it redirects to a view called send_confirmation_email. def save_service_request(request): try: # some stuff except: return HttpResponseRedirect(reverse(service_order, args = [contact...
Django question: need help using HttpResponseRedirect
I have a view called save_service_request. At the end of the code it redirects to a view called send_confirmation_email. def save_service_request(request): try: # some stuff except: return HttpResponseRedirect(reverse(service_order, args = [contact.client.pk , service_type])) return HttpResponseRedirec...
[ "Use next attribute:\nIn views.service_order\ncontext = {'next': reverse('views.send_confirmation_email')}\n\nIn template:\n<form action='?next={{ next }}'>\n\nIn view which validates form:\nif 'next' in request.GET:\n return HttpResponseRedirect(request.GET['next'])\n\n" ]
[ 0 ]
[]
[]
[ "django", "httpresponse", "parameters", "python", "views" ]
stackoverflow_0005115955_django_httpresponse_parameters_python_views.txt
Q: Lambda function and 0 I want to make a function that changes each elements in list with lambda function. a = [1,5,2,4] def func1(list,func2): for x in range(len(list)): list[x] = func2(list[x]) func1(a,lambda x: x>3 and 10 or x) print a The result is [1,10,2,10] This is OK. But I change '10' to '0' ...
Lambda function and 0
I want to make a function that changes each elements in list with lambda function. a = [1,5,2,4] def func1(list,func2): for x in range(len(list)): list[x] = func2(list[x]) func1(a,lambda x: x>3 and 10 or x) print a The result is [1,10,2,10] This is OK. But I change '10' to '0' func1(a,lambda x: x>3 and 0...
[ "The problem you have is that 0 is being evaluated as False which means that using the and-or trick as a conditional expression is failing.\nPython 2.5 introduced \"proper\" conditional expressions of the form:\nx = true_value if condition else false_value\n\nSo you can replace:\nlambda x: x>3 and 0 or x\n\nwith:\n...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005115897_python.txt
Q: Is it a simplest substring in python? Below is my code which get code(always in brackets, and always has 3 chars) from string : raw_text='Spain (BCN)' #another examples: 'Italy (BGN)' , 'Germany (SXF)' formatted_text=raw_text[raw_text.index('(')+1:len(raw_text)-1] # BCN,BGN,SFX Can I write it simpler? A: import...
Is it a simplest substring in python?
Below is my code which get code(always in brackets, and always has 3 chars) from string : raw_text='Spain (BCN)' #another examples: 'Italy (BGN)' , 'Germany (SXF)' formatted_text=raw_text[raw_text.index('(')+1:len(raw_text)-1] # BCN,BGN,SFX Can I write it simpler?
[ "import re\nraw_text='Spain (BCN)'\nformatted_text = re.search(r\"\"\"\n (?<=\\() # assert that the preceding character is a (\n \\w{3} # match three alphanumeric characters\n (?=\\)) # assert that the following character is a )\"\"\", \n raw_text, re.VERBOSE).group(0)\n\nwould be another way of doin...
[ 3, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005116759_python_string.txt
Q: python mysqldb not working - no error message Any idea what I am doing wrong here? There are no error messages and the script runs fine, but no record is inserted into the db. Running the insert query on the database works fine. Even if i put in a bogus IP or password no error is generated. This is on windows wi...
python mysqldb not working - no error message
Any idea what I am doing wrong here? There are no error messages and the script runs fine, but no record is inserted into the db. Running the insert query on the database works fine. Even if i put in a bogus IP or password no error is generated. This is on windows with python 2.7 and the mysqldb 2.7 windows binaries....
[ "Autocommit is disabled. Commit the transaction before disconnecting.\n" ]
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005117001_mysql_python.txt
Q: Why is this Button not centered, Tkinter I'm attempting to center a button (self.HBu) within my frame. For some reason when I run this, the button sticks toward the bottom of the frame. What am I doing wrong? Snippet: frame = Tk.Frame(self).pack(ipadx=180, ipady=100) self.HBu = Tk.Button(frame, text='cl...
Why is this Button not centered, Tkinter
I'm attempting to center a button (self.HBu) within my frame. For some reason when I run this, the button sticks toward the bottom of the frame. What am I doing wrong? Snippet: frame = Tk.Frame(self).pack(ipadx=180, ipady=100) self.HBu = Tk.Button(frame, text='click', command=self.do_stuff) self.HBu.pac...
[ "Are you aware that by default, pack places widgets at the top of a frame? There is no explanation for it being at the bottom, based on the code you posted.\nTry adding side=\"left\" to your pack statement if you want the button on the left side of your frame. If that doesn't work, make sure it's really at the bott...
[ 2 ]
[ "Check the Dock Property of the Button, it may be set to bottom i think. r else some where in the coding the align property of the button is modified.\n" ]
[ -1 ]
[ "pack", "python", "tkinter" ]
stackoverflow_0005114487_pack_python_tkinter.txt
Q: RSA encryption in .NET, decryption in python I'm trying to encrypt a short message using RSA algorithm in C# and decrypt the message using a python skript. I'd like to use the .NET classes on the C# side and pycrypto on python side. I've managed both sides to use the same key (which was not even trivial since .NET...
RSA encryption in .NET, decryption in python
I'm trying to encrypt a short message using RSA algorithm in C# and decrypt the message using a python skript. I'd like to use the .NET classes on the C# side and pycrypto on python side. I've managed both sides to use the same key (which was not even trivial since .NET doesn't support the standard PEM/DER format direc...
[ "Ok, it was my fault, I just didn't look at the results: The leading zero (from PKCS#1 padding) is not part of the python result string, which looks (in hex) like:\n02 a2 16 4e 51 45 aa 8d \n94 b0 de 64 4d 4c 4c bd \n0b 01 b8 d2 de dc ed 23 \n0b 25 c2 11 6c 0a 0b 1f \n4f 19 d0 33 18 db e0 81 \n25 33 f6 e3 70 8d 97 ...
[ 2 ]
[]
[]
[ ".net", "public_key_encryption", "pycrypto", "python", "rsa" ]
stackoverflow_0005116760_.net_public_key_encryption_pycrypto_python_rsa.txt
Q: Windows Service relative path issue in Python I have written a small Windows Service compiled to an exe using py2exe, which from I read a file. It works great - however - I can only use an absolute path to access the file, using a relative path won't work. In .net you can do something like: System.Reflection.Assem...
Windows Service relative path issue in Python
I have written a small Windows Service compiled to an exe using py2exe, which from I read a file. It works great - however - I can only use an absolute path to access the file, using a relative path won't work. In .net you can do something like: System.Reflection.Assembly.GetEntryAssembly().Location To get the path to...
[ "You have a couple of options. If you already have a module object, you can do <module>.__file__ to get the path:\n>>> import time\n>>> time.__file__\n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/time.so'\n\nHowever, often times you want to know the location of your current m...
[ 1 ]
[]
[]
[ "exe", "py2exe", "python", "windows_services" ]
stackoverflow_0005117253_exe_py2exe_python_windows_services.txt
Q: using pyserial flush method I've read somewhere that the use of flush is necessary to reduce lag. Is this true? I'm not really sure about using it. Please help me understand what it does exactly. I've checked pyserial docs but it didnt give me much information. All it said was: flush() Flush of file like obj...
using pyserial flush method
I've read somewhere that the use of flush is necessary to reduce lag. Is this true? I'm not really sure about using it. Please help me understand what it does exactly. I've checked pyserial docs but it didnt give me much information. All it said was: flush() Flush of file like objects. It’s a no-op in this class,...
[ "Information you're sending/writing may be temporarily stored in a buffer, so that a larger chunk can be written in one go. So, if you do:\nf = open(\"test.txt\",\"w\")\nf.write(\"Hello\")\n\ntest.txt will still be empty, until you do f.flush() to flush the buffer. f.close() also flushes the buffer before closing t...
[ 3 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0005116780_pyserial_python.txt
Q: Printing linux man-help like on python I am trying to build a help message output for my custom app like Linux man does. I've been walking around pprint, using dictionaries, and others. But, I'm al little lost. I'm currently using a dictionary combined with print commands. Until now is enough for my needs but I mu...
Printing linux man-help like on python
I am trying to build a help message output for my custom app like Linux man does. I've been walking around pprint, using dictionaries, and others. But, I'm al little lost. I'm currently using a dictionary combined with print commands. Until now is enough for my needs but I must confess It's not up to scratch. I would l...
[ "optparse and argparse both support printing usage details.\n", "There's the optparse module, and its successor argparse (the first one is deprecated since Python 2.7). These modules automatically generate help output like this one (from the Python docs):\n$ prog.py -h\nusage: prog.py [-h] [--sum] N [N ...]\n\nPr...
[ 4, 2 ]
[]
[]
[ "formatting", "messages", "python" ]
stackoverflow_0005117417_formatting_messages_python.txt
Q: Python csv: finding out rows with biggest values I must be missing something, but I have trouble with finding out the biggest values and printing them using the csv.DictReader() function. The csv file is something like (I have cut the fields as well as rows because the rows are too wide for this format): traverse;...
Python csv: finding out rows with biggest values
I must be missing something, but I have trouble with finding out the biggest values and printing them using the csv.DictReader() function. The csv file is something like (I have cut the fields as well as rows because the rows are too wide for this format): traverse;damage;hull_front;turret_back;penetration;full_name;ti...
[ "In tank = list(itertools.islice(tanks,1,2)) you define tank as a list.\nbest_tanks is a dict with the values being the list tank.\nIn your if you replace the lists in best_tanks with the variable tank that now is a dict, so its ok to later use best_tanks[field][field].\nBut if the if if is not executed, the elemen...
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005117819_csv_python.txt
Q: Having difficulty in mapreduce to understand I have seen the below link which is of getting started mapreduce with python http://code.google.com/p/appengine-mapreduce/wiki/GettingStartedInPython But still I am not able to understand how its working. I am executing below code but not able to understand what exactly...
Having difficulty in mapreduce to understand
I have seen the below link which is of getting started mapreduce with python http://code.google.com/p/appengine-mapreduce/wiki/GettingStartedInPython But still I am not able to understand how its working. I am executing below code but not able to understand what exactly is happening? mapreduce.yaml mapreduce: - name: ...
[ "You are setting the \"mahesh\" value to the StringProperty name of all your userDetail entities.\nIf you want to count your entities use :\nfrom mapreduce import operation as op\n def process(entity):\n yield op.counters.Increment(\"counter1\")\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "mapreduce", "python" ]
stackoverflow_0005114627_google_app_engine_mapreduce_python.txt
Q: Namespacing and classes I'm trying to write some (in my opinion) readable code in Python. I need a module that will contain a number of classes. Theoretically I know everything that is needed to accomplish this: I can simply put class definitions in a single module file. For readability purposes I want to put ever...
Namespacing and classes
I'm trying to write some (in my opinion) readable code in Python. I need a module that will contain a number of classes. Theoretically I know everything that is needed to accomplish this: I can simply put class definitions in a single module file. For readability purposes I want to put every class definition into separ...
[ "Import them all within __init__.py, and then have the consumer import the package.\nfrom .module1 import Class1\nfrom .module2 import Class2\n ...\n\n", "If you want to avoid hardcoding module paths, file, class, and function names in many places, you could do something like the following which dynamically impor...
[ 8, 3 ]
[]
[]
[ "class", "module", "python", "scope" ]
stackoverflow_0005117194_class_module_python_scope.txt
Q: Any system to write code with multiple users online in real time like a shared google docs? Is there any free system to write code with multiple users online in real time like a shared google docs? Google docs would work just fine for us if only it could do some color-highlighting. Ideas? Thanks A: Similar groun...
Any system to write code with multiple users online in real time like a shared google docs?
Is there any free system to write code with multiple users online in real time like a shared google docs? Google docs would work just fine for us if only it could do some color-highlighting. Ideas? Thanks
[ "Similar ground covered here: https://stackoverflow.com/questions/1873780/best-editor-for-remote-pair-programming\n..and here: https://superuser.com/questions/10088/google-docs-syntax-highlight\n..and here: Is there any IDE or Source Control System inspired by Google Docs collaborative mode?\nI hope one of the abov...
[ 5, 1 ]
[]
[]
[ "editor", "python" ]
stackoverflow_0005118461_editor_python.txt
Q: Recursive algorithm for generating a graph I have some database objects that are fully linked to each other as dependencies. What i want to do is to write an algorithm to retrieve that information and represent all this as a graph. Right now a pseudocode should do the trick for me , then after i should be able to ...
Recursive algorithm for generating a graph
I have some database objects that are fully linked to each other as dependencies. What i want to do is to write an algorithm to retrieve that information and represent all this as a graph. Right now a pseudocode should do the trick for me , then after i should be able to write the python implementation. This seems like...
[ "If I understood correctly, you want only the leaf nodes of the tree (those with no more dependencies). Is that the case? An example using an auxiliar struct to make it runnable:\nclass Struct:\n def __init__(self, **entries): \n self.__dict__.update(entries) \n\nobj = Struct(\n name=\"1\",\n ...
[ 1 ]
[]
[]
[ "graph", "python" ]
stackoverflow_0005117444_graph_python.txt
Q: Need help fnding the average of a set of numbers in python in my data file I have 60,66,88,90,44,90,80,77 all the numbers are in one line this is my code which does not give me the average of my numbers inFile3 = open("data2.txt","r") global gradeVar gradeVar = len(gradeArray) global Total ...
Need help fnding the average of a set of numbers in python
in my data file I have 60,66,88,90,44,90,80,77 all the numbers are in one line this is my code which does not give me the average of my numbers inFile3 = open("data2.txt","r") global gradeVar gradeVar = len(gradeArray) global Total Total = 0 for Numbers in inFile3: Total = Tota...
[ "Your problem is here:\nfor Numbers in inFile3: \n Total = Total + int(Numbers)\n\nNumbers in the code above is a list of lines, rather than a list of numbers.\nfor Line in inFile3:\n for number in Line.split(','):\n Total = Total + int(number)\n\nshould help.\nYou also have no need to pre-declare ...
[ 5, 2, 2, 1, 1, 0 ]
[]
[]
[ "average", "file_io", "python" ]
stackoverflow_0005118509_average_file_io_python.txt
Q: Django: Odd mark_safe behaviour? I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' ...
Django: Odd mark_safe behaviour?
I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>', co...
[ "The render method of your widget is called by the BoundField.__unicode__ function, which returns SafeString instead (of a subclass of unicode.)\nMany places in Django (e.g. django.template.VariableNode.render) will actually call force_unicode on the field instance itself. This will have the effect of doing unicode...
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002597184_django_python.txt
Q: Haskell Equivalent of Zope Test Browser I've been tinkering around with the Zope test browser in Python, exploring its suitability as for a few projects. As I explored, I realized that there are a few things in Haskell that would be fun and useful to have. Is there something in the Haskellverese equivalent to t...
Haskell Equivalent of Zope Test Browser
I've been tinkering around with the Zope test browser in Python, exploring its suitability as for a few projects. As I explored, I realized that there are a few things in Haskell that would be fun and useful to have. Is there something in the Haskellverese equivalent to the Zope Test Browser?
[ "The closest analogue is probably the Network.Browser module form http: http://hackage.haskell.org/packages/archive/HTTP/4000.1.1/doc/html/Network-Browser.html\nIt's been around a long time an isn't the fanciest or most efficient, but it gives a similar direct emulation of a browser.\nFor doing browser-like things ...
[ 2 ]
[]
[]
[ "automation", "haskell", "http", "python", "testing" ]
stackoverflow_0005118912_automation_haskell_http_python_testing.txt
Q: Getting error while trying to add header with Set-Cookie in GAE I am trying to include external python module in my project for working with sessions. It's named gmemsess.py. It tries to add Set-Cookie header in the response and an error appears: rh.response.headers.add_header('Set-Cookie','%s=%s; path=/;'%(name,s...
Getting error while trying to add header with Set-Cookie in GAE
I am trying to include external python module in my project for working with sessions. It's named gmemsess.py. It tries to add Set-Cookie header in the response and an error appears: rh.response.headers.add_header('Set-Cookie','%s=%s; path=/;'%(name,self._sid)) AttributeError: HeaderDict instance has no attribute 'add_...
[ "The headers.add_header method should absolutely work if you are using stock AppEngine, but I am guessing that you are using a framework -- and there are plenty of them, like Bottle -- that uses a custom replacement for webob's Response object.\nA little bit of time with Google reveals that there is at least one id...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python", "session", "webapp2" ]
stackoverflow_0005118639_google_app_engine_python_session_webapp2.txt
Q: Breadth first search with three-letter words, optimization I'm using a breadth-first search algorithm in Python to find the shortest "path" from a three-letter word to another. I've got it working but the performance is horrible and I suspect my word children generation function. Basically for every word I pop fro...
Breadth first search with three-letter words, optimization
I'm using a breadth-first search algorithm in Python to find the shortest "path" from a three-letter word to another. I've got it working but the performance is horrible and I suspect my word children generation function. Basically for every word I pop from the queue I generate all other three-letter words that can be ...
[ "I assume that you have a list of valid words and you are actually not looking for a single path (why would you care to optimize for that) but for lots of paths. This can be done quite easily with networkX:\nfrom networkx import Graph\nfrom networkx.algorithms.shortest_paths import shortest_path, all_pairs_shortest...
[ 4, 2, 0 ]
[]
[]
[ "breadth_first_search", "graph", "python" ]
stackoverflow_0005118703_breadth_first_search_graph_python.txt
Q: USB devices UDev and D-BUS I am trying to get a list of currently plugged in USB devices in Ubuntu 10.10 and monitor changes that happen, like devices being plugged in or out using UDev and D-BUS. I'm fairly new to programming using D-BUS. I saw one example: Linux : How to detect is usb keyboard is plugged and unp...
USB devices UDev and D-BUS
I am trying to get a list of currently plugged in USB devices in Ubuntu 10.10 and monitor changes that happen, like devices being plugged in or out using UDev and D-BUS. I'm fairly new to programming using D-BUS. I saw one example: Linux : How to detect is usb keyboard is plugged and unplugged only that one uses HAL an...
[ "The udisks D-Bus service, obviously, only reports disks.\nJust monitor udev directly (through libudev, through pyudev).\nimport pyudev\ncontext = pyudev.Context()\nmonitor = pyudev.Monitor.from_netlink(context)\nobserver = pyudev.pygtk.GUDevMonitorObserver(monitor)\nobserver.connect('device-added', device_added_ca...
[ 11, 2 ]
[]
[]
[ "dbus", "linux", "python", "ubuntu", "udev" ]
stackoverflow_0005109879_dbus_linux_python_ubuntu_udev.txt
Q: Does poster.encode module supported in python appengine? Does poster.encode module supported in python appengine ?? if No , whats is the possible alternatives ? A: You'd need to deploy the module with your code by including it in your application's directory when deploying, but it does appear to be a pure python...
Does poster.encode module supported in python appengine?
Does poster.encode module supported in python appengine ?? if No , whats is the possible alternatives ?
[ "You'd need to deploy the module with your code by including it in your application's directory when deploying, but it does appear to be a pure python module and looking through the source I see no reason why it wouldn't work just fine in App Engine.\nThe only modules that won't work are those that use C extensions...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005119269_google_app_engine_python.txt
Q: In Python, what's the difference between 'except Exception as e' and 'except Exception, e' In python, there are two ways to catch an exception except Exception, e: except Exception as e: It seems like 'as e' is the one to use going forward. In what version of python did this change? Any idea why? A: This PE...
In Python, what's the difference between 'except Exception as e' and 'except Exception, e'
In python, there are two ways to catch an exception except Exception, e: except Exception as e: It seems like 'as e' is the one to use going forward. In what version of python did this change? Any idea why?
[ "\nThis PEP introduces changes intended to help eliminate ambiguities in Python's grammar, simplify exception classes, simplify garbage collection for exceptions and reduce the size of the language in Python 3.0.\n\nPEP 3110: \"Catching Exceptions in Python 3000\"\n", "Short answer for the why: Exception, e and E...
[ 50, 16, 14 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0005119751_exception_python.txt
Q: How to return to previous part of the program (Python) I'm novice in python and got a problem in which I would appreciate some help. The problem in short: ask for a string check if all letter in a predefined list if any letter is not in the list then ask for a new string, otherwise go to next step ask for a secon...
How to return to previous part of the program (Python)
I'm novice in python and got a problem in which I would appreciate some help. The problem in short: ask for a string check if all letter in a predefined list if any letter is not in the list then ask for a new string, otherwise go to next step ask for a second string check again whether the second string's letters in ...
[ "I suggest you start here: http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming\nAnd continue to next chapter: http://docs.python.org/tutorial/controlflow.html\n", "You have a couple of options, you could use iteration, or recursion. For this kind of problem I would go with iteration....
[ 3, 0, 0, 0 ]
[]
[]
[ "python", "return" ]
stackoverflow_0005118608_python_return.txt
Q: Recursive variable definitions in Python and F# (probably OCaml, too) Given these F# type declarations... type Message = | MessageA | MessageB | MessageC | MessageD type State = { Name:string NextStateMap: Map<Message,State> } ...is there an equally expressive definition of this specific ...
Recursive variable definitions in Python and F# (probably OCaml, too)
Given these F# type declarations... type Message = | MessageA | MessageB | MessageC | MessageD type State = { Name:string NextStateMap: Map<Message,State> } ...is there an equally expressive definition of this specific state machine... let rec state0 = { Name = "0"; NextStateMap = Map.ofList [...
[ "In Python I think you'd define the states and then set the map. Pseudo-code like:\nstate0 = State(\"0\")\nstate1 = State(\"1\")\n... and so on ...\nstate0.next_states = {message_a: state1, message_b: state2 }\nstate1.next_states = {message_b: state3}\n... and so on ...\n\n", "## a generic state machine framework...
[ 5, 0 ]
[]
[]
[ "f#", "ocaml", "python", "recursive_datastructures" ]
stackoverflow_0005119230_f#_ocaml_python_recursive_datastructures.txt
Q: Finding optimal elements from an array in python I need to devise an algorithm that finds me the most optimal elements from a list in python. I have a cd that holds 700mb. And an array of 300 randomly generated file sizes varying from 30 - 90 mb. It needs to fill the cd the most optimal way, that minimum room is w...
Finding optimal elements from an array in python
I need to devise an algorithm that finds me the most optimal elements from a list in python. I have a cd that holds 700mb. And an array of 300 randomly generated file sizes varying from 30 - 90 mb. It needs to fill the cd the most optimal way, that minimum room is wasted ( looking through all possible ways) I guess it'...
[ "As @payne points out in his comment, this is really the same as the knapsack problem. The solution is therefore a simple dynamic programming algorithm.\nSay the files are arranged one after another in some order in a list. At first, you have the choice of either choosing to include the first file or skipping it. I...
[ 4, 2 ]
[]
[]
[ "algorithm", "arrays", "data_structures", "python" ]
stackoverflow_0005119695_algorithm_arrays_data_structures_python.txt
Q: Pass variable between two custom tags in Django I am trying to implement django template tag {% domready %}{% enddomready %} that would take it's contents, remember it somewhere, and then tag {% domready_render %} that would render all that content. It would look something like this: {# main.html #} <html> ... <bo...
Pass variable between two custom tags in Django
I am trying to implement django template tag {% domready %}{% enddomready %} that would take it's contents, remember it somewhere, and then tag {% domready_render %} that would render all that content. It would look something like this: {# main.html #} <html> ... <body> ... <script> (function($) { $...
[ "As you guess render contexts are not shared between template files.\nYou can solve your problem by using a module level variable where you define your template tags.\nJust add\ndom_ready = []\n\nto the top of the file, then where you have context['dom_ready'] replace it with dom_ready.\nDid you know that you can c...
[ 2 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0005119897_django_javascript_jquery_python.txt
Q: Django - Get ContentType model by model name (Generic Relations) I'm thinking about this for a while now, I'm creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my project, since it uses a generic relation in it's foreign key. Is there a way to know...
Django - Get ContentType model by model name (Generic Relations)
I'm thinking about this for a while now, I'm creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my project, since it uses a generic relation in it's foreign key. Is there a way to know which model that Room is related knowing only the models name? Like: ...
[ "http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances\nuser_type = ContentType.objects.get(app_label=\"auth\", model=\"user\")\nuser_type = ContentType.objects.get(model=\"user\")\n# but this can throw an error if you have 2 models with the same name.\n\nVery similar to dj...
[ 56 ]
[]
[]
[ "content_type", "django", "python" ]
stackoverflow_0005120071_content_type_django_python.txt
Q: Python html parsing I need to parse html emails that will be similar but not exactly the same. I will be looking for things like dates, amounts, vendors, ect., but depending on who the email came from, the markup will be different. How could I parse out those common things from lots of different html markup in pyt...
Python html parsing
I need to parse html emails that will be similar but not exactly the same. I will be looking for things like dates, amounts, vendors, ect., but depending on who the email came from, the markup will be different. How could I parse out those common things from lots of different html markup in python? Thanks for your sugg...
[ "You absolutely need to consider Beautiful Soup library. \n", "You can use Beautiful Soup to parse HTML in Python.\n", "BeautifulSoup or lxml are decent HTML parsers. BeautifulSoup is a bit more handy but has some odds and ends.\n" ]
[ 7, 2, 2 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0005120129_html_parsing_python.txt
Q: python module from source code - naming I am a python module-making novice. Following the spirit of this question, I installed Rx to validate some data from YAML files. Wanting to keep the whole party together, I simply put the whole git tree under site-packages. This provided me a (very simplified) tree to the...
python module from source code - naming
I am a python module-making novice. Following the spirit of this question, I installed Rx to validate some data from YAML files. Wanting to keep the whole party together, I simply put the whole git tree under site-packages. This provided me a (very simplified) tree to the python implementation of site-packages/Rx/py...
[ "A common pattern is to setup your project like this:\nProjectName/\n|-- bin/\n| `-- myscript\n|-- package_name/\n| |-- __init__.py\n| |-- rx.py\n`-- setup.py\n\nYour setup script then looks like:\n#!/usr/bin/env python\n\nfrom distutils.core import setup\n\nsetup(name='ProjectName',\n version='1.0',\n ...
[ 1, 0 ]
[]
[]
[ "installation", "module", "python" ]
stackoverflow_0005119452_installation_module_python.txt
Q: Baffled: Django "could not import app.views" but can import app, in WSGI? I'm having an odd Django problem, running Django with mod_wsgi. Django is finding urls.py, and then saying: ViewDoesNotExist: Could not import app.views. Error was: No module named views Bizarrely, if I have import app in the import state...
Baffled: Django "could not import app.views" but can import app, in WSGI?
I'm having an odd Django problem, running Django with mod_wsgi. Django is finding urls.py, and then saying: ViewDoesNotExist: Could not import app.views. Error was: No module named views Bizarrely, if I have import app in the import statements in urls.py I don't get an error (until it hits app.views as above), but i...
[ "Probably a circular dependency - something in views is importing another module, which itself is trying to import views.\n" ]
[ 3 ]
[ "Your web server is out of file handles. Reconfigure the WSGI app for daemon mode.\n" ]
[ -2 ]
[ "django", "django_views", "django_wsgi", "mod_wsgi", "python" ]
stackoverflow_0005119964_django_django_views_django_wsgi_mod_wsgi_python.txt
Q: Can anyone point me to good guides on using django.contrib.sites for multiple views on the same database? [Warning - python noob] I have read what I can find and got sites up and running with one "site" in the database. I'm not sure where to go from here. What is the right folder structure for the code for the sec...
Can anyone point me to good guides on using django.contrib.sites for multiple views on the same database?
[Warning - python noob] I have read what I can find and got sites up and running with one "site" in the database. I'm not sure where to go from here. What is the right folder structure for the code for the second site? It's going to re-use models (I assume - DRY) so presumably needs to use the same app folders - but th...
[ "Here's my preferred setup.\nexample1.com (with GA authentication) should be served by Apache (via mod_wsgi) and references some suite of Django Apps that use your only database.\nexample2.com should also be served by the the same Apache (via mod_wsgi) and references some suite of Django Apps that use your only dat...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005116755_django_python.txt
Q: AttributeError: '_MainProcess' object has no attribute '_exiting' I got an AttributeError: '_MainProcess' object has no attribute '_exiting' from a Python application. Unfortunately this code has to run Python 2.5 and therefore the processing module nowadays known as multiprocessing. What I was doing is to create...
AttributeError: '_MainProcess' object has no attribute '_exiting'
I got an AttributeError: '_MainProcess' object has no attribute '_exiting' from a Python application. Unfortunately this code has to run Python 2.5 and therefore the processing module nowadays known as multiprocessing. What I was doing is to create a Process with a Queue and to put an item in the queue from the main p...
[ "I am not sure why you would want to pickle a function in this case, if you really want to do that have a look at this answer: Is there an easy way to pickle a python function (or otherwise serialize its code)?\notherwise, this works for python 2.6 (I know you are looking for 2.5 but I don't have 2.5). I have repla...
[ 1 ]
[]
[]
[ "multiprocessing", "python", "python_2.5" ]
stackoverflow_0004155811_multiprocessing_python_python_2.5.txt